Yukang Chen commited on
Commit
8eb8c7a
·
1 Parent(s): caa3d11

Initial commit for qwen2-7b-longvila-256f-rl-reformated-0412

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.wandb filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ wandb/
2
+ logs/
3
+ *.wandb
4
+ *.tmp
5
+
__init__.py ADDED
File without changes
auto_processor.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import os
3
+ import os.path as osp
4
+ import warnings
5
+ from collections import defaultdict
6
+ from io import BytesIO
7
+ from typing import List, Optional, Union
8
+
9
+ import PIL.Image
10
+ import requests
11
+ import torch
12
+ from transformers import AutoConfig, AutoImageProcessor, AutoModel, AutoProcessor, AutoTokenizer
13
+ from transformers.feature_extraction_utils import BatchFeature
14
+ from transformers.image_utils import ImageInput, VideoInput
15
+ from transformers.processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
16
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
17
+ from transformers.utils import logging
18
+
19
+ from .constants import DEFAULT_IMAGE_TOKEN, MEDIA_TOKENS
20
+ from .media import Image, Video, extract_media
21
+ from .mm_utils import process_image, process_images
22
+ from .tokenizer_utils import tokenize_conversation
23
+
24
+
25
+ def to_rgb(pil_image: PIL.Image.Image) -> PIL.Image.Image:
26
+ if pil_image.mode == "RGBA":
27
+ white_background = PIL.Image.new("RGB", pil_image.size, (255, 255, 255))
28
+ white_background.paste(pil_image, mask=pil_image.split()[3]) # Use alpha channel as mask
29
+ return white_background
30
+ else:
31
+ return pil_image.convert("RGB")
32
+
33
+
34
+ def fetch_image(ele: dict[str, str | PIL.Image.Image], size_factor=None) -> PIL.Image.Image:
35
+ if "image" in ele:
36
+ image = ele["image"]
37
+ else:
38
+ image = ele["image_url"]
39
+ image_obj = None
40
+ if isinstance(image, PIL.Image.Image):
41
+ image_obj = image
42
+ elif image.startswith("http://") or image.startswith("https://"):
43
+ response = requests.get(image, stream=True)
44
+ image_obj = PIL.Image.open(BytesIO(response.content))
45
+ elif image.startswith("file://"):
46
+ image_obj = PIL.Image.open(image[7:])
47
+ elif image.startswith("data:image"):
48
+ if "base64," in image:
49
+ _, base64_data = image.split("base64,", 1)
50
+ data = base64.b64decode(base64_data)
51
+ image_obj = PIL.Image.open(BytesIO(data))
52
+ else:
53
+ image_obj = PIL.Image.open(image)
54
+ if image_obj is None:
55
+ raise ValueError(f"Unrecognized image input, support local path, http url, base64 and PIL.Image, got {image}")
56
+ image = to_rgb(image_obj)
57
+
58
+ return image
59
+
60
+
61
+ def fetch_image_url_or_fpath(url_or_fpath):
62
+ if url_or_fpath.startswith("http") or url_or_fpath.startswith("https"):
63
+ import tempfile
64
+
65
+ import requests
66
+
67
+ # Download the image to a temporary file
68
+ temp_dir = tempfile.mkdtemp()
69
+ temp_file = os.path.join(temp_dir, os.path.basename(url_or_fpath))
70
+
71
+ response = requests.get(url_or_fpath, stream=True)
72
+ response.raise_for_status()
73
+
74
+ with open(temp_file, "wb") as f:
75
+ for chunk in response.iter_content(chunk_size=8192):
76
+ f.write(chunk)
77
+
78
+ return temp_file
79
+ elif url_or_fpath.startswith("file://"):
80
+ fpath = url_or_fpath.replace("file://", "")
81
+ assert osp.exists(fpath), f"File {fpath} does not exist"
82
+ return fpath
83
+ elif osp.exists(url_or_fpath):
84
+ assert osp.isfile(url_or_fpath), f"File {url_or_fpath} does not exist"
85
+ return url_or_fpath
86
+ else:
87
+ raise ValueError(f"Unsupported image path: {url_or_fpath}")
88
+
89
+
90
+ def pad_fn(input_ids_list: List[torch.Tensor], padding_value=0, target_len=None, padding_side="left") -> torch.Tensor:
91
+ # tensor shape is (batch_size, seq_len)
92
+ max_len = max([ids.shape[1] for ids in input_ids_list])
93
+ if target_len is not None:
94
+ assert target_len >= max_len, "target_len must be greater than or equal to max_len"
95
+ max_len = target_len
96
+
97
+ new_input_ids_list = []
98
+ for i, input_ids in enumerate(input_ids_list):
99
+ pad_tensor = torch.ones_like(input_ids) * padding_value
100
+ curr_len = input_ids.shape[1]
101
+ pad_tensor = pad_tensor[:, : max_len - curr_len]
102
+ if padding_side == "right":
103
+ input_ids = torch.cat((input_ids, pad_tensor), dim=1)
104
+ else:
105
+ input_ids = torch.cat((pad_tensor, input_ids), dim=1)
106
+ new_input_ids_list.append(input_ids)
107
+ return torch.cat(new_input_ids_list, dim=0)
108
+
109
+
110
+ def extract_value_from_conv(chat):
111
+ value = []
112
+ if isinstance(chat["content"], str):
113
+ # vila_chat["value"].append(chat["content"])
114
+ value.append(chat["content"])
115
+ return value
116
+
117
+ # otherwise, it's a list of content
118
+ for content in chat["content"]:
119
+ if content["type"] == "image":
120
+ if "path" in content:
121
+ # VILA style, can be either filepath or http url
122
+ value.append(Image(fetch_image_url_or_fpath(content["path"])))
123
+ elif "image" in content:
124
+ # Qwen style
125
+ value.append(Image(fetch_image_url_or_fpath(content["image"])))
126
+ elif "image_pil" in content:
127
+ # Qwen style
128
+ assert isinstance(content["image_pil"], PIL.Image.Image), f"Type of {media_key} must be PIL.Image.Image"
129
+ value.append(content["image_pil"])
130
+ else:
131
+ raise ValueError(f"Type = `image` , but no `path` or `image` in | {content=}, {conversation=}")
132
+ elif content["type"] == "video":
133
+ if "video" in content:
134
+ # Qwen style
135
+ value.append(Video(fetch_image_url_or_fpath(content["video"])))
136
+ else:
137
+ raise ValueError(f"Type = `video` , but no `video` in | {content=}, {conversation=}")
138
+ elif content["type"] == "text":
139
+ value.append(content["text"])
140
+ # NOTE(ligeng): video supports are needed here
141
+ else:
142
+ raise ValueError(f"Unsupported content type: {content['type']}")
143
+ return value
144
+
145
+
146
+ class VILAProcessorKwargs(ProcessingKwargs, total=False):
147
+ _defaults = {
148
+ "text_kwargs": {
149
+ "padding": False,
150
+ },
151
+ }
152
+
153
+
154
+ class VILAProcessor(ProcessorMixin):
155
+ # attributes = ["image_processor", "tokenizer"]
156
+ attributes = []
157
+ # valid_kwargs = ["chat_template"]
158
+ valid_kwargs = []
159
+ # image_processor_class = "VILAImageProcessor"
160
+ # tokenizer_class = ("VILATokenizer", "VILATokenizerFast")
161
+
162
+ def __init__(self, image_processor=None, tokenizer=None, chat_template=None, config=None, padding_side="left", **kwargs):
163
+ self.image_token = MEDIA_TOKENS["image"]
164
+ self.video_token = MEDIA_TOKENS["video"]
165
+ self.config = config
166
+ self.image_processor = image_processor
167
+ self.tokenizer = tokenizer
168
+ self.padding_side = padding_side
169
+
170
+ # This is a special setting for Qwen.
171
+ # self.pad_token_id = tokenizer.pad_token_id
172
+ self.pad_token_id = self.tokenizer("<|endoftext|>").input_ids[0] # 151643
173
+ self.eos_token_id = self.tokenizer.eos_token_id
174
+
175
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
176
+
177
+ @staticmethod
178
+ def extract_vision_info(conversations: list[dict] | list[list[dict]]) -> list[dict]:
179
+ """
180
+ referernce from qwen_vl_utils
181
+ """
182
+ vision_infos = []
183
+ if isinstance(conversations[0], dict):
184
+ conversations = [conversations]
185
+ for conversation in conversations:
186
+ for message in conversation:
187
+ if isinstance(message["content"], list):
188
+ for ele in message["content"]:
189
+ if (
190
+ "image" in ele
191
+ or "image_url" in ele
192
+ or "video" in ele
193
+ or ele["type"] in ("image", "image_url", "video")
194
+ ):
195
+ vision_infos.append(ele)
196
+ return vision_infos
197
+
198
+ @staticmethod
199
+ def process_vision_info(
200
+ conversations: list[dict] | list[list[dict]],
201
+ return_video_kwargs: bool = False,
202
+ ) -> tuple[list[PIL.Image.Image] | None, list[torch.Tensor | list[PIL.Image.Image]] | None, Optional[dict]]:
203
+ """
204
+ referernce from qwen_vl_utils
205
+ NVILA does not depend on the function, but the interface is the same.
206
+ """
207
+ vision_infos = extract_vision_info(conversations)
208
+ ## Read images or videos
209
+ image_inputs = []
210
+ video_inputs = []
211
+ video_sample_fps_list = []
212
+ for vision_info in vision_infos:
213
+ if "image" in vision_info or "image_url" in vision_info:
214
+ image_inputs.append(fetch_image(vision_info))
215
+ elif "video" in vision_info:
216
+ video_input, video_sample_fps = fetch_video(vision_info, return_video_sample_fps=True)
217
+ video_sample_fps_list.append(video_sample_fps)
218
+ video_inputs.append(video_input)
219
+ else:
220
+ raise ValueError("image, image_url or video should in content.")
221
+ if len(image_inputs) == 0:
222
+ image_inputs = None
223
+ if len(video_inputs) == 0:
224
+ video_inputs = None
225
+ if return_video_kwargs:
226
+ return image_inputs, video_inputs, {"fps": video_sample_fps_list}
227
+ return image_inputs, video_inputs
228
+
229
+ @staticmethod
230
+ def move_data_to_device(cls, prompt_inputs):
231
+ def _move_data_to_device(item):
232
+ # wrap function grpo trainer _prepare_input
233
+ kwargs = {"device": cls.args.device}
234
+ if cls.is_deepspeed_enabled and (torch.is_floating_point(item) or torch.is_complex(item)):
235
+ kwargs.update({"dtype": cls.accelerator.state.deepspeed_plugin.hf_ds_config.dtype()})
236
+ return item.to(**kwargs)
237
+
238
+ prompt_inputs.input_ids = _move_data_to_device(prompt_inputs.input_ids)
239
+ prompt_inputs.attention_mask = _move_data_to_device(prompt_inputs.attention_mask)
240
+ if "image" in prompt_inputs.media:
241
+ prompt_inputs.media["image"] = [_move_data_to_device(img) for img in prompt_inputs.media["image"]]
242
+ return prompt_inputs
243
+
244
+ @classmethod
245
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
246
+ padding_side = kwargs.get("padding_side", "left")
247
+ if os.path.isdir(pretrained_model_name_or_path):
248
+ pretrained_model_name_or_path = pretrained_model_name_or_path
249
+ else:
250
+ print(f"pretrained_model_name_or_path {pretrained_model_name_or_path} is not a directory, downloading")
251
+ from huggingface_hub import snapshot_download
252
+ pretrained_model_name_or_path = snapshot_download(pretrained_model_name_or_path)
253
+
254
+ image_processor = AutoImageProcessor.from_pretrained(
255
+ osp.join(pretrained_model_name_or_path, "vision_tower"), trust_remote_code=True
256
+ )
257
+ tokenizer = AutoTokenizer.from_pretrained(
258
+ osp.join(pretrained_model_name_or_path, "llm"), trust_remote_code=True
259
+ )
260
+ config = AutoConfig.from_pretrained(pretrained_model_name_or_path, trust_remote_code=True)
261
+ return cls(image_processor=image_processor, tokenizer=tokenizer, config=config, padding_side=padding_side)
262
+
263
+ def __repr__(self):
264
+ # NOTE(ligeng): hard coded image_processor to avoid serialization error. Dirty fix
265
+ return f"VILAProcessor(image_processor=SigLip, tokenizer={self.tokenizer}, config={self.config})"
266
+
267
+ def __call__(
268
+ self,
269
+ conversation=None,
270
+ **kwargs: Unpack[VILAProcessorKwargs],
271
+ ) -> BatchFeature:
272
+ """
273
+ The `conv` will be look like
274
+ [
275
+ {
276
+ 'from': 'human',
277
+ 'value': [
278
+ <transformers_modules.NVILA-Lite-2B-hf-preview.media.Image object at 0x154e68e4c460>,
279
+ 'What are the common elements in these pictures?'
280
+ ]
281
+ }
282
+ ]
283
+ and `conversation` will be a list of such `conv`s
284
+ """
285
+ if kwargs.get("text", None) is not None:
286
+ conversation = kwargs.get("text")
287
+ assert conversation is not None, "`conversation` or `text` is required"
288
+ padding_side = kwargs.get("padding_side", self.padding_side)
289
+
290
+ input_ids_list = []
291
+ attention_mask = []
292
+ media = defaultdict(list)
293
+ media_config = defaultdict(dict)
294
+ for conv in conversation:
295
+ feat = self.__single_call__(conv, **kwargs)
296
+ input_ids_list.append(feat.input_ids)
297
+ attention_mask.append(feat.attention_mask)
298
+ for name in feat.media:
299
+ media[name] += feat.media[name]
300
+ for name in feat.media_config:
301
+ media_config[name].update(feat.media_config[name])
302
+
303
+ # pad the input_ids to batchfy
304
+ input_ids = pad_fn(
305
+ input_ids_list,
306
+ padding_value=self.pad_token_id,
307
+ padding_side=padding_side,
308
+ )
309
+ # ignore the pad token in the attention mask
310
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
311
+ attention_mask[input_ids == self.pad_token_id] = False
312
+ # print("[DEBUGAAA]", self.pad_token_id, self.tokenizer.pad_token_id); exit(0)
313
+ input_texts = self.tokenizer.batch_decode(input_ids)
314
+ bdata = BatchFeature(
315
+ data={
316
+ # "input_texts": input_texts,
317
+ "input_ids": input_ids,
318
+ "attention_mask": attention_mask,
319
+ "media": media,
320
+ "media_config": media_config,
321
+ }
322
+ )
323
+ # NOTE: hard coded to cuda
324
+ # bdata.input_ids = bdata.input_ids.cuda()
325
+ # bdata.attention_mask = bdata.attention_mask.cuda()
326
+ # bdata.media["image"] = [img.cuda() for img in bdata.media["image"]]
327
+ return bdata
328
+
329
+ def __single_call__(
330
+ self,
331
+ conversation,
332
+ images: ImageInput = None,
333
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
334
+ videos: VideoInput = None,
335
+ **kwargs: Unpack[VILAProcessorKwargs],
336
+ ) -> BatchFeature:
337
+ # TODO: should be merged with llava_arch.py/generate_content()
338
+ # TODO (extract and preprocess should be done together, as the preprocess of image and video can be different, i.e. when dynamic res is used)
339
+ conversation = copy.deepcopy(conversation)
340
+ media = extract_media(conversation, self.config)
341
+ # Process media
342
+ media_config = defaultdict(dict)
343
+ for name in media:
344
+ if name == "image":
345
+ if len(media["image"]) == 1 and self.config.image_aspect_ratio in ["dynamic", "dynamic_s2"]:
346
+ self.config.image_processor = self.image_processor
347
+ if self.config.image_aspect_ratio == "dynamic":
348
+ images = process_image(media["image"][0], self.config, None, enable_dynamic_res=True).half()
349
+ # print("DEBUG", len(images)); input()
350
+ # NOTE: this only works for images appears at the first conversation
351
+ conversation[0]["value"] = conversation[0]["value"].replace(
352
+ DEFAULT_IMAGE_TOKEN, f"{DEFAULT_IMAGE_TOKEN}\n" * images.shape[0]
353
+ )
354
+ else:
355
+ if type(self.config.s2_scales) is str:
356
+ self.config.s2_scales = list(map(int, self.config.s2_scales.split(",")))
357
+ images, block_sizes = process_image(
358
+ media["image"][0], self.config, None, enable_dynamic_s2=True
359
+ )
360
+ images = images.half()
361
+ media_config[name]["block_sizes"] = [block_sizes]
362
+ else:
363
+ images = process_images(media["image"], self.vision_tower.image_processor, self.config).half()
364
+ media[name] = [image for image in images]
365
+ elif name == "video":
366
+ media[name] = [
367
+ process_images(images, self.image_processor, self.config).half()
368
+ for images in media[name]
369
+ ]
370
+ else:
371
+ raise ValueError(f"Unsupported media type: {name}")
372
+
373
+ inputs = tokenize_conversation(conversation, self.tokenizer, add_generation_prompt=True, return_ids_only=False)
374
+ input_ids = inputs.input_ids[0].unsqueeze(0) #.cuda()
375
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
376
+ return BatchFeature(
377
+ data={
378
+ "input_ids": input_ids,
379
+ "attention_mask": attention_mask,
380
+ "media": media,
381
+ "media_config": media_config,
382
+ }
383
+ )
384
+
385
+ def batch_decode(self, *args, **kwargs):
386
+ """
387
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
388
+ refer to the docstring of this method for more information.
389
+ """
390
+ return self.tokenizer.batch_decode(*args, **kwargs)
391
+
392
+ def decode(self, *args, **kwargs):
393
+ """
394
+ This method forwards all its arguments to Qwen2TokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
395
+ the docstring of this method for more information.
396
+ """
397
+ return self.tokenizer.decode(*args, **kwargs)
398
+
399
+ def post_process_image_text_to_text(self, generated_outputs):
400
+ """
401
+ Post-process the output of the model to decode the text.
402
+
403
+ Args:
404
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
405
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
406
+ or `(sequence_length,)`.
407
+
408
+ Returns:
409
+ `List[str]`: The decoded text.
410
+ """
411
+ return self.tokenizer.batch_decode(
412
+ generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False
413
+ )
414
+
415
+ @property
416
+ def model_input_names(self):
417
+ tokenizer_input_names = self.tokenizer.model_input_names
418
+ image_processor_input_names = self.image_processor.model_input_names
419
+ return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
420
+
421
+ def convert_gpt_conv_to_vila_conv(self, conversation):
422
+ vila_conv = []
423
+ for chat in conversation:
424
+ vila_chat = {"from": "", "value": []}
425
+ if chat["role"] in ("user", "system"):
426
+ # user allows to input image and text
427
+ vila_chat["from"] = "human" if chat["role"] == "user" else "system"
428
+ vila_chat["value"] = extract_value_from_conv(chat)
429
+ elif chat["role"] == "assistant":
430
+ vila_chat["from"] = "gpt"
431
+ vila_chat["value"] = extract_value_from_conv(chat)
432
+ else:
433
+ raise ValueError(f"Unsupported role: {chat['role']} in chat {chat}")
434
+ vila_conv.append(vila_chat)
435
+
436
+ return vila_conv
437
+
438
+ def apply_chat_template(self, conversation, add_generation_prompt=True, **kwargs):
439
+ return self.convert_gpt_conv_to_vila_conv(conversation)
440
+
441
+
442
+ if __name__ == "__main__":
443
+ # gpt style: user, assistant
444
+ # vila style: human, gpt
445
+ gpt_conv = [
446
+ {
447
+ "role": "user",
448
+ "content": [
449
+ {"type": "image", "path": "demo_images/demo_img_1.png"},
450
+ {"type": "text", "text": "Describe this image."},
451
+ ],
452
+ }
453
+ ]
454
+
455
+ llavaconv = [
456
+ {
457
+ "from": "human",
458
+ "value": [
459
+ PIL.Image.open("demo_images/demo_img_1.png"),
460
+ "Describe this image.",
461
+ ],
462
+ }
463
+ ]
464
+
465
+ processor = AutoProcessor.from_pretrained(output_dir, trust_remote_code=True)
466
+ inputs = processor.apply_chat_template(conversation=gpt_conv, padding=True, return_tensors="pt")
467
+ # model = llava.load("Efficient-Large-Model/qwen25_2B_3x3-sft").cuda()
468
+ # print(model)
469
+ model_path = "NVILA-Lite-2B-hf-preview"
470
+ model = AutoModel.from_pretrained(model_path, trust_remote_code=True, device_map="auto")
471
+ # res = model.generate_content(["how are you today?"])
472
+ # print(model.config)
473
+ # print(model.tokenizer)
474
+ # print(res)
475
+
476
+ processor = VILAProcessor(
477
+ config=model.config,
478
+ image_processor=model.vision_tower.image_processor,
479
+ tokenizer=model.tokenizer,
480
+ )
481
+
482
+ # TODO: add padding, return_tensors,
483
+ inputs = processor(conversation=llavaconv, padding=True, return_tensors="pt")
484
+ print(inputs.keys(), inputs.input_ids.shape, [_.shape for _ in inputs.image])
485
+ print("vila conv pass")
486
+
487
+ inputs = processor.apply_chat_template(conversation=gpt_conv, padding=True, return_tensors="pt")
488
+ print(inputs.keys(), inputs.input_ids.shape, [_.shape for _ in inputs.image])
489
+ print("gpt conv pass")
490
+
491
+ output_ids = model.generate(
492
+ input_ids=inputs.input_ids,
493
+ media={
494
+ "image": inputs.image,
495
+ },
496
+ media_config={"image": {}},
497
+ generation_config=model.generation_config,
498
+ max_new_tokens=100,
499
+ )
500
+ print(output_ids)
base_projector.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ import re
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ from transformers import AutoConfig, AutoModel, PretrainedConfig, PreTrainedModel
22
+
23
+
24
+ class IdentityMap(nn.Module):
25
+ def __init__(self):
26
+ super().__init__()
27
+
28
+ def forward(self, x, *args, **kwargs):
29
+ return x
30
+
31
+ @property
32
+ def config(self):
33
+ return {"mm_projector_type": "identity"}
34
+
35
+
36
+ class SimpleResBlock(nn.Module):
37
+ def __init__(self, channels):
38
+ super().__init__()
39
+ self.pre_norm = nn.LayerNorm(channels)
40
+
41
+ self.proj = nn.Sequential(nn.Linear(channels, channels), nn.GELU(), nn.Linear(channels, channels))
42
+
43
+ def forward(self, x):
44
+ x = self.pre_norm(x)
45
+ return x + self.proj(x)
46
+
47
+
48
+ class DownSampleBlock(nn.Module):
49
+ def forward(self, x):
50
+ vit_embeds = x
51
+ h = w = int(vit_embeds.shape[1] ** 0.5)
52
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
53
+ vit_embeds = self.flat_square(vit_embeds)
54
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
55
+ return vit_embeds
56
+
57
+ def flat_square(self, x):
58
+ n, w, h, c = x.size()
59
+ if w % 2 == 1:
60
+ x = torch.concat([x, torch.zeros((n, 1, h, c), dtype=x.dtype).to(x.device)], dim=1).contiguous()
61
+ n, w, h, c = x.size()
62
+ if h % 2 == 1:
63
+ x = torch.concat([x, torch.zeros((n, w, 1, c), dtype=x.dtype).to(x.device)], dim=2).contiguous()
64
+ n, w, h, c = x.size()
65
+ x = x.contiguous()
66
+ x = x.view(n, w, int(h / 2), int(c * 2))
67
+ x = x.permute(0, 2, 1, 3).contiguous()
68
+ x = x.view(n, int(h / 2), int(w / 2), int(c * 4))
69
+ x = x.permute(0, 2, 1, 3).contiguous()
70
+ return x
71
+
72
+
73
+ class DownSample2x2BlockFix(nn.Module):
74
+ def forward(self, x):
75
+ vit_embeds = x
76
+ h = w = int(vit_embeds.shape[1] ** 0.5)
77
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
78
+ vit_embeds = flat_square_2x2(vit_embeds)
79
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
80
+ return vit_embeds
81
+
82
+
83
+ def flat_square_2x2(x):
84
+ n, w, h, c = x.size()
85
+ if w % 2 == 1:
86
+ x = torch.concat([x, torch.zeros((n, 1, h, c), dtype=x.dtype).to(x.device)], dim=1).contiguous()
87
+ n, w, h, c = x.size()
88
+ x = x.contiguous()
89
+ if h % 2 == 1:
90
+ x = torch.concat([x, torch.zeros((n, w, 1, c), dtype=x.dtype).to(x.device)], dim=2).contiguous()
91
+ n, w, h, c = x.size()
92
+ x = x.view(n, w, int(h / 2), int(c * 2))
93
+ x = x.permute(0, 2, 1, 3).contiguous()
94
+ x = x.view(n, int(h / 2), int(w / 2), int(c * 4))
95
+ x = x.permute(0, 2, 1, 3).contiguous()
96
+ return x
97
+
98
+
99
+ class DownSample3x3BlockFix(nn.Module):
100
+ def forward(self, x):
101
+ vit_embeds = x
102
+ h = w = int(vit_embeds.shape[1] ** 0.5)
103
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
104
+ vit_embeds = flat_square_3x3(vit_embeds)
105
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
106
+ return vit_embeds
107
+
108
+
109
+ def flat_square_3x3(x):
110
+ n, w, h, c = x.size()
111
+ if w % 3 != 0:
112
+ x = torch.concat([x, torch.zeros((n, 3 - (w % 3), h, c), dtype=x.dtype).to(x.device)], dim=1).contiguous()
113
+ n, w, h, c = x.size()
114
+ x = x.contiguous()
115
+ if h % 3 != 0:
116
+ x = torch.concat([x, torch.zeros((n, w, 3 - (h % 3), c), dtype=x.dtype).to(x.device)], dim=2).contiguous()
117
+ n, w, h, c = x.size()
118
+ x = x.view(n, w, int(h / 3), int(c * 3))
119
+ x = x.permute(0, 2, 1, 3).contiguous()
120
+ x = x.view(n, int(h / 3), int(w / 3), int(c * 9))
121
+ x = x.permute(0, 2, 1, 3).contiguous()
122
+ return x
123
+
124
+
125
+ class MultimodalProjectorConfig(PretrainedConfig):
126
+ model_type = "v2l_projector"
127
+
128
+ def __init__(self, mm_projector_type: str = None, **kwargs):
129
+ super().__init__()
130
+ self.mm_projector_type = mm_projector_type
131
+
132
+
133
+ class MultimodalProjector(PreTrainedModel):
134
+ config_class = MultimodalProjectorConfig
135
+
136
+ def __init__(self, mm_projector_cfg: MultimodalProjectorConfig, config: PretrainedConfig):
137
+ super().__init__(mm_projector_cfg)
138
+ mm_projector_type = mm_projector_cfg.mm_projector_type
139
+ self.downsample_rate = 1
140
+ if mm_projector_type == "identity":
141
+ self.layers = IdentityMap()
142
+ elif mm_projector_type == "linear":
143
+ self.layers = nn.Linear(config.mm_hidden_size, config.hidden_size)
144
+ elif mm_projector_type == "mlp_downsample":
145
+ self.layers = nn.Sequential(
146
+ DownSampleBlock(),
147
+ nn.LayerNorm(config.mm_hidden_size * 4),
148
+ nn.Linear(config.mm_hidden_size * 4, config.hidden_size),
149
+ nn.GELU(),
150
+ nn.Linear(config.hidden_size, config.hidden_size),
151
+ )
152
+ self.downsample_rate = 2
153
+ elif mm_projector_type == "mlp_downsample_2x2_fix":
154
+ self.layers = nn.Sequential(
155
+ DownSample2x2BlockFix(),
156
+ nn.LayerNorm(config.mm_hidden_size * 4),
157
+ nn.Linear(config.mm_hidden_size * 4, config.hidden_size),
158
+ nn.GELU(),
159
+ nn.Linear(config.hidden_size, config.hidden_size),
160
+ )
161
+ self.downsample_rate = 2
162
+ elif mm_projector_type == "mlp_downsample_3x3_fix":
163
+ self.layers = nn.Sequential(
164
+ DownSample3x3BlockFix(),
165
+ nn.LayerNorm(config.mm_hidden_size * 9),
166
+ nn.Linear(config.mm_hidden_size * 9, config.mm_hidden_size * 3),
167
+ nn.GELU(),
168
+ nn.LayerNorm(config.mm_hidden_size * 3),
169
+ nn.Linear(config.mm_hidden_size * 3, config.hidden_size),
170
+ nn.GELU(),
171
+ nn.Linear(config.hidden_size, config.hidden_size),
172
+ )
173
+ self.downsample_rate = 3
174
+ elif mm_projector_type == "mlp_downsample_3x3_s2":
175
+ self.layers = nn.Sequential(
176
+ DownSample3x3BlockFix(),
177
+ nn.LayerNorm(config.mm_hidden_size * 9),
178
+ nn.Linear(config.mm_hidden_size * 9, config.mm_hidden_size * 3),
179
+ nn.GELU(),
180
+ nn.LayerNorm(config.mm_hidden_size * 3),
181
+ nn.Linear(config.mm_hidden_size * 3, config.mm_hidden_size),
182
+ nn.GELU(),
183
+ nn.LayerNorm(config.mm_hidden_size),
184
+ nn.Linear(config.mm_hidden_size, config.mm_hidden_size // 3),
185
+ nn.GELU(),
186
+ nn.LayerNorm(config.mm_hidden_size // 3),
187
+ nn.Linear(config.mm_hidden_size // 3, config.hidden_size),
188
+ nn.GELU(),
189
+ nn.Linear(config.hidden_size, config.hidden_size),
190
+ )
191
+ elif mm_projector_type == "mlp_downsample_3x3_s2_new":
192
+ self.layers = nn.Sequential(
193
+ DownSample3x3BlockFix(),
194
+ nn.LayerNorm(config.mm_hidden_size * 9),
195
+ nn.Linear(config.mm_hidden_size * 9, config.mm_hidden_size * 4),
196
+ nn.GELU(),
197
+ nn.LayerNorm(config.mm_hidden_size * 4),
198
+ nn.Linear(config.mm_hidden_size * 4, config.mm_hidden_size * 2),
199
+ nn.GELU(),
200
+ nn.LayerNorm(config.mm_hidden_size * 2),
201
+ nn.Linear(config.mm_hidden_size * 2, config.mm_hidden_size),
202
+ nn.GELU(),
203
+ nn.LayerNorm(config.mm_hidden_size),
204
+ nn.Linear(config.mm_hidden_size, config.mm_hidden_size // 3),
205
+ nn.GELU(),
206
+ nn.LayerNorm(config.mm_hidden_size // 3),
207
+ nn.Linear(config.mm_hidden_size // 3, config.hidden_size),
208
+ nn.GELU(),
209
+ nn.Linear(config.hidden_size, config.hidden_size),
210
+ )
211
+ else:
212
+ mlp_gelu_match = re.match(r"^mlp(\d+)x_gelu$", mm_projector_type)
213
+ if mlp_gelu_match:
214
+ mlp_depth = int(mlp_gelu_match.group(1))
215
+ modules = [nn.Linear(config.mm_hidden_size, config.hidden_size)]
216
+ for _ in range(1, mlp_depth):
217
+ modules.append(nn.GELU())
218
+ modules.append(nn.Linear(config.hidden_size, config.hidden_size))
219
+ self.layers = nn.Sequential(*modules)
220
+ else:
221
+ raise ValueError(f"Unknown projector type: {mm_projector_type}")
222
+
223
+ def forward(self, x, *args, **kwargs):
224
+ return self.layers(x)
225
+
226
+
227
+ # AutoConfig.register("v2l_projector", MultimodalProjectorConfig)
228
+ # AutoModel.register(MultimodalProjectorConfig, MultimodalProjector)
builder.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ import math
18
+ import os
19
+ import os.path as osp
20
+ import warnings
21
+ from dataclasses import asdict
22
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
23
+
24
+ import torch
25
+ import transformers
26
+ from huggingface_hub import file_exists, repo_exists
27
+ from huggingface_hub.utils import HFValidationError
28
+ from transformers import (
29
+ AutoConfig,
30
+ AutoModelForCausalLM,
31
+ AutoTokenizer,
32
+ PretrainedConfig,
33
+ PreTrainedModel,
34
+ PreTrainedTokenizer,
35
+ )
36
+ from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled
37
+
38
+ # from .conversation import *
39
+ from .conversation import SeparatorStyle, default_conversation
40
+
41
+ SENTINEL_TOKEN = "<vila/sentinel>"
42
+ MEDIA_TOKENS = {
43
+ "image": "<image>",
44
+ "video": "<vila/video>",
45
+ }
46
+
47
+ # from llava.model.utils import packing
48
+ # from llava.utils.logging import logger
49
+ # from llava.utils.tokenizer import infer_stop_tokens
50
+
51
+ DUMMY_CONVERSATION = [
52
+ {"from": "human", "value": "question"},
53
+ {"from": "gpt", "value": "answer"},
54
+ ] * 10
55
+
56
+
57
+ def tokenizer_image_token(prompt, tokenizer, return_tensors=None):
58
+ return tokenizer(prompt, return_tensors=return_tensors).input_ids[0]
59
+
60
+
61
+ def has_tokenizer(repo_id_or_path: str) -> bool:
62
+ # Check if the tokenizer is in a local directory
63
+ if osp.exists(osp.join(repo_id_or_path, "tokenizer_config.json")):
64
+ return True
65
+
66
+ # Check if the tokenizer is in a Hugging Face Hub repo
67
+ try:
68
+ return repo_exists(repo_id_or_path) and file_exists(repo_id_or_path, "tokenizer_config.json")
69
+ except HFValidationError:
70
+ return False
71
+
72
+
73
+ def _maybe_add_sentinel_token(tokenizer: transformers.PreTrainedTokenizer) -> None:
74
+ if not hasattr(tokenizer, "sentinel_token"):
75
+ tokenizer.add_tokens([SENTINEL_TOKEN], special_tokens=True)
76
+ tokenizer.sentinel_token = SENTINEL_TOKEN
77
+ tokenizer.sentinel_token_id = tokenizer.convert_tokens_to_ids(SENTINEL_TOKEN)
78
+
79
+
80
+ def tokenize_conversation_legacy(
81
+ messages: Sequence[Dict[str, str]],
82
+ tokenizer: transformers.PreTrainedTokenizer,
83
+ add_generation_prompt: bool = False,
84
+ overrides: Optional[Dict[str, str]] = None,
85
+ no_system_prompt: bool = False,
86
+ ) -> torch.Tensor:
87
+ conv = default_conversation.copy()
88
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
89
+
90
+ if no_system_prompt:
91
+ conv.system = ""
92
+
93
+ # Skip the first message if it is not from human
94
+ if messages[0]["from"] != "human":
95
+ messages = messages[1:]
96
+
97
+ # Add a generation prompt if needed
98
+ if add_generation_prompt:
99
+ messages.append({"from": "gpt", "value": None})
100
+
101
+ conv.messages = []
102
+ for turn, message in enumerate(messages):
103
+ role = roles[message["from"]]
104
+ assert role == conv.roles[turn % 2]
105
+ if overrides is not None and message["from"] in overrides:
106
+ conv.append_message(role, overrides[message["from"]])
107
+ else:
108
+ conv.append_message(role, message["value"])
109
+
110
+ return tokenizer_image_token(conv.get_prompt(), tokenizer, return_tensors="pt")
111
+
112
+
113
+ def tokenize_conversation(
114
+ messages: Sequence[Dict[str, str]],
115
+ tokenizer: transformers.PreTrainedTokenizer,
116
+ add_generation_prompt: bool = False,
117
+ overrides: Optional[Dict[str, str]] = None,
118
+ no_system_prompt: bool = False,
119
+ ) -> torch.Tensor:
120
+ # Normalize the conversation before tokenization
121
+ for message in messages:
122
+ message["value"] = message["value"].strip()
123
+
124
+ if default_conversation.sep_style != SeparatorStyle.AUTO:
125
+ return tokenize_conversation_legacy(
126
+ messages,
127
+ tokenizer,
128
+ add_generation_prompt=add_generation_prompt,
129
+ overrides=overrides,
130
+ no_system_prompt=no_system_prompt,
131
+ )
132
+
133
+ conversation = []
134
+ for m in messages:
135
+ message = {}
136
+ if m["from"] == "human":
137
+ message["role"] = "user"
138
+ elif m["from"] == "gpt":
139
+ message["role"] = "assistant"
140
+ else:
141
+ raise ValueError(f"Unexpected sender '{m['from']}' in conversation entry.")
142
+
143
+ message["content"] = m["value"]
144
+ if overrides is not None and m["from"] in overrides:
145
+ message["content"] = overrides[m["from"]]
146
+ conversation.append(message)
147
+
148
+ if no_system_prompt:
149
+ conversation = [{"role": "system", "content": ""}] + conversation
150
+
151
+ text = tokenizer.apply_chat_template(
152
+ conversation,
153
+ add_generation_prompt=add_generation_prompt,
154
+ tokenize=False,
155
+ )
156
+ return tokenizer_image_token(text, tokenizer, return_tensors="pt")
157
+
158
+
159
+ def infer_stop_tokens(tokenizer: transformers.PreTrainedTokenizer) -> List[str]:
160
+ _maybe_add_sentinel_token(tokenizer)
161
+ template = tokenize_conversation(DUMMY_CONVERSATION, tokenizer, overrides={"gpt": SENTINEL_TOKEN})
162
+
163
+ stop_tokens = {tokenizer.eos_token}
164
+ for k in range(template.size(0) - 1):
165
+ if template[k] == tokenizer.sentinel_token_id:
166
+ stop_token = tokenizer.decode(template[k + 1])
167
+ stop_tokens.add(stop_token)
168
+ return list(stop_tokens)
169
+
170
+
171
+ def context_length_extension(config):
172
+ orig_ctx_len = getattr(config, "max_position_embeddings", None)
173
+ model_max_length = getattr(config, "model_max_length", None)
174
+ if orig_ctx_len and model_max_length > orig_ctx_len:
175
+ print(f"Scaling RoPE from {orig_ctx_len} to {model_max_length}")
176
+ scaling_factor = float(math.ceil(model_max_length / orig_ctx_len))
177
+ config.rope_scaling = {"type": "linear", "factor": scaling_factor}
178
+ return config
179
+
180
+
181
+ def build_llm_and_tokenizer(
182
+ model_name_or_path: str,
183
+ config: PretrainedConfig,
184
+ attn_implementation=None,
185
+ model_max_length=None,
186
+ *args,
187
+ **kwargs,
188
+ ) -> Tuple[PreTrainedModel, PreTrainedTokenizer]:
189
+ # print(model_name_or_path)
190
+ llm_cfg = AutoConfig.from_pretrained(model_name_or_path)
191
+ llm_cfg._attn_implementation = attn_implementation
192
+ llm_cfg.model_max_length = model_max_length
193
+ if model_max_length is not None:
194
+ context_length_extension(llm_cfg)
195
+
196
+ # Quantization related
197
+ quantization_restore_from_checkpoint = False
198
+
199
+ if quantization_restore_from_checkpoint:
200
+ fp8_model_name_or_path = kwargs.pop("fp8_llm_cfg", None)
201
+
202
+ llm = AutoModelForCausalLM.from_pretrained(
203
+ fp8_model_name_or_path, config=llm_cfg, torch_dtype=eval(config.model_dtype), *args, **kwargs
204
+ )
205
+ else:
206
+ if is_deepspeed_zero3_enabled():
207
+ # NOTE: found by wei, need to pop out device_map when using zero3
208
+ kwargs.pop("device_map")
209
+ llm = AutoModelForCausalLM.from_pretrained(
210
+ model_name_or_path, config=llm_cfg, torch_dtype=eval(config.model_dtype), *args, **kwargs
211
+ )
212
+ # NOTE(ligeng): not sure whether it affects the training
213
+ # packing.patch(llm)
214
+
215
+ # Locate the tokenizer.
216
+ llm_path = model_name_or_path
217
+ if not has_tokenizer(llm_path):
218
+ llm_path = osp.join(llm_path, "llm")
219
+ if not has_tokenizer(llm_path):
220
+ raise ValueError(f"Cannot find tokenizer in {llm_path}.")
221
+
222
+ tokenizer = AutoTokenizer.from_pretrained(llm_path, padding_side="right", use_fast=True, legacy=False)
223
+ if model_max_length is not None:
224
+ tokenizer.model_max_length = model_max_length
225
+
226
+ # Load chat template if specified.
227
+ if getattr(config, "chat_template", None) is not None:
228
+ print(f"Using chat template: {config.chat_template}")
229
+ fpath = os.path.join(os.path.dirname(__file__), "chat_templates", f"{config.chat_template}.jinja")
230
+ if not os.path.exists(fpath):
231
+ fpath = os.path.join(os.path.dirname(model_name_or_path), f"{config.chat_template}.jinja")
232
+ with open(fpath) as fd:
233
+ chat_template = fd.read()
234
+ tokenizer.chat_template = chat_template.replace(" ", "").replace("\n", "")
235
+
236
+ # Set stop tokens for the tokenizer
237
+ tokenizer.stop_tokens = infer_stop_tokens(tokenizer)
238
+ tokenizer.stop_token_ids = tokenizer.convert_tokens_to_ids(tokenizer.stop_tokens)
239
+
240
+ # Add media tokens to the tokenizer
241
+ tokenizer.media_tokens = MEDIA_TOKENS
242
+ tokenizer.media_token_ids = {}
243
+ for name, token in MEDIA_TOKENS.items():
244
+ tokenizer.add_tokens([token], special_tokens=True)
245
+ tokenizer.media_token_ids[name] = tokenizer.convert_tokens_to_ids(token)
246
+
247
+ # TODO(ligeng): is this necessary for llava?
248
+ config.hidden_size = llm.config.hidden_size
249
+ return llm, tokenizer
config.json ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_attn_implementation_autoset": true,
3
+ "_name_or_path": "./output/qwen2-7b-longvila-256f",
4
+ "architectures": [
5
+ "VILAForCasualLM"
6
+ ],
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_vila.VILAConfig",
9
+ "AutoModel": "modeling_vila.VILAForCasualLM",
10
+ "AutoModelForCausalLM": "modeling_vila.VILAForCasualLM",
11
+ "AutoProcessor": "auto_processor.VILAProcessor"
12
+ },
13
+ "model_type": "vila",
14
+ "chat_template": null,
15
+ "drop_path_rate": 0.0,
16
+ "dynamic_s2": false,
17
+ "fps": 2.0,
18
+ "hidden_size": 3584,
19
+ "image_aspect_ratio": "dynamic",
20
+ "image_encoder": "{\"_target_\": \"llava.model.encoders.BasicImageEncoder\"}",
21
+ "interpolate_mode": "linear",
22
+ "llm_cfg": {
23
+ "_attn_implementation_autoset": false,
24
+ "_name_or_path": "./output/qwen2-7b-longvila-256f/llm",
25
+ "add_cross_attention": false,
26
+ "architectures": [
27
+ "Qwen2ForCausalLM"
28
+ ],
29
+ "attention_dropout": 0.0,
30
+ "bad_words_ids": null,
31
+ "begin_suppress_tokens": null,
32
+ "bos_token_id": 151643,
33
+ "chunk_size_feed_forward": 0,
34
+ "cross_attention_hidden_size": null,
35
+ "decoder_start_token_id": null,
36
+ "diversity_penalty": 0.0,
37
+ "do_sample": false,
38
+ "early_stopping": false,
39
+ "encoder_no_repeat_ngram_size": 0,
40
+ "eos_token_id": 151645,
41
+ "exponential_decay_length_penalty": null,
42
+ "finetuning_task": null,
43
+ "forced_bos_token_id": null,
44
+ "forced_eos_token_id": null,
45
+ "hidden_act": "silu",
46
+ "hidden_size": 3584,
47
+ "id2label": {
48
+ "0": "LABEL_0",
49
+ "1": "LABEL_1"
50
+ },
51
+ "initializer_range": 0.02,
52
+ "intermediate_size": 18944,
53
+ "is_decoder": false,
54
+ "is_encoder_decoder": false,
55
+ "label2id": {
56
+ "LABEL_0": 0,
57
+ "LABEL_1": 1
58
+ },
59
+ "length_penalty": 1.0,
60
+ "max_length": 20,
61
+ "max_position_embeddings": 131072,
62
+ "max_window_layers": 28,
63
+ "min_length": 0,
64
+ "model_max_length": 131072,
65
+ "model_type": "qwen2",
66
+ "no_repeat_ngram_size": 0,
67
+ "num_attention_heads": 28,
68
+ "num_beam_groups": 1,
69
+ "num_beams": 1,
70
+ "num_hidden_layers": 28,
71
+ "num_key_value_heads": 4,
72
+ "num_return_sequences": 1,
73
+ "output_attentions": false,
74
+ "output_hidden_states": false,
75
+ "output_scores": false,
76
+ "pad_token_id": null,
77
+ "prefix": null,
78
+ "problem_type": null,
79
+ "pruned_heads": {},
80
+ "remove_invalid_values": false,
81
+ "repetition_penalty": 1.0,
82
+ "return_dict": true,
83
+ "return_dict_in_generate": false,
84
+ "rms_norm_eps": 1e-06,
85
+ "rope_scaling": null,
86
+ "rope_theta": 15300000,
87
+ "sep_token_id": null,
88
+ "sliding_window": null,
89
+ "suppress_tokens": null,
90
+ "task_specific_params": null,
91
+ "temperature": 1.0,
92
+ "tf_legacy_loss": false,
93
+ "tie_encoder_decoder": false,
94
+ "tie_word_embeddings": true,
95
+ "tokenizer_class": null,
96
+ "tokenizer_model_max_length": 131072,
97
+ "tokenizer_padding_side": "right",
98
+ "top_k": 50,
99
+ "top_p": 1.0,
100
+ "torch_dtype": "bfloat16",
101
+ "torchscript": false,
102
+ "typical_p": 1.0,
103
+ "use_bfloat16": true,
104
+ "use_cache": true,
105
+ "use_sliding_window": false,
106
+ "vocab_size": 151648
107
+ },
108
+ "mm_hidden_size": 1152,
109
+ "mm_projector_cfg": {
110
+ "_attn_implementation_autoset": false,
111
+ "_name_or_path": "./output/qwen2-7b-longvila-256f/mm_projector",
112
+ "add_cross_attention": false,
113
+ "architectures": [
114
+ "MultimodalProjector"
115
+ ],
116
+ "bad_words_ids": null,
117
+ "begin_suppress_tokens": null,
118
+ "bos_token_id": null,
119
+ "chunk_size_feed_forward": 0,
120
+ "cross_attention_hidden_size": null,
121
+ "decoder_start_token_id": null,
122
+ "diversity_penalty": 0.0,
123
+ "do_sample": false,
124
+ "early_stopping": false,
125
+ "encoder_no_repeat_ngram_size": 0,
126
+ "eos_token_id": null,
127
+ "exponential_decay_length_penalty": null,
128
+ "finetuning_task": null,
129
+ "forced_bos_token_id": null,
130
+ "forced_eos_token_id": null,
131
+ "id2label": {
132
+ "0": "LABEL_0",
133
+ "1": "LABEL_1"
134
+ },
135
+ "is_decoder": false,
136
+ "is_encoder_decoder": false,
137
+ "label2id": {
138
+ "LABEL_0": 0,
139
+ "LABEL_1": 1
140
+ },
141
+ "length_penalty": 1.0,
142
+ "max_length": 20,
143
+ "min_length": 0,
144
+ "mm_projector_type": "mlp_downsample_2x2_fix",
145
+ "model_type": "v2l_projector",
146
+ "no_repeat_ngram_size": 0,
147
+ "num_beam_groups": 1,
148
+ "num_beams": 1,
149
+ "num_return_sequences": 1,
150
+ "output_attentions": false,
151
+ "output_hidden_states": false,
152
+ "output_scores": false,
153
+ "pad_token_id": null,
154
+ "prefix": null,
155
+ "problem_type": null,
156
+ "pruned_heads": {},
157
+ "remove_invalid_values": false,
158
+ "repetition_penalty": 1.0,
159
+ "return_dict": true,
160
+ "return_dict_in_generate": false,
161
+ "sep_token_id": null,
162
+ "suppress_tokens": null,
163
+ "task_specific_params": null,
164
+ "temperature": 1.0,
165
+ "tf_legacy_loss": false,
166
+ "tie_encoder_decoder": false,
167
+ "tie_word_embeddings": true,
168
+ "tokenizer_class": null,
169
+ "top_k": 50,
170
+ "top_p": 1.0,
171
+ "torch_dtype": "bfloat16",
172
+ "torchscript": false,
173
+ "typical_p": 1.0,
174
+ "use_bfloat16": true
175
+ },
176
+ "mm_projector_lr": null,
177
+ "mm_use_im_patch_token": true,
178
+ "mm_use_im_start_end": false,
179
+ "mm_vision_select_feature": "cls_patch",
180
+ "mm_vision_select_layer": -2,
181
+ "model_dtype": "torch.bfloat16",
182
+ "num_time_tokens": 0,
183
+ "num_video_frames": 8,
184
+ "resume_path": "./output/qwen2-7b-longvila-256f",
185
+ "s2": false,
186
+ "s2_max_split_size": 336,
187
+ "s2_resize_output_to_scale_idx": 0,
188
+ "s2_scales": "336,672,1008",
189
+ "soft_ce_std": 1.0,
190
+ "time_token_format": "<t{t}>",
191
+ "time_token_ids": [],
192
+ "transformers_version": "4.46.0",
193
+ "tune_language_model": true,
194
+ "tune_mm_projector": true,
195
+ "tune_vision_tower": true,
196
+ "version": "2.0",
197
+ "video_encoder": "{\"_target_\": \"llava.model.encoders.BasicVideoEncoder\"}",
198
+ "vision_resolution": -1,
199
+ "vision_tower_cfg": {
200
+ "_attn_implementation_autoset": false,
201
+ "_name_or_path": "./output/qwen2-7b-longvila-256f/vision_tower",
202
+ "add_cross_attention": false,
203
+ "architectures": [
204
+ "SiglipVisionModel"
205
+ ],
206
+ "attention_dropout": 0.0,
207
+ "bad_words_ids": null,
208
+ "begin_suppress_tokens": null,
209
+ "bos_token_id": null,
210
+ "chunk_size_feed_forward": 0,
211
+ "cross_attention_hidden_size": null,
212
+ "decoder_start_token_id": null,
213
+ "diversity_penalty": 0.0,
214
+ "do_sample": false,
215
+ "early_stopping": false,
216
+ "encoder_no_repeat_ngram_size": 0,
217
+ "eos_token_id": null,
218
+ "exponential_decay_length_penalty": null,
219
+ "finetuning_task": null,
220
+ "forced_bos_token_id": null,
221
+ "forced_eos_token_id": null,
222
+ "hidden_act": "gelu_pytorch_tanh",
223
+ "hidden_size": 1152,
224
+ "id2label": {
225
+ "0": "LABEL_0",
226
+ "1": "LABEL_1"
227
+ },
228
+ "image_size": 448,
229
+ "intermediate_size": 4304,
230
+ "is_decoder": false,
231
+ "is_encoder_decoder": false,
232
+ "label2id": {
233
+ "LABEL_0": 0,
234
+ "LABEL_1": 1
235
+ },
236
+ "layer_norm_eps": 1e-06,
237
+ "length_penalty": 1.0,
238
+ "max_length": 20,
239
+ "min_length": 0,
240
+ "model_type": "siglip_vision_model",
241
+ "no_repeat_ngram_size": 0,
242
+ "num_attention_heads": 16,
243
+ "num_beam_groups": 1,
244
+ "num_beams": 1,
245
+ "num_channels": 3,
246
+ "num_hidden_layers": 27,
247
+ "num_image_tokens": 256,
248
+ "num_return_sequences": 1,
249
+ "output_attentions": false,
250
+ "output_hidden_states": false,
251
+ "output_scores": false,
252
+ "pad_token_id": null,
253
+ "patch_size": 14,
254
+ "prefix": null,
255
+ "problem_type": null,
256
+ "projection_dim": 2048,
257
+ "projector_hidden_act": "gelu_fast",
258
+ "pruned_heads": {},
259
+ "remove_invalid_values": false,
260
+ "repetition_penalty": 1.0,
261
+ "return_dict": true,
262
+ "return_dict_in_generate": false,
263
+ "sep_token_id": null,
264
+ "suppress_tokens": null,
265
+ "task_specific_params": null,
266
+ "temperature": 1.0,
267
+ "tf_legacy_loss": false,
268
+ "tie_encoder_decoder": false,
269
+ "tie_word_embeddings": true,
270
+ "tokenizer_class": null,
271
+ "top_k": 50,
272
+ "top_p": 1.0,
273
+ "torch_dtype": "bfloat16",
274
+ "torchscript": false,
275
+ "typical_p": 1.0,
276
+ "use_bfloat16": true,
277
+ "vision_use_head": false
278
+ },
279
+ "vision_tower_lr": null
280
+ }
configuration_vila.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import math
3
+ import os
4
+ import os.path as osp
5
+ from copy import deepcopy
6
+ from threading import Thread
7
+ from typing import List, Optional
8
+
9
+ import torch
10
+ import torchvision
11
+ from PIL import Image
12
+ from transformers import (
13
+ AutoProcessor,
14
+ PretrainedConfig,
15
+ PreTrainedModel,
16
+ Qwen2Config,
17
+ Qwen2ForCausalLM,
18
+ Qwen2PreTrainedModel,
19
+ TextIteratorStreamer,
20
+ )
21
+
22
+
23
+ class VILAConfig(PretrainedConfig):
24
+ model_type = "vila"
25
+ keys_to_ignore_at_inference = ["past_key_values"]
26
+
27
+ def __init__(
28
+ self,
29
+ llm_cfg=None,
30
+ vision_tower_cfg=None,
31
+ mm_projector_cfg=None,
32
+ architectures=None,
33
+ resume_path=None,
34
+ hidden_size=None,
35
+ mm_hidden_size=None,
36
+ image_aspect_ratio=None,
37
+ num_video_frames=None,
38
+ fps=None,
39
+ mm_vision_select_layer=None,
40
+ mm_vision_select_feature=None,
41
+ mm_use_im_start_end=False,
42
+ mm_use_im_patch_token=False,
43
+ mm_projector_lr=None,
44
+ vision_tower_lr=None,
45
+ vision_resolution=None,
46
+ interpolate_mode=None,
47
+ s2=None,
48
+ dynamic_s2=None,
49
+ s2_scales=None,
50
+ s2_max_split_size=None,
51
+ s2_resize_output_to_scale_idx=0,
52
+ min_tiles: Optional[int] = 1,
53
+ max_tiles: Optional[int] = 12,
54
+ num_time_tokens=None,
55
+ time_token_format=None,
56
+ image_encoder: str = '{"_target_": "llava.model.encoders.BasicImageEncoder"}',
57
+ video_encoder: str = '{"_target_": "llava.model.encoders.BasicVideoEncoder"}',
58
+ **kwargs,
59
+ ):
60
+ super().__init__()
61
+ self.architectures = architectures
62
+ self.llm_cfg = llm_cfg
63
+ self.vision_tower_cfg = vision_tower_cfg
64
+ self.mm_projector_cfg = mm_projector_cfg
65
+ self.resume_path = resume_path
66
+
67
+ self.hidden_size = hidden_size
68
+ self.mm_hidden_size = mm_hidden_size
69
+ self.image_aspect_ratio = image_aspect_ratio
70
+ self.num_video_frames = num_video_frames
71
+ self.fps = fps
72
+ self.mm_vision_select_layer = mm_vision_select_layer
73
+ self.mm_vision_select_feature = mm_vision_select_feature
74
+ self.mm_use_im_start_end = mm_use_im_start_end
75
+ self.mm_use_im_patch_token = mm_use_im_patch_token
76
+ self.mm_projector_lr = mm_projector_lr
77
+ self.vision_tower_lr = vision_tower_lr
78
+ self.vision_resolution = vision_resolution
79
+ self.interpolate_mode = interpolate_mode
80
+ self.s2 = s2
81
+ self.dynamic_s2 = dynamic_s2
82
+ self.s2_scales = s2_scales
83
+ self.s2_max_split_size = s2_max_split_size
84
+ self.s2_resize_output_to_scale_idx = s2_resize_output_to_scale_idx
85
+ self.min_tiles = min_tiles
86
+ self.max_tiles = max_tiles
87
+ self.num_time_tokens = num_time_tokens
88
+ self.time_token_format = time_token_format
89
+
90
+ self.image_encoder = image_encoder
91
+ self.video_encoder = video_encoder
92
+
93
+ super().__init__(**kwargs)
constants.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
18
+ WORKER_HEART_BEAT_INTERVAL = 15
19
+
20
+ LOGDIR = "."
21
+
22
+ # Model Constants
23
+ IGNORE_INDEX = -100
24
+ DEFAULT_IMAGE_TOKEN = "<image>"
25
+
26
+ SENTINEL_TOKEN = "<vila/sentinel>"
27
+ MEDIA_TOKENS = {
28
+ "image": "<image>",
29
+ "video": "<vila/video>",
30
+ }
31
+ # <image> <vila/video> <vila/sentinel>
32
+ # TODO(ligeng): need to discuss with Zhijian for the following tokens for different models.
33
+ """
34
+ 151643: AddedToken("<|endoftext|>", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),
35
+ 151644: AddedToken("<|im_start|>", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),
36
+ 151645: AddedToken("<|im_end|>", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),
37
+ 151646: AddedToken("[BOS]", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),
38
+ 151647: AddedToken("[PAD]", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),
39
+ 151648: AddedToken("<vila/sentinel>", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),
40
+ 151649: AddedToken("<image>", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),
41
+ 151650: AddedToken("<vila/video>", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),
42
+ """
43
+ NUM_EXTRA_TOKENS = 8
conversation.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
17
+
18
+ import dataclasses
19
+ from enum import Enum, auto
20
+ from typing import List
21
+
22
+ # from llava.utils.logging import logger
23
+
24
+
25
+ class SeparatorStyle(Enum):
26
+ """Different separator style."""
27
+
28
+ AUTO = auto()
29
+ TWO = auto()
30
+ MPT = auto()
31
+ PLAIN = auto()
32
+ LLAMA_3 = auto()
33
+
34
+
35
+ @dataclasses.dataclass
36
+ class Conversation:
37
+ """A class that keeps all conversation history."""
38
+
39
+ system: str
40
+ roles: List[str]
41
+ messages: List[List[str]]
42
+ sep_style: SeparatorStyle = SeparatorStyle.AUTO
43
+ sep: str = "###"
44
+ sep2: str = None
45
+ version: str = "Unknown"
46
+
47
+ def get_prompt(self):
48
+ messages = self.messages
49
+ if len(messages) > 0 and type(messages[0][1]) is tuple:
50
+ messages = self.messages.copy()
51
+ init_role, init_msg = messages[0].copy()
52
+ init_msg = init_msg[0].replace("<image>", "").strip()
53
+ messages[0] = (init_role, "<image>\n" + init_msg)
54
+
55
+ if self.sep_style == SeparatorStyle.TWO:
56
+ seps = [self.sep, self.sep2]
57
+ ret = self.system + seps[0]
58
+ for i, (role, message) in enumerate(messages):
59
+ if message:
60
+ if type(message) is tuple:
61
+ message, _, _ = message
62
+ ret += role + ": " + message + seps[i % 2]
63
+ else:
64
+ ret += role + ":"
65
+ elif self.sep_style == SeparatorStyle.LLAMA_3:
66
+ ret = self.system + self.sep
67
+ for rid, (role, message) in enumerate(messages):
68
+ if message:
69
+ if type(message) is tuple:
70
+ message = message[0]
71
+ sep = self.sep if rid < len(messages) - 1 else self.sep2
72
+ ret += role + message + sep
73
+ else:
74
+ ret += role
75
+ elif self.sep_style == SeparatorStyle.MPT:
76
+ ret = self.system + self.sep
77
+ for role, message in messages:
78
+ if message:
79
+ if type(message) is tuple:
80
+ message, _, _ = message
81
+ ret += role + message + self.sep
82
+ else:
83
+ ret += role
84
+ elif self.sep_style == SeparatorStyle.PLAIN:
85
+ seps = [self.sep, self.sep2]
86
+ ret = self.system
87
+ for i, (role, message) in enumerate(messages):
88
+ if message:
89
+ if type(message) is tuple:
90
+ message, _, _ = message
91
+ ret += message + seps[i % 2]
92
+ else:
93
+ ret += ""
94
+ else:
95
+ raise ValueError(f"Invalid style: {self.sep_style}")
96
+
97
+ return ret
98
+
99
+ def append_message(self, role, message):
100
+ self.messages.append([role, message])
101
+
102
+ def copy(self):
103
+ return Conversation(
104
+ system=self.system,
105
+ roles=self.roles,
106
+ messages=[[x, y] for x, y in self.messages],
107
+ sep_style=self.sep_style,
108
+ sep=self.sep,
109
+ sep2=self.sep2,
110
+ version=self.version,
111
+ )
112
+
113
+
114
+ conv_auto = Conversation(
115
+ system="",
116
+ roles=("", ""),
117
+ messages=(),
118
+ sep_style=SeparatorStyle.AUTO,
119
+ sep="\n",
120
+ )
121
+
122
+ conv_vicuna_v1 = Conversation(
123
+ system="A chat between a curious user and an artificial intelligence assistant. "
124
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
125
+ roles=("USER", "ASSISTANT"),
126
+ version="v1",
127
+ messages=(),
128
+ sep_style=SeparatorStyle.TWO,
129
+ sep=" ",
130
+ sep2="</s>",
131
+ )
132
+
133
+ conv_llava_plain = Conversation(
134
+ system="",
135
+ roles=("", ""),
136
+ messages=(),
137
+ sep_style=SeparatorStyle.PLAIN,
138
+ sep="\n",
139
+ )
140
+
141
+ hermes_2 = Conversation(
142
+ system="<|im_start|>system\nAnswer the questions.",
143
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
144
+ sep_style=SeparatorStyle.MPT,
145
+ sep="<|im_end|>",
146
+ messages=(),
147
+ version="hermes-2",
148
+ )
149
+
150
+ # Template added by Yukang. Note (kentang-mit@): sep is <|eot_id|> for official template.
151
+ llama_3_chat = Conversation(
152
+ system="<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\nYou are a helpful language and vision assistant. "
153
+ "You are able to understand the visual content that the user provides, "
154
+ "and assist the user with a variety of tasks using natural language.",
155
+ roles=("<|start_header_id|>user<|end_header_id|>\n\n", "<|start_header_id|>assistant<|end_header_id|>\n\n"),
156
+ version="llama_v3",
157
+ messages=(),
158
+ sep_style=SeparatorStyle.LLAMA_3,
159
+ sep="<|eot_id|>",
160
+ sep2="<|end_of_text|>",
161
+ )
162
+
163
+
164
+ default_conversation = conv_auto
165
+ conv_templates = {
166
+ "auto": conv_auto,
167
+ "hermes-2": hermes_2,
168
+ "llama_3": llama_3_chat,
169
+ "v1": conv_vicuna_v1,
170
+ "vicuna_v1": conv_vicuna_v1,
171
+ "plain": conv_llava_plain,
172
+ }
173
+
174
+
175
+ CONVERSATION_MODE_MAPPING = {
176
+ "vila1.5-3b": "vicuna_v1",
177
+ "vila1.5-8b": "llama_3",
178
+ "vila1.5-13b": "vicuna_v1",
179
+ "vila1.5-40b": "hermes-2",
180
+ "llama-3": "llama_3",
181
+ "llama3": "llama_3",
182
+ }
183
+
184
+
185
+ def auto_set_conversation_mode(model_name_or_path: str) -> str:
186
+ global default_conversation
187
+ for k, v in CONVERSATION_MODE_MAPPING.items():
188
+ if k in model_name_or_path.lower():
189
+ print(f"Setting conversation mode to `{v}` based on model name/path `{model_name_or_path}`.")
190
+ default_conversation = conv_templates[v]
191
+ return
distributed.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import warnings
3
+ from typing import Any, List, Optional
4
+
5
+ from torch import distributed as dist
6
+
7
+ __all__ = [
8
+ "init",
9
+ "is_initialized",
10
+ "size",
11
+ "rank",
12
+ "local_size",
13
+ "local_rank",
14
+ "is_main",
15
+ "barrier",
16
+ "gather",
17
+ "all_gather",
18
+ ]
19
+
20
+
21
+ def init() -> None:
22
+ if "RANK" not in os.environ:
23
+ warnings.warn("Environment variable `RANK` is not set. Skipping distributed initialization.")
24
+ return
25
+ dist.init_process_group(backend="nccl", init_method="env://")
26
+
27
+
28
+ def is_initialized() -> bool:
29
+ return dist.is_initialized()
30
+
31
+
32
+ def size() -> int:
33
+ return int(os.environ.get("WORLD_SIZE", 1))
34
+
35
+
36
+ def rank() -> int:
37
+ return int(os.environ.get("RANK", 0))
38
+
39
+
40
+ def local_size() -> int:
41
+ return int(os.environ.get("LOCAL_WORLD_SIZE", 1))
42
+
43
+
44
+ def local_rank() -> int:
45
+ return int(os.environ.get("LOCAL_RANK", 0))
46
+
47
+
48
+ def is_main() -> bool:
49
+ return rank() == 0
50
+
51
+
52
+ def barrier() -> None:
53
+ dist.barrier()
54
+
55
+
56
+ def gather(obj: Any, dst: int = 0) -> Optional[List[Any]]:
57
+ if not is_initialized():
58
+ return [obj]
59
+ if is_main():
60
+ objs = [None for _ in range(size())]
61
+ dist.gather_object(obj, objs, dst=dst)
62
+ return objs
63
+ else:
64
+ dist.gather_object(obj, dst=dst)
65
+ return None
66
+
67
+
68
+ def all_gather(obj: Any) -> List[Any]:
69
+ if not is_initialized():
70
+ return [obj]
71
+ objs = [None for _ in range(size())]
72
+ dist.all_gather_object(objs, obj)
73
+ return objs
llm/added_tokens.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "<image>": 151649,
3
+ "<vila/sentinel>": 151648,
4
+ "<vila/video>": 151650,
5
+ "<|endoftext|>": 151643,
6
+ "<|im_end|>": 151645,
7
+ "<|im_start|>": 151644,
8
+ "[BOS]": 151646,
9
+ "[PAD]": 151647
10
+ }
llm/config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./output/qwen2-7b-longvila-256f-internal-reasoning-0320/llm",
3
+ "architectures": [
4
+ "Qwen2ForCausalLM"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 151643,
8
+ "eos_token_id": 151645,
9
+ "hidden_act": "silu",
10
+ "hidden_size": 3584,
11
+ "initializer_range": 0.02,
12
+ "intermediate_size": 18944,
13
+ "max_position_embeddings": 131072,
14
+ "max_window_layers": 28,
15
+ "model_max_length": 131072,
16
+ "model_type": "qwen2",
17
+ "num_attention_heads": 28,
18
+ "num_hidden_layers": 28,
19
+ "num_key_value_heads": 4,
20
+ "rms_norm_eps": 1e-06,
21
+ "rope_scaling": null,
22
+ "rope_theta": 15300000,
23
+ "sliding_window": null,
24
+ "tie_word_embeddings": false,
25
+ "tokenizer_model_max_length": 131072,
26
+ "tokenizer_padding_side": "right",
27
+ "torch_dtype": "bfloat16",
28
+ "transformers_version": "4.46.2",
29
+ "use_cache": true,
30
+ "use_sliding_window": false,
31
+ "vocab_size": 151648
32
+ }
llm/generation_config.json ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 151643,
3
+ "do_sample": true,
4
+ "eos_token_id": [
5
+ 151645,
6
+ 151643
7
+ ],
8
+ "pad_token_id": 151643,
9
+ "repetition_penalty": 1.05,
10
+ "temperature": 0.7,
11
+ "top_k": 20,
12
+ "top_p": 0.8,
13
+ "transformers_version": "4.46.2"
14
+ }
llm/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
llm/model-00001-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:66daccf1697203882b2fcbcf9c45b3ac40304c00ff220cb65109ffcd9096c8b0
3
+ size 4874678888
llm/model-00002-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e833dc38658d12ac762425486f67bbe1b0b052b24539b23ca452e16ff220acf3
3
+ size 4932751008
llm/model-00003-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a2d0ef16d9a85cdc3c3f384e48d8581927675d06d5c42c6913290700f530fb6
3
+ size 4330865200
llm/model-00004-of-00004.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bc86393c91368d93d360454c4aba3d7df6c41385dc15b001b5c06331ed85bb54
3
+ size 1087012992
llm/model.safetensors.index.json ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 15225269248
4
+ },
5
+ "weight_map": {
6
+ "lm_head.weight": "model-00004-of-00004.safetensors",
7
+ "model.embed_tokens.weight": "model-00001-of-00004.safetensors",
8
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00004.safetensors",
9
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
10
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
11
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
12
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
13
+ "model.layers.0.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
14
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
15
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
16
+ "model.layers.0.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
17
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
18
+ "model.layers.0.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
19
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
20
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00004.safetensors",
21
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
22
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
23
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
24
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
25
+ "model.layers.1.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
26
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
27
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
28
+ "model.layers.1.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
29
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
30
+ "model.layers.1.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
31
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
32
+ "model.layers.10.input_layernorm.weight": "model-00002-of-00004.safetensors",
33
+ "model.layers.10.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
34
+ "model.layers.10.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
35
+ "model.layers.10.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
36
+ "model.layers.10.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
37
+ "model.layers.10.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
38
+ "model.layers.10.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
39
+ "model.layers.10.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
40
+ "model.layers.10.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
41
+ "model.layers.10.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
42
+ "model.layers.10.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
43
+ "model.layers.10.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
44
+ "model.layers.11.input_layernorm.weight": "model-00002-of-00004.safetensors",
45
+ "model.layers.11.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
46
+ "model.layers.11.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
47
+ "model.layers.11.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
48
+ "model.layers.11.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
49
+ "model.layers.11.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
50
+ "model.layers.11.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
51
+ "model.layers.11.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
52
+ "model.layers.11.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
53
+ "model.layers.11.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
54
+ "model.layers.11.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
55
+ "model.layers.11.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
56
+ "model.layers.12.input_layernorm.weight": "model-00002-of-00004.safetensors",
57
+ "model.layers.12.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
58
+ "model.layers.12.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
59
+ "model.layers.12.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
60
+ "model.layers.12.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
61
+ "model.layers.12.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
62
+ "model.layers.12.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
63
+ "model.layers.12.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
64
+ "model.layers.12.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
65
+ "model.layers.12.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
66
+ "model.layers.12.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
67
+ "model.layers.12.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
68
+ "model.layers.13.input_layernorm.weight": "model-00002-of-00004.safetensors",
69
+ "model.layers.13.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
70
+ "model.layers.13.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
71
+ "model.layers.13.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
72
+ "model.layers.13.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
73
+ "model.layers.13.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
74
+ "model.layers.13.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
75
+ "model.layers.13.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
76
+ "model.layers.13.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
77
+ "model.layers.13.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
78
+ "model.layers.13.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
79
+ "model.layers.13.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
80
+ "model.layers.14.input_layernorm.weight": "model-00002-of-00004.safetensors",
81
+ "model.layers.14.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
82
+ "model.layers.14.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
83
+ "model.layers.14.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
84
+ "model.layers.14.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
85
+ "model.layers.14.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
86
+ "model.layers.14.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
87
+ "model.layers.14.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
88
+ "model.layers.14.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
89
+ "model.layers.14.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
90
+ "model.layers.14.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
91
+ "model.layers.14.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
92
+ "model.layers.15.input_layernorm.weight": "model-00002-of-00004.safetensors",
93
+ "model.layers.15.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
94
+ "model.layers.15.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
95
+ "model.layers.15.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
96
+ "model.layers.15.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
97
+ "model.layers.15.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
98
+ "model.layers.15.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
99
+ "model.layers.15.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
100
+ "model.layers.15.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
101
+ "model.layers.15.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
102
+ "model.layers.15.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
103
+ "model.layers.15.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
104
+ "model.layers.16.input_layernorm.weight": "model-00002-of-00004.safetensors",
105
+ "model.layers.16.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
106
+ "model.layers.16.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
107
+ "model.layers.16.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
108
+ "model.layers.16.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
109
+ "model.layers.16.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
110
+ "model.layers.16.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
111
+ "model.layers.16.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
112
+ "model.layers.16.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
113
+ "model.layers.16.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
114
+ "model.layers.16.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
115
+ "model.layers.16.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
116
+ "model.layers.17.input_layernorm.weight": "model-00002-of-00004.safetensors",
117
+ "model.layers.17.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
118
+ "model.layers.17.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
119
+ "model.layers.17.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
120
+ "model.layers.17.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
121
+ "model.layers.17.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
122
+ "model.layers.17.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
123
+ "model.layers.17.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
124
+ "model.layers.17.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
125
+ "model.layers.17.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
126
+ "model.layers.17.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
127
+ "model.layers.17.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
128
+ "model.layers.18.input_layernorm.weight": "model-00003-of-00004.safetensors",
129
+ "model.layers.18.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
130
+ "model.layers.18.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
131
+ "model.layers.18.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
132
+ "model.layers.18.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
133
+ "model.layers.18.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
134
+ "model.layers.18.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
135
+ "model.layers.18.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
136
+ "model.layers.18.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
137
+ "model.layers.18.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
138
+ "model.layers.18.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
139
+ "model.layers.18.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
140
+ "model.layers.19.input_layernorm.weight": "model-00003-of-00004.safetensors",
141
+ "model.layers.19.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
142
+ "model.layers.19.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
143
+ "model.layers.19.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
144
+ "model.layers.19.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
145
+ "model.layers.19.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
146
+ "model.layers.19.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
147
+ "model.layers.19.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
148
+ "model.layers.19.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
149
+ "model.layers.19.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
150
+ "model.layers.19.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
151
+ "model.layers.19.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
152
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00004.safetensors",
153
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
154
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
155
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
156
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
157
+ "model.layers.2.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
158
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
159
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
160
+ "model.layers.2.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
161
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
162
+ "model.layers.2.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
163
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
164
+ "model.layers.20.input_layernorm.weight": "model-00003-of-00004.safetensors",
165
+ "model.layers.20.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
166
+ "model.layers.20.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
167
+ "model.layers.20.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
168
+ "model.layers.20.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
169
+ "model.layers.20.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
170
+ "model.layers.20.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
171
+ "model.layers.20.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
172
+ "model.layers.20.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
173
+ "model.layers.20.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
174
+ "model.layers.20.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
175
+ "model.layers.20.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
176
+ "model.layers.21.input_layernorm.weight": "model-00003-of-00004.safetensors",
177
+ "model.layers.21.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
178
+ "model.layers.21.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
179
+ "model.layers.21.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
180
+ "model.layers.21.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
181
+ "model.layers.21.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
182
+ "model.layers.21.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
183
+ "model.layers.21.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
184
+ "model.layers.21.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
185
+ "model.layers.21.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
186
+ "model.layers.21.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
187
+ "model.layers.21.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
188
+ "model.layers.22.input_layernorm.weight": "model-00003-of-00004.safetensors",
189
+ "model.layers.22.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
190
+ "model.layers.22.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
191
+ "model.layers.22.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
192
+ "model.layers.22.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
193
+ "model.layers.22.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
194
+ "model.layers.22.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
195
+ "model.layers.22.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
196
+ "model.layers.22.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
197
+ "model.layers.22.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
198
+ "model.layers.22.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
199
+ "model.layers.22.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
200
+ "model.layers.23.input_layernorm.weight": "model-00003-of-00004.safetensors",
201
+ "model.layers.23.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
202
+ "model.layers.23.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
203
+ "model.layers.23.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
204
+ "model.layers.23.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
205
+ "model.layers.23.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
206
+ "model.layers.23.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
207
+ "model.layers.23.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
208
+ "model.layers.23.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
209
+ "model.layers.23.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
210
+ "model.layers.23.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
211
+ "model.layers.23.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
212
+ "model.layers.24.input_layernorm.weight": "model-00003-of-00004.safetensors",
213
+ "model.layers.24.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
214
+ "model.layers.24.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
215
+ "model.layers.24.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
216
+ "model.layers.24.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
217
+ "model.layers.24.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
218
+ "model.layers.24.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
219
+ "model.layers.24.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
220
+ "model.layers.24.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
221
+ "model.layers.24.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
222
+ "model.layers.24.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
223
+ "model.layers.24.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
224
+ "model.layers.25.input_layernorm.weight": "model-00003-of-00004.safetensors",
225
+ "model.layers.25.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
226
+ "model.layers.25.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
227
+ "model.layers.25.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
228
+ "model.layers.25.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
229
+ "model.layers.25.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
230
+ "model.layers.25.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
231
+ "model.layers.25.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
232
+ "model.layers.25.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
233
+ "model.layers.25.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
234
+ "model.layers.25.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
235
+ "model.layers.25.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
236
+ "model.layers.26.input_layernorm.weight": "model-00003-of-00004.safetensors",
237
+ "model.layers.26.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
238
+ "model.layers.26.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
239
+ "model.layers.26.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
240
+ "model.layers.26.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
241
+ "model.layers.26.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
242
+ "model.layers.26.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
243
+ "model.layers.26.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
244
+ "model.layers.26.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
245
+ "model.layers.26.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
246
+ "model.layers.26.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
247
+ "model.layers.26.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
248
+ "model.layers.27.input_layernorm.weight": "model-00003-of-00004.safetensors",
249
+ "model.layers.27.mlp.down_proj.weight": "model-00003-of-00004.safetensors",
250
+ "model.layers.27.mlp.gate_proj.weight": "model-00003-of-00004.safetensors",
251
+ "model.layers.27.mlp.up_proj.weight": "model-00003-of-00004.safetensors",
252
+ "model.layers.27.post_attention_layernorm.weight": "model-00003-of-00004.safetensors",
253
+ "model.layers.27.self_attn.k_proj.bias": "model-00003-of-00004.safetensors",
254
+ "model.layers.27.self_attn.k_proj.weight": "model-00003-of-00004.safetensors",
255
+ "model.layers.27.self_attn.o_proj.weight": "model-00003-of-00004.safetensors",
256
+ "model.layers.27.self_attn.q_proj.bias": "model-00003-of-00004.safetensors",
257
+ "model.layers.27.self_attn.q_proj.weight": "model-00003-of-00004.safetensors",
258
+ "model.layers.27.self_attn.v_proj.bias": "model-00003-of-00004.safetensors",
259
+ "model.layers.27.self_attn.v_proj.weight": "model-00003-of-00004.safetensors",
260
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00004.safetensors",
261
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
262
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
263
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
264
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
265
+ "model.layers.3.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
266
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
267
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
268
+ "model.layers.3.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
269
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
270
+ "model.layers.3.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
271
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
272
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00004.safetensors",
273
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
274
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
275
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
276
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
277
+ "model.layers.4.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
278
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
279
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
280
+ "model.layers.4.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
281
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
282
+ "model.layers.4.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
283
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
284
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00004.safetensors",
285
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
286
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
287
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
288
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
289
+ "model.layers.5.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
290
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
291
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
292
+ "model.layers.5.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
293
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
294
+ "model.layers.5.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
295
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
296
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00004.safetensors",
297
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
298
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
299
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
300
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
301
+ "model.layers.6.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
302
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
303
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
304
+ "model.layers.6.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
305
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
306
+ "model.layers.6.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
307
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
308
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00004.safetensors",
309
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00004.safetensors",
310
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00004.safetensors",
311
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00004.safetensors",
312
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00004.safetensors",
313
+ "model.layers.7.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
314
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
315
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
316
+ "model.layers.7.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
317
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
318
+ "model.layers.7.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
319
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
320
+ "model.layers.8.input_layernorm.weight": "model-00002-of-00004.safetensors",
321
+ "model.layers.8.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
322
+ "model.layers.8.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
323
+ "model.layers.8.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
324
+ "model.layers.8.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
325
+ "model.layers.8.self_attn.k_proj.bias": "model-00001-of-00004.safetensors",
326
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00004.safetensors",
327
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00004.safetensors",
328
+ "model.layers.8.self_attn.q_proj.bias": "model-00001-of-00004.safetensors",
329
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00004.safetensors",
330
+ "model.layers.8.self_attn.v_proj.bias": "model-00001-of-00004.safetensors",
331
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00004.safetensors",
332
+ "model.layers.9.input_layernorm.weight": "model-00002-of-00004.safetensors",
333
+ "model.layers.9.mlp.down_proj.weight": "model-00002-of-00004.safetensors",
334
+ "model.layers.9.mlp.gate_proj.weight": "model-00002-of-00004.safetensors",
335
+ "model.layers.9.mlp.up_proj.weight": "model-00002-of-00004.safetensors",
336
+ "model.layers.9.post_attention_layernorm.weight": "model-00002-of-00004.safetensors",
337
+ "model.layers.9.self_attn.k_proj.bias": "model-00002-of-00004.safetensors",
338
+ "model.layers.9.self_attn.k_proj.weight": "model-00002-of-00004.safetensors",
339
+ "model.layers.9.self_attn.o_proj.weight": "model-00002-of-00004.safetensors",
340
+ "model.layers.9.self_attn.q_proj.bias": "model-00002-of-00004.safetensors",
341
+ "model.layers.9.self_attn.q_proj.weight": "model-00002-of-00004.safetensors",
342
+ "model.layers.9.self_attn.v_proj.bias": "model-00002-of-00004.safetensors",
343
+ "model.layers.9.self_attn.v_proj.weight": "model-00002-of-00004.safetensors",
344
+ "model.norm.weight": "model-00003-of-00004.safetensors"
345
+ }
346
+ }
llm/special_tokens_map.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>"
5
+ ],
6
+ "bos_token": {
7
+ "content": "[BOS]",
8
+ "lstrip": false,
9
+ "normalized": false,
10
+ "rstrip": false,
11
+ "single_word": false
12
+ },
13
+ "eos_token": {
14
+ "content": "<|im_end|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ },
20
+ "pad_token": {
21
+ "content": "[PAD]",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false
26
+ }
27
+ }
llm/tokenizer_config.json ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "added_tokens_decoder": {
4
+ "151643": {
5
+ "content": "<|endoftext|>",
6
+ "lstrip": false,
7
+ "normalized": false,
8
+ "rstrip": false,
9
+ "single_word": false,
10
+ "special": true
11
+ },
12
+ "151644": {
13
+ "content": "<|im_start|>",
14
+ "lstrip": false,
15
+ "normalized": false,
16
+ "rstrip": false,
17
+ "single_word": false,
18
+ "special": true
19
+ },
20
+ "151645": {
21
+ "content": "<|im_end|>",
22
+ "lstrip": false,
23
+ "normalized": false,
24
+ "rstrip": false,
25
+ "single_word": false,
26
+ "special": true
27
+ },
28
+ "151646": {
29
+ "content": "[BOS]",
30
+ "lstrip": false,
31
+ "normalized": false,
32
+ "rstrip": false,
33
+ "single_word": false,
34
+ "special": true
35
+ },
36
+ "151647": {
37
+ "content": "[PAD]",
38
+ "lstrip": false,
39
+ "normalized": false,
40
+ "rstrip": false,
41
+ "single_word": false,
42
+ "special": true
43
+ },
44
+ "151648": {
45
+ "content": "<vila/sentinel>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false,
50
+ "special": true
51
+ },
52
+ "151649": {
53
+ "content": "<image>",
54
+ "lstrip": false,
55
+ "normalized": false,
56
+ "rstrip": false,
57
+ "single_word": false,
58
+ "special": true
59
+ },
60
+ "151650": {
61
+ "content": "<vila/video>",
62
+ "lstrip": false,
63
+ "normalized": false,
64
+ "rstrip": false,
65
+ "single_word": false,
66
+ "special": true
67
+ }
68
+ },
69
+ "additional_special_tokens": [
70
+ "<|im_start|>",
71
+ "<|im_end|>"
72
+ ],
73
+ "bos_token": "[BOS]",
74
+ "chat_template": "{% if messages[0]['role'] != 'system' %}{{ '<|im_start|>system\\nYou are a helpful assistant<|im_end|>\\n' }}{% endif %}{% for message in messages if message['content'] is not none %}{{ '<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>' + '\\n' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\\n' }}{% endif %}",
75
+ "clean_up_tokenization_spaces": false,
76
+ "eos_token": "<|im_end|>",
77
+ "errors": "replace",
78
+ "legacy": false,
79
+ "model_max_length": 4096,
80
+ "pad_token": "[PAD]",
81
+ "padding_side": "left",
82
+ "split_special_tokens": false,
83
+ "tokenizer_class": "Qwen2Tokenizer",
84
+ "unk_token": null
85
+ }
llm/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
loss.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Union
2
+
3
+ import torch
4
+ from torch.nn.functional import cross_entropy
5
+
6
+ from .constants import IGNORE_INDEX
7
+
8
+ __all__ = ["soft_cross_entropy"]
9
+
10
+
11
+ def soft_cross_entropy(
12
+ outputs: torch.Tensor,
13
+ targets: torch.Tensor,
14
+ soft_tokens: Union[torch.Tensor, List[int]],
15
+ std: float = 1,
16
+ ignore_index: int = IGNORE_INDEX,
17
+ ) -> torch.Tensor:
18
+ # Remove last token from outputs and first token from targets
19
+ outputs = outputs[..., :-1, :].contiguous()
20
+ targets = targets[..., 1:].contiguous()
21
+
22
+ # Flatten outputs and targets
23
+ targets = targets.view(-1)
24
+ outputs = outputs.view(targets.size(0), -1)
25
+
26
+ # Remove outputs and targets with ignore_index
27
+ indices = targets != ignore_index
28
+ outputs = outputs[indices]
29
+ targets = targets[indices]
30
+
31
+ # Convert soft token IDs to tensor
32
+ if isinstance(soft_tokens, list):
33
+ soft_tokens = torch.tensor(soft_tokens).to(targets)
34
+
35
+ # Calculate loss for non-soft tokens
36
+ indices = torch.isin(targets, soft_tokens, invert=True)
37
+ loss = cross_entropy(outputs[indices], targets[indices], reduction="sum")
38
+
39
+ # Calculate loss for soft tokens
40
+ indices = torch.isin(targets, soft_tokens)
41
+ targets_indices = torch.zeros_like(outputs[indices])
42
+ for k, target in enumerate(targets[indices]):
43
+ dist = torch.exp(-((target - soft_tokens) ** 2) / (2 * std**2))
44
+ targets_indices[k][soft_tokens] = dist / dist.sum()
45
+ loss += cross_entropy(outputs[indices], targets_indices, reduction="sum")
46
+
47
+ # Return average loss
48
+ return loss / targets.size(0)
main.py ADDED
File without changes
media.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import os
3
+ from collections import defaultdict
4
+ from typing import Any, Dict, List, Optional, Union
5
+
6
+ import cv2
7
+ import numpy as np
8
+ import PIL
9
+ import PIL.Image
10
+ import requests
11
+ from transformers import PretrainedConfig
12
+
13
+ # from llava.constants import MEDIA_TOKENS
14
+ # from llava.media import Image, Video
15
+ # from llava.utils import make_list
16
+ # from llava.utils.logging import logger
17
+
18
+ MEDIA_TOKENS = {
19
+ "image": "<image>",
20
+ "video": "<vila/video>",
21
+ }
22
+
23
+
24
+ class Media:
25
+ pass
26
+
27
+
28
+ class File(Media):
29
+ def __init__(self, path: str) -> None:
30
+ self.path = path
31
+
32
+
33
+ class Image(File):
34
+ pass
35
+
36
+
37
+ class Video(File):
38
+ pass
39
+
40
+
41
+ def make_list(obj: Any) -> List:
42
+ return obj if isinstance(obj, list) else [obj]
43
+
44
+
45
+ def _extract_image(image: Union[Image, PIL.Image.Image]) -> PIL.Image.Image:
46
+ if isinstance(image, Image):
47
+ if image.path.startswith("http://") or image.path.startswith("https://"):
48
+ image = PIL.Image.open(requests.get(image.path, stream=True).raw)
49
+ else:
50
+ image = PIL.Image.open(image.path)
51
+ return image
52
+
53
+
54
+ def _load_video(video_path: str, *, num_frames: int) -> List[PIL.Image.Image]:
55
+ # Load video frames from a directory
56
+ if os.path.isdir(video_path):
57
+ frame_paths = sorted(glob.glob(os.path.join(video_path, "*")))
58
+ indices = np.round(np.linspace(0, len(frame_paths) - 1, num_frames)).astype(int)
59
+ return [PIL.Image.open(frame_paths[index]) for index in indices]
60
+
61
+ # Load video frames from a video file
62
+ vidcap = cv2.VideoCapture(video_path)
63
+
64
+ # Find the last frame as frame count might not be accurate
65
+ frame_count = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
66
+ while frame_count > 0:
67
+ vidcap.set(cv2.CAP_PROP_POS_FRAMES, frame_count - 1)
68
+ if vidcap.grab():
69
+ break
70
+ frame_count -= 1
71
+ else:
72
+ raise ValueError(f"Video '{video_path}' has no frames.")
73
+
74
+ # Extract frames uniformly
75
+ indices = np.round(np.linspace(0, frame_count - 1, num_frames)).astype(int)
76
+ frames = {}
77
+ for index in indices:
78
+ if index in frames:
79
+ continue
80
+ vidcap.set(cv2.CAP_PROP_POS_FRAMES, index)
81
+ success, frame = vidcap.read()
82
+ if not success:
83
+ print(f"Failed to read frame {index} from video '{video_path}'. Skipped.")
84
+ continue
85
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
86
+ frames[index] = PIL.Image.fromarray(frame)
87
+ return [frames[index] for index in indices if index in frames]
88
+
89
+
90
+ def _extract_video(video: Video, config: PretrainedConfig) -> List[PIL.Image.Image]:
91
+ num_frames = config.num_video_frames
92
+ if getattr(config, "fps") != 0:
93
+ print("Extracting frames from video with specified FPS is not supported yet. Ignored.")
94
+
95
+ frames = _load_video(video.path, num_frames=num_frames)
96
+ return frames
97
+
98
+
99
+ def extract_media(
100
+ messages: List[Dict[str, Any]],
101
+ config: Optional[PretrainedConfig] = None,
102
+ draft: bool = False,
103
+ ) -> Dict[str, List[Any]]:
104
+ media = defaultdict(list)
105
+ for message in messages:
106
+ text = ""
107
+ for part in make_list(message["value"]):
108
+ if isinstance(part, str):
109
+ for token in MEDIA_TOKENS.values():
110
+ if token in part:
111
+ print(f"Media token '{token}' found in text: '{part}'. Removed.")
112
+ part = part.replace(token, "").strip()
113
+ text += part
114
+ elif isinstance(part, (Image, PIL.Image.Image)):
115
+ if draft:
116
+ media["image"].append(part)
117
+ else:
118
+ media["image"].append(_extract_image(part))
119
+ text += MEDIA_TOKENS["image"]
120
+ elif isinstance(part, Video):
121
+ if draft:
122
+ media["video"].append(part)
123
+ else:
124
+ media["video"].append(_extract_video(part, config))
125
+ text += MEDIA_TOKENS["video"]
126
+ else:
127
+ raise ValueError(f"Unsupported prompt part type: {type(part)}")
128
+ message["value"] = text
129
+ return media
media_encoder.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import partial
2
+ from typing import Any, Dict, List, Optional
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+
8
+ class BaseEncoder(nn.Module):
9
+ def __init__(self, parent: nn.Module) -> None:
10
+ super().__init__()
11
+ self._parent = [parent]
12
+
13
+ @property
14
+ def parent(self) -> nn.Module:
15
+ return self._parent[0]
16
+
17
+
18
+ class BasicImageEncoder(BaseEncoder):
19
+ def __init__(
20
+ self,
21
+ parent: torch.nn.Module,
22
+ start_tokens: Optional[str] = None,
23
+ end_tokens: Optional[str] = "\n",
24
+ ) -> None:
25
+ super().__init__(parent)
26
+ self.start_tokens = start_tokens
27
+ self.end_tokens = end_tokens
28
+
29
+ def embed_tokens(self, tokens: Optional[str]) -> Optional[torch.Tensor]:
30
+ if tokens is None:
31
+ return None
32
+ token_ids = self.parent.tokenizer(tokens).input_ids
33
+ token_ids = torch.tensor(token_ids, device=self.parent.device)
34
+ return self.parent.llm.model.embed_tokens(token_ids)
35
+
36
+ def _process_features(
37
+ self,
38
+ features: torch.Tensor,
39
+ start_token_embeds: Optional[torch.Tensor],
40
+ end_token_embeds: Optional[torch.Tensor],
41
+ ) -> torch.Tensor:
42
+ if start_token_embeds is not None:
43
+ features = torch.cat([start_token_embeds, features], dim=0)
44
+ if end_token_embeds is not None:
45
+ features = torch.cat([features, end_token_embeds], dim=0)
46
+ return features
47
+
48
+ def forward(self, images: List[torch.Tensor], config: Dict[str, Any]) -> List[torch.Tensor]:
49
+ images = torch.stack(images, dim=0)
50
+ features = self.parent.encode_images(images, block_sizes=config.get("block_sizes"))
51
+ process_features = partial(
52
+ self._process_features,
53
+ start_token_embeds=self.embed_tokens(self.start_tokens),
54
+ end_token_embeds=self.embed_tokens(self.end_tokens),
55
+ )
56
+ return [process_features(f) for f in features]
57
+
58
+
59
+ class BasicVideoEncoder(BaseEncoder):
60
+ def __init__(
61
+ self,
62
+ parent: torch.nn.Module,
63
+ start_tokens: Optional[str] = None,
64
+ end_tokens: Optional[str] = "\n",
65
+ ) -> None:
66
+ super().__init__(parent)
67
+ self.start_tokens = start_tokens
68
+ self.end_tokens = end_tokens
69
+
70
+ def embed_tokens(self, tokens: Optional[str]) -> Optional[torch.Tensor]:
71
+ if tokens is None:
72
+ return None
73
+ token_ids = self.parent.tokenizer(tokens).input_ids
74
+ token_ids = torch.tensor(token_ids, device=self.parent.device)
75
+ return self.parent.llm.model.embed_tokens(token_ids)
76
+
77
+ def _process_features(
78
+ self,
79
+ features: torch.Tensor,
80
+ start_token_embeds: Optional[torch.Tensor],
81
+ end_token_embeds: Optional[torch.Tensor],
82
+ ) -> torch.Tensor:
83
+ if start_token_embeds is not None:
84
+ start_embeds = torch.stack([start_token_embeds] * features.shape[0], dim=0)
85
+ features = torch.cat([start_embeds, features], dim=1)
86
+ if end_token_embeds is not None:
87
+ end_embeds = torch.stack([end_token_embeds] * features.shape[0], dim=0)
88
+ features = torch.cat([features, end_embeds], dim=1)
89
+ return features.flatten(0, 1)
90
+
91
+ def forward(self, videos: List[torch.Tensor], config: Dict[str, Any]) -> List[torch.Tensor]:
92
+ num_frames = [video.shape[0] for video in videos]
93
+ images = torch.cat(videos, dim=0)
94
+ features = self.parent.encode_images(images)
95
+ features = torch.split(features, num_frames)
96
+ process_features = partial(
97
+ self._process_features,
98
+ start_token_embeds=self.embed_tokens(self.start_tokens),
99
+ end_token_embeds=self.embed_tokens(self.end_tokens),
100
+ )
101
+ return [process_features(f) for f in features]
mm_projector/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./output/qwen2-7b-longvila-256f-internal-reasoning-0320/mm_projector",
3
+ "architectures": [
4
+ "MultimodalProjector"
5
+ ],
6
+ "mm_projector_type": "mlp_downsample_2x2_fix",
7
+ "model_type": "v2l_projector",
8
+ "torch_dtype": "bfloat16",
9
+ "transformers_version": "4.46.2"
10
+ }
mm_projector/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7f20bb5ef5136401b2dc0162f8dfbee9c12702f8ec7f6d93aa883950ecd73344
3
+ size 58753552
mm_utils.py ADDED
@@ -0,0 +1,575 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ # dynamic_preprocess and find_closest_aspect_ratio are referenced from https://github.com/OpenGVLab/InternVL
18
+
19
+ import base64
20
+ import os
21
+ import tempfile
22
+ from io import BytesIO
23
+
24
+ import numpy as np
25
+ import torch
26
+ from PIL import Image
27
+ from transformers import StoppingCriteria
28
+
29
+ from .constants import DEFAULT_IMAGE_TOKEN
30
+
31
+
32
+ def get_frame_from_vcap(vidcap, num_frames=10, max_fps=0.0, fps=None, frame_count=None, video_file_name=None):
33
+ import cv2
34
+
35
+ if fps == None or frame_count == None:
36
+ # if one of fps or frame_count is None, still recompute
37
+ fps = vidcap.get(cv2.CAP_PROP_FPS)
38
+ frame_count = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
39
+ if fps == 0 or frame_count == 0:
40
+ print(f"Video file not found. return empty images. {video_file_name}")
41
+ return [
42
+ Image.new("RGB", (720, 720)),
43
+ ] * num_frames, 0
44
+
45
+ duration = frame_count / fps
46
+ frame_interval = frame_count // num_frames
47
+ if frame_interval == 0 and frame_count <= 1:
48
+ print(f"frame_interval is equal to 0. return empty image. {video_file_name}")
49
+ return [
50
+ Image.new("RGB", (720, 720)),
51
+ ] * num_frames, 0
52
+ # print("duration:", duration, "frames:", frame_count, "intervals:", frame_interval)
53
+
54
+ images = []
55
+ count = 0
56
+ success = True
57
+ frame_indices = np.linspace(0, frame_count - 1, num_frames, dtype=int)
58
+ while success:
59
+ # print("frame_count:", frame_count, "count:", count, "num_frames:", num_frames, "frame_interval:", frame_interval)
60
+ if frame_count >= num_frames:
61
+ success, frame = vidcap.read()
62
+ if count in frame_indices:
63
+ try:
64
+ img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
65
+ im_pil = Image.fromarray(img)
66
+ images.append(im_pil)
67
+ except BaseException:
68
+ continue
69
+ if len(images) >= num_frames:
70
+ return images, num_frames
71
+ count += 1
72
+ else:
73
+ # Left padding frames if the video is not long enough
74
+ success, frame = vidcap.read()
75
+ if success:
76
+ try:
77
+ img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
78
+ im_pil = Image.fromarray(img)
79
+ images.append(im_pil)
80
+ except BaseException:
81
+ continue
82
+ count += 1
83
+ else:
84
+ break
85
+ if len(images) == 0:
86
+ raise ValueError("Did not find enough frames in the video. return empty image.")
87
+
88
+ return images, len(images)
89
+
90
+
91
+ def get_frame_from_vcap_with_fps(vidcap, num_frames=10, max_fps=0.0, fps=None, frame_count=None, video_file_name=None):
92
+ """
93
+ num_frames is the max number of frames the model can support.
94
+ frame_count is the number of frames in the input video.
95
+ max_fps is the max FPS of the model can support.
96
+ fps is the fps of the input video.
97
+ """
98
+
99
+ import random
100
+
101
+ import cv2
102
+
103
+ if fps == None or frame_count == None:
104
+ # if one of fps or frame_count is None, still recompute
105
+ fps = vidcap.get(cv2.CAP_PROP_FPS)
106
+ frame_count = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
107
+
108
+ if fps == 0 or frame_count == 0:
109
+ print(f"Video file not found. return empty images. {video_file_name}")
110
+ empty_video_frames = int(random.uniform(2, 8 * max_fps))
111
+ return [
112
+ Image.new("RGB", (720, 720)),
113
+ ] * empty_video_frames, 0
114
+
115
+ duration = frame_count / fps
116
+ # print("duration:", duration, "frames:", frame_count, "fps:", fps, "num_frames:", num_frames, "max_fps:", max_fps)
117
+ # If the video is too long (longer than max_fps and num_frames can support),
118
+ # we will use lower fps to sample frames.
119
+ if duration >= num_frames / max_fps:
120
+ frame_interval = frame_count // num_frames
121
+
122
+ # If the video is too short, we will skip the video if there is only one frame.
123
+ if frame_interval == 0 and frame_count <= 1:
124
+ print(f"frame_interval is equal to 0. return empty image. {video_file_name}")
125
+ empty_video_frames = int(random.uniform(2, 8 * max_fps))
126
+ return [
127
+ Image.new("RGB", (720, 720)),
128
+ ] * empty_video_frames, 0
129
+
130
+ images = []
131
+ count = 0
132
+ success = True
133
+ frame_indices = np.linspace(0, frame_count - 1, num_frames, dtype=int)
134
+
135
+ while success:
136
+ if frame_count >= num_frames:
137
+ # success, frame = vidcap.read()
138
+ if count in frame_indices:
139
+ success, frame = vidcap.read()
140
+ try:
141
+ img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
142
+ im_pil = Image.fromarray(img)
143
+ images.append(im_pil)
144
+ except:
145
+ # print("Failed to read frame:", count)
146
+ continue
147
+ if len(images) >= num_frames:
148
+ return images, num_frames
149
+ else:
150
+ success = vidcap.grab()
151
+ count += 1
152
+ else:
153
+ # Left padding frames if the video is not long enough
154
+ success, frame = vidcap.read()
155
+ if success:
156
+ try:
157
+ img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
158
+ im_pil = Image.fromarray(img)
159
+ images.append(im_pil)
160
+ except:
161
+ # print("Failed to read frame:", count)
162
+ continue
163
+ count += 1
164
+ else:
165
+ break
166
+ else:
167
+ frames_required = int(duration * max_fps)
168
+ frame_indices = np.linspace(0, frame_count - 1, frames_required, dtype=int)
169
+ if frames_required == 0:
170
+ print(f"frames_required is fewer than 2. Duration {duration}, return empty image.")
171
+ empty_video_frames = int(random.uniform(2, 8 * max_fps))
172
+ return [
173
+ Image.new("RGB", (720, 720)),
174
+ ] * empty_video_frames, 0
175
+ elif frames_required == 1:
176
+ frame_indices = np.linspace(0, frame_count - 1, 2, dtype=int)
177
+ images = []
178
+ count = 0
179
+ looked = 0
180
+ success = True
181
+
182
+ while success:
183
+ success, frame = vidcap.read()
184
+ if success and (looked in frame_indices):
185
+ try:
186
+ img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
187
+ im_pil = Image.fromarray(img)
188
+ images.append(im_pil)
189
+ except:
190
+ continue
191
+ count += 1
192
+ looked += 1
193
+
194
+ if len(images) == 0:
195
+ empty_video_frames = int(random.uniform(2, 8 * max_fps))
196
+ return [
197
+ Image.new("RGB", (720, 720)),
198
+ ] * empty_video_frames, 0
199
+ else:
200
+ return images, len(images)
201
+
202
+
203
+ def opencv_extract_frames(vpath_or_bytesio, frames=6, max_fps=0.0, fps=None, frame_count=None):
204
+ """
205
+ Extract frames from a video using OpenCV.
206
+
207
+ Args:
208
+ vpath_or_bytesio (str or BytesIO): Path to the video file or BytesIO object containing the video.
209
+ frames (int): Number of frames to extract from the video.
210
+ fps (float): Frames per second of the video. If 0.0, the function will extract frames at equal intervals.
211
+
212
+ Returns:
213
+ list: List of PIL Images extracted from the video.
214
+
215
+ Raises:
216
+ NotImplementedError: If the type of `vpath_or_bytesio` is not supported.
217
+ """
218
+ import cv2
219
+
220
+ if isinstance(vpath_or_bytesio, str):
221
+ vidcap = cv2.VideoCapture(vpath_or_bytesio)
222
+ if max_fps > 0.0:
223
+ return get_frame_from_vcap_with_fps(
224
+ vidcap, frames, max_fps, fps=fps, frame_count=frame_count, video_file_name=vpath_or_bytesio
225
+ )
226
+ return get_frame_from_vcap(
227
+ vidcap, frames, max_fps, fps=fps, frame_count=frame_count, video_file_name=vpath_or_bytesio
228
+ )
229
+ elif isinstance(vpath_or_bytesio, (BytesIO,)):
230
+ # assuming mp4
231
+ with tempfile.NamedTemporaryFile(delete=True, suffix=".mp4") as temp_video:
232
+ temp_video.write(vpath_or_bytesio.read())
233
+ temp_video_name = temp_video.name
234
+ vidcap = cv2.VideoCapture(temp_video_name)
235
+ if max_fps > 0.0:
236
+ return get_frame_from_vcap_with_fps(
237
+ vidcap, frames, max_fps, fps=fps, frame_count=frame_count, video_file_name=temp_video_name
238
+ )
239
+ return get_frame_from_vcap(
240
+ vidcap, frames, max_fps, fps=fps, frame_count=frame_count, video_file_name=temp_video_name
241
+ )
242
+ else:
243
+ raise NotImplementedError(type(vpath_or_bytesio))
244
+
245
+
246
+ def load_image_from_base64(image):
247
+ return Image.open(BytesIO(base64.b64decode(image)))
248
+
249
+
250
+ def expand2square(pil_img, background_color):
251
+ """
252
+ Expand the given PIL image to a square shape by adding padding.
253
+
254
+ Parameters:
255
+ - pil_img: The PIL image to be expanded.
256
+ - background_color: The color of the padding to be added.
257
+
258
+ Returns:
259
+ - The expanded PIL image.
260
+
261
+ If the image is already square, it is returned as is.
262
+ If the image is wider than it is tall, padding is added to the top and bottom.
263
+ If the image is taller than it is wide, padding is added to the left and right.
264
+ """
265
+ width, height = pil_img.size
266
+ if pil_img.mode == "L":
267
+ background_color = background_color[0]
268
+ if width == height:
269
+ return pil_img
270
+ elif width > height:
271
+ result = Image.new(pil_img.mode, (width, width), background_color)
272
+ result.paste(pil_img, (0, (width - height) // 2))
273
+ return result
274
+ else:
275
+ result = Image.new(pil_img.mode, (height, height), background_color)
276
+ result.paste(pil_img, ((height - width) // 2, 0))
277
+ return result
278
+
279
+
280
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
281
+ best_ratio_diff = float("inf")
282
+ best_ratio = (1, 1)
283
+ area = width * height
284
+ for ratio in target_ratios:
285
+ target_aspect_ratio = ratio[0] / ratio[1]
286
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
287
+ if ratio_diff < best_ratio_diff:
288
+ best_ratio_diff = ratio_diff
289
+ best_ratio = ratio
290
+ elif ratio_diff == best_ratio_diff:
291
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
292
+ best_ratio = ratio
293
+ return best_ratio
294
+
295
+
296
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=384, use_thumbnail=True):
297
+ orig_width, orig_height = image.size
298
+ aspect_ratio = orig_width / orig_height
299
+
300
+ # calculate the existing image aspect ratio
301
+ target_ratios = {
302
+ (i, j)
303
+ for n in range(min_num, max_num + 1)
304
+ for i in range(1, n + 1)
305
+ for j in range(1, n + 1)
306
+ if i * j <= max_num and i * j >= min_num
307
+ }
308
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
309
+
310
+ # find the closest aspect ratio to the target
311
+ target_aspect_ratio = find_closest_aspect_ratio(aspect_ratio, target_ratios, orig_width, orig_height, image_size)
312
+
313
+ # calculate the target width and height
314
+ target_width = image_size * target_aspect_ratio[0]
315
+ target_height = image_size * target_aspect_ratio[1]
316
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
317
+
318
+ # resize the image
319
+ resized_img = image.resize((target_width, target_height))
320
+ processed_images = []
321
+ for i in range(blocks):
322
+ box = (
323
+ (i % (target_width // image_size)) * image_size,
324
+ (i // (target_width // image_size)) * image_size,
325
+ ((i % (target_width // image_size)) + 1) * image_size,
326
+ ((i // (target_width // image_size)) + 1) * image_size,
327
+ )
328
+ # split the image
329
+ split_img = resized_img.crop(box)
330
+ processed_images.append(split_img)
331
+ assert len(processed_images) == blocks
332
+ if use_thumbnail and len(processed_images) != 1:
333
+ thumbnail_img = image.resize((image_size, image_size))
334
+ processed_images.append(thumbnail_img)
335
+ return processed_images
336
+
337
+
338
+ def dynamic_s2_preprocess(image, s2_scales=[384, 768, 1152], max_num=12, image_size=384):
339
+ orig_width, orig_height = image.size
340
+ aspect_ratio = orig_width / orig_height
341
+ min_num = (s2_scales[-1] // s2_scales[0]) ** 2 # at least use number of tiles as the largest scale
342
+
343
+ processed_images = []
344
+
345
+ ##########################################################################################
346
+ ############# Add tiles for all but the last scale using fixed squre ratio ###############
347
+ ##########################################################################################
348
+
349
+ for scale in s2_scales[:-1]:
350
+ target_width = image_size * (scale // s2_scales[0])
351
+ target_height = image_size * (scale // s2_scales[0])
352
+ blocks = (scale // s2_scales[0]) ** 2
353
+
354
+ # resize the image
355
+ resized_img = image.resize((target_width, target_height))
356
+ for i in range(blocks):
357
+ box = (
358
+ (i % (target_width // image_size)) * image_size,
359
+ (i // (target_width // image_size)) * image_size,
360
+ ((i % (target_width // image_size)) + 1) * image_size,
361
+ ((i // (target_width // image_size)) + 1) * image_size,
362
+ )
363
+ # split the image
364
+ split_img = resized_img.crop(box)
365
+ processed_images.append(split_img)
366
+
367
+ ##########################################################################################
368
+ ################ Add tiles for the last scale using dynamic aspect ratio #################
369
+ ##########################################################################################
370
+
371
+ # calculate the existing image aspect ratio
372
+ target_ratios = {
373
+ (i, j)
374
+ for n in range(min_num, max_num + 1)
375
+ for i in range(1, n + 1)
376
+ for j in range(1, n + 1)
377
+ if i * j <= max_num and i * j >= min_num
378
+ }
379
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
380
+
381
+ # find the closest aspect ratio to the target
382
+ target_aspect_ratio = find_closest_aspect_ratio(aspect_ratio, target_ratios, orig_width, orig_height, image_size)
383
+
384
+ # calculate the target width and height
385
+ target_width = image_size * target_aspect_ratio[0]
386
+ target_height = image_size * target_aspect_ratio[1]
387
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
388
+
389
+ # resize the image
390
+ resized_img = image.resize((target_width, target_height))
391
+ for i in range(blocks):
392
+ box = (
393
+ (i % (target_width // image_size)) * image_size,
394
+ (i // (target_width // image_size)) * image_size,
395
+ ((i % (target_width // image_size)) + 1) * image_size,
396
+ ((i // (target_width // image_size)) + 1) * image_size,
397
+ )
398
+ # split the image
399
+ split_img = resized_img.crop(box)
400
+ processed_images.append(split_img)
401
+
402
+ return processed_images, (target_aspect_ratio[1], target_aspect_ratio[0])
403
+
404
+
405
+ def dynamic_process_images_and_prompt(images, prompt, data_args, image_folder=None, max_tiles=None):
406
+ prompt = prompt.split(DEFAULT_IMAGE_TOKEN)
407
+ idx = 0
408
+ all_images = []
409
+ for img in images:
410
+ processed_images = process_image(img, data_args, image_folder, enable_dynamic_res=True, max_tiles=max_tiles)
411
+ all_images.append(processed_images)
412
+ prompt.insert(idx + 1, f"{DEFAULT_IMAGE_TOKEN}\n" * processed_images.shape[0])
413
+ idx += 2
414
+ prompt = "".join(prompt)
415
+ if all_images:
416
+ all_images = torch.cat(all_images)
417
+ else:
418
+ all_images = None
419
+ prompt = prompt.replace(DEFAULT_IMAGE_TOKEN, "")
420
+ return all_images, prompt
421
+
422
+
423
+ def dynamic_s2_process_images_and_prompt(images, prompt, data_args, image_folder=None):
424
+ idx = 0
425
+ all_images = []
426
+ all_block_size = []
427
+ for img in images:
428
+ processed_images, block_size = process_image(img, data_args, image_folder, enable_dynamic_s2=True)
429
+ all_images.append(processed_images)
430
+ all_block_size.append(block_size)
431
+ idx += 2
432
+ if all_images:
433
+ all_images = torch.cat(all_images)
434
+ else:
435
+ all_images = None
436
+ return all_images, all_block_size
437
+
438
+
439
+ def process_image(
440
+ image_file, data_args, image_folder, enable_dynamic_res=False, enable_dynamic_s2=False, max_tiles=None
441
+ ):
442
+ processor = data_args.image_processor
443
+ if isinstance(image_file, str):
444
+ if image_folder is not None:
445
+ image = Image.open(os.path.join(image_folder, image_file)).convert("RGB")
446
+ else:
447
+ image = Image.open(image_file).convert("RGB")
448
+ else:
449
+ # image is stored in bytearray
450
+ image = image_file
451
+ image = image.convert("RGB")
452
+ if hasattr(data_args.image_processor, "crop_size"):
453
+ # CLIP vision tower
454
+ crop_size = data_args.image_processor.crop_size
455
+ else:
456
+ # SIGLIP vision tower
457
+ assert hasattr(data_args.image_processor, "size")
458
+ crop_size = data_args.image_processor.size
459
+ if "dynamic_s2" in data_args.image_aspect_ratio and enable_dynamic_s2:
460
+ assert crop_size["height"] == crop_size["width"]
461
+ images, block_size = dynamic_s2_preprocess(
462
+ image, s2_scales=data_args.s2_scales, max_num=data_args.max_tiles, image_size=crop_size["height"]
463
+ )
464
+ images = [processor.preprocess(image, return_tensors="pt")["pixel_values"][0] for image in images]
465
+ return torch.stack(images), block_size
466
+ if "dynamic" in data_args.image_aspect_ratio and enable_dynamic_res:
467
+ assert crop_size["height"] == crop_size["width"]
468
+ if max_tiles is not None:
469
+ max_num = max_tiles
470
+ else:
471
+ max_num = data_args.max_tiles
472
+ images = dynamic_preprocess(image, min_num=data_args.min_tiles, max_num=max_num, image_size=crop_size["height"])
473
+ images = [processor.preprocess(image, return_tensors="pt")["pixel_values"][0] for image in images]
474
+ return torch.stack(images)
475
+
476
+ if data_args.image_aspect_ratio == "resize":
477
+ image = image.resize((crop_size["width"], crop_size["height"]))
478
+ if data_args.image_aspect_ratio == "pad":
479
+
480
+ def expand2square(pil_img, background_color):
481
+ width, height = pil_img.size
482
+ if width == height:
483
+ return pil_img
484
+ elif width > height:
485
+ result = Image.new(pil_img.mode, (width, width), background_color)
486
+ result.paste(pil_img, (0, (width - height) // 2))
487
+ return result
488
+ else:
489
+ result = Image.new(pil_img.mode, (height, height), background_color)
490
+ result.paste(pil_img, ((height - width) // 2, 0))
491
+ return result
492
+
493
+ image = expand2square(image, tuple(int(x * 255) for x in processor.image_mean))
494
+ image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
495
+ else:
496
+ # Using default behavior of the vision encoder
497
+ # For CLIP, default is central crop
498
+ # For Radio, default is central crop
499
+ # For Siglip, default is resize
500
+ # For InternVIT, default is resize
501
+ image = processor.preprocess(image, return_tensors="pt")["pixel_values"][0]
502
+ return image
503
+
504
+
505
+ def process_images(images, image_processor, model_cfg, enable_dynamic_res=False, max_tiles=None):
506
+ model_cfg.image_processor = image_processor
507
+ new_images = [
508
+ process_image(image, model_cfg, None, enable_dynamic_res=enable_dynamic_res, max_tiles=max_tiles)
509
+ for image in images
510
+ ]
511
+
512
+ if all(x.shape == new_images[0].shape for x in new_images):
513
+ if len(new_images[0].shape) == 4:
514
+ new_images = torch.cat(new_images, dim=0)
515
+ elif len(new_images[0].shape) == 3:
516
+ new_images = torch.stack(new_images, dim=0)
517
+ else:
518
+ raise ValueError(f"new_images rank does not equal to 4, rank: {len(new_images[0].shape)}")
519
+ else:
520
+ raise ValueError("The shape of images in new_images is different!")
521
+ return new_images
522
+
523
+
524
+ def tokenizer_image_token(prompt, tokenizer, return_tensors=None, return_ids=True):
525
+ if return_ids:
526
+ return tokenizer(prompt, return_tensors=return_tensors).input_ids[0]
527
+ else:
528
+ return tokenizer(prompt, return_tensors=return_tensors)
529
+
530
+
531
+ def is_gemma_tokenizer(tokenizer):
532
+ return "gemma" in tokenizer.__class__.__name__.lower()
533
+
534
+
535
+ def get_model_name_from_path(model_path):
536
+ model_path = model_path.strip("/")
537
+ model_paths = model_path.split("/")
538
+ if model_paths[-1].startswith("checkpoint-"):
539
+ return model_paths[-2] + "_" + model_paths[-1]
540
+ else:
541
+ return model_paths[-1]
542
+
543
+
544
+ class KeywordsStoppingCriteria(StoppingCriteria):
545
+ def __init__(self, keywords, tokenizer, input_ids):
546
+ self.keywords = keywords
547
+ self.keyword_ids = []
548
+ self.max_keyword_len = 0
549
+ for keyword in keywords:
550
+ cur_keyword_ids = tokenizer(keyword).input_ids
551
+ if len(cur_keyword_ids) > 1 and cur_keyword_ids[0] == tokenizer.bos_token_id:
552
+ cur_keyword_ids = cur_keyword_ids[1:]
553
+ if len(cur_keyword_ids) > self.max_keyword_len:
554
+ self.max_keyword_len = len(cur_keyword_ids)
555
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
556
+ self.tokenizer = tokenizer
557
+ self.start_len = input_ids.shape[1]
558
+
559
+ def call_for_batch(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
560
+ offset = min(output_ids.shape[1] - self.start_len, self.max_keyword_len)
561
+ self.keyword_ids = [keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids]
562
+ for keyword_id in self.keyword_ids:
563
+ if (output_ids[0, -keyword_id.shape[0] :] == keyword_id).all():
564
+ return True
565
+ outputs = self.tokenizer.batch_decode(output_ids[:, -offset:], skip_special_tokens=True)[0]
566
+ for keyword in self.keywords:
567
+ if keyword in outputs:
568
+ return True
569
+ return False
570
+
571
+ def __call__(self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:
572
+ outputs = []
573
+ for i in range(output_ids.shape[0]):
574
+ outputs.append(self.call_for_batch(output_ids[i].unsqueeze(0), scores))
575
+ return all(outputs)
model_utils_packing.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from importlib import import_module
2
+ from typing import Tuple
3
+
4
+ import torch
5
+ import transformers
6
+ from torch import nn
7
+ from torch.nn import functional as F
8
+
9
+ __all__ = ["patch"]
10
+
11
+
12
+ def _get_unpad_data(attention_mask: torch.Tensor, *args, **kwargs) -> Tuple[torch.Tensor, torch.Tensor, int]:
13
+ if hasattr(_get_unpad_data, "seqlens_in_batch"):
14
+ seqlens_in_batch = _get_unpad_data.seqlens_in_batch
15
+ else:
16
+ seqlens_in_batch = torch.sum(attention_mask, dim=1)
17
+
18
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
19
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
20
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
21
+ return indices, cu_seqlens, max_seqlen_in_batch
22
+
23
+
24
+ def set_seqlens_in_batch(seqlens_in_batch: torch.Tensor) -> None:
25
+ _get_unpad_data.seqlens_in_batch = seqlens_in_batch
26
+
27
+
28
+ def patch(model: nn.Module) -> None:
29
+ if transformers.__version__ < "4.43.0":
30
+ m = import_module(model.__module__)
31
+ if not hasattr(m, "_get_unpad_data"):
32
+ raise ValueError(f"Module {m} does not have function '_get_unpad_data' for packing")
33
+ m._get_unpad_data = _get_unpad_data
34
+ else:
35
+ transformers.modeling_flash_attention_utils._get_unpad_data = _get_unpad_data
modeling_vila.py ADDED
@@ -0,0 +1,1262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import json
3
+ import logging
4
+ import math
5
+ import os
6
+ import os.path
7
+ import os.path as osp
8
+ import shutil
9
+ import warnings
10
+ from abc import ABC
11
+ from collections import OrderedDict, defaultdict, deque
12
+ from copy import deepcopy
13
+ from itertools import chain
14
+ from threading import Thread
15
+ from typing import Any, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ import torch.distributed as dist
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ import torchvision
22
+ from einops import rearrange
23
+ from PIL import Image
24
+ from transformers import (
25
+ AutoConfig,
26
+ AutoModel,
27
+ AutoProcessor,
28
+ AutoTokenizer,
29
+ GenerationConfig,
30
+ LogitsProcessor,
31
+ PretrainedConfig,
32
+ PreTrainedModel,
33
+ Qwen2Config,
34
+ Qwen2ForCausalLM,
35
+ Qwen2PreTrainedModel,
36
+ TextIteratorStreamer,
37
+ )
38
+ from transformers.modeling_outputs import CausalLMOutputWithPast
39
+ from transformers.modeling_utils import ContextManagers, no_init_weights
40
+
41
+ from .auto_processor import VILAProcessor
42
+ from .base_projector import MultimodalProjector, MultimodalProjectorConfig
43
+ from .builder import build_llm_and_tokenizer
44
+ from .configuration_vila import VILAConfig
45
+ from .constants import *
46
+ from .conversation import SeparatorStyle, default_conversation
47
+ from .distributed import all_gather as vila_all_gather
48
+ from .loss import soft_cross_entropy
49
+ from .media import extract_media
50
+ from .media_encoder import BasicImageEncoder, BasicVideoEncoder
51
+ from .mm_utils import process_image, process_images
52
+ from .model_utils_packing import set_seqlens_in_batch
53
+ from .siglip_encoder import SiglipVisionTower, SiglipVisionTowerDynamicS2, SiglipVisionTowerS2
54
+ from .tokenizer_utils import tokenize_conversation
55
+ from .utils import get_model_config, load_tokenizer_then_handle_media_tokens_and_chat_template
56
+
57
+ # from llava.constants import DEFAULT_IMAGE_TOKEN, IGNORE_INDEX, NUM_EXTRA_TOKENS
58
+
59
+ # ease debugging
60
+ python_input = input
61
+
62
+ # quick hack for remote code
63
+ def get_pg_manager():
64
+ return None
65
+
66
+
67
+ def get_model_weights_dtype(model: nn.Module):
68
+ pass
69
+
70
+
71
+ def build_mm_projector(model_type_or_path: str, config: PretrainedConfig) -> PreTrainedModel:
72
+ if model_type_or_path is None:
73
+ return None
74
+ ## load from pretrained model
75
+ if config.resume_path:
76
+ assert os.path.exists(model_type_or_path), f"Resume mm projector path {model_type_or_path} does not exist!"
77
+ return MultimodalProjector.from_pretrained(model_type_or_path, config)
78
+ ## build from scratch
79
+ else:
80
+ mm_projector_cfg = MultimodalProjectorConfig(model_type_or_path)
81
+ mm_projector = MultimodalProjector(mm_projector_cfg, config)
82
+ return mm_projector
83
+
84
+
85
+ def check_dot_in_model_path(model_path: str):
86
+ """Check if the model path contains dot, which will affect the remote code loading."""
87
+ if osp.isdir(model_path): # local model
88
+ if "." in osp.abspath(model_path):
89
+ return True
90
+ else: # remote model
91
+ if "." in model_path:
92
+ return True
93
+ return False
94
+
95
+
96
+ def get_vila_version(model_path: str) -> str:
97
+ VERSIONS = ["vila1.5", "vila-u", "longvila", "nvila", "vila-m3"]
98
+ for version in VERSIONS:
99
+ if version in model_path.lower():
100
+ return version
101
+ return None
102
+
103
+
104
+ def generate_jinja_template(conv_mode: str) -> str:
105
+ if conv_mode == "vicuna_v1":
106
+ return """{% set system_prompt = "A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. " %}
107
+ {% set roles = ["user", "assistant"] %}
108
+ {% set sep = " " %}
109
+
110
+ {{ system_prompt }}
111
+
112
+ {% for message in messages %}
113
+ {% if message['role'] == roles[0] %}
114
+ {{ "USER: " }}{{ sep }}{{ message['content'] }}{{ sep }}
115
+ {% else %}
116
+ {{ "ASSISTANT: " }}{{ sep }}{{ message['content'] }}{{ sep }}
117
+ {% endif %}
118
+ {% endfor %}
119
+ {% if messages[-1]['role'] == 'user' %}
120
+ {{ "ASSISTANT:" }}
121
+ {% endif %}
122
+ """
123
+ elif conv_mode == "llama_3":
124
+ return """{% set system_prompt = "<|begin_of_text|><|start_header_id|>system<|end_header_id|>\\n\\nYou are a helpful language and vision assistant. You are able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language.<|eot_id|>" %}
125
+ {% set roles = ["<|start_header_id|>user<|end_header_id|>\\n\\n", "<|start_header_id|>assistant<|end_header_id|>\\n\\n"]%}
126
+ {% set sep = "<|eot_id|>" %}
127
+
128
+ {{ system_prompt }}
129
+ {% for message in messages %}
130
+ {% if message['role'] == 'user' %}
131
+ {{ roles[0] }}{{ message['content'] }}{{ sep }}
132
+ {% else %}
133
+ {{ roles[1] }}{{ message['content'] }}{{ sep }}
134
+ {% endif %}
135
+ {% endfor %}
136
+ {% if messages[-1]['role'] == 'user' %}
137
+ {{ roles[1] }}
138
+ {% endif %}
139
+ """
140
+ elif conv_mode == "hermes_2":
141
+ return """{% set system_prompt = "<|im_start|>system\nAnswer the questions." %}
142
+ {% set roles = ["<|im_start|>user\n", "<|im_start|>assistant\n"] %}
143
+ {% set sep = "<|im_end|>" %}
144
+
145
+ {{ system_prompt }}{{ sep }}
146
+
147
+ {% for message in messages %}
148
+ {% if message['role'] == 'user' %}
149
+ {{ roles[0] }}{{ message['content'] }}{{ sep }}
150
+ {% else %}
151
+ {{ roles[1] }}{{ message['content'] }}{{ sep }}
152
+ {% endif %}
153
+ {% endfor %}"""
154
+ else:
155
+ raise NotImplementedError(f"Jinja template generation is not implemented for {conv_mode}.")
156
+
157
+
158
+ def build_vision_tower(model_name_or_path: str, config: PretrainedConfig) -> PreTrainedModel:
159
+ ## skip vision tower instantiation
160
+ if model_name_or_path is None:
161
+ return None
162
+
163
+ vision_tower_arch = None
164
+ if config.resume_path and "radio" not in model_name_or_path:
165
+ assert os.path.exists(model_name_or_path), f"Resume vision tower path {model_name_or_path} does not exist!"
166
+ vision_tower_cfg = AutoConfig.from_pretrained(model_name_or_path, trust_remote_code=True)
167
+ vision_tower_arch = vision_tower_cfg.architectures[0].lower()
168
+ vision_tower_name = vision_tower_arch if vision_tower_arch is not None else model_name_or_path
169
+
170
+ use_s2 = getattr(config, "s2", False)
171
+ use_dynamic_s2 = getattr(config, "dynamic_s2", False)
172
+
173
+ if "siglip" in vision_tower_name:
174
+ if use_dynamic_s2:
175
+ vision_tower = SiglipVisionTowerDynamicS2(model_name_or_path, config)
176
+ elif use_s2:
177
+ vision_tower = SiglipVisionTowerS2(model_name_or_path, config)
178
+ else:
179
+ vision_tower = SiglipVisionTower(model_name_or_path, config)
180
+ else:
181
+ raise NotImplementedError(f"Unknown vision tower: {model_name_or_path}")
182
+
183
+ config.mm_hidden_size = (
184
+ vision_tower.config.hidden_size if not (use_s2 or use_dynamic_s2) else vision_tower.hidden_size
185
+ )
186
+ return vision_tower
187
+
188
+
189
+ class VILAPretrainedModel(PreTrainedModel):
190
+ config_class = VILAConfig
191
+ main_input_name = "input_embeds"
192
+ supports_gradient_checkpointing = True
193
+ _supports_flash_attn_2 = True
194
+ _no_split_modules = [] #["Qwen2DecoderLayer", "SiglipEncoderLayer"]
195
+
196
+ def __init__(self, config: VILAConfig, *args, **kwargs):
197
+ super().__init__(config)
198
+ self.config = config
199
+ cfgs = get_model_config(config)
200
+ if len(cfgs) == 3:
201
+ llm_cfg, vision_tower_cfg, mm_projector_cfg = cfgs
202
+ else:
203
+ raise ValueError("`llm_cfg` `mm_projector_cfg` `vision_tower_cfg` not found in the config.")
204
+
205
+ # loading on auto by default
206
+ device_map = kwargs.get("device_map", "auto")
207
+ self.mm_projector = build_mm_projector(mm_projector_cfg, config)
208
+ self.vision_tower = build_vision_tower(vision_tower_cfg, config)
209
+ print("device_map", device_map)
210
+ if device_map in ["auto", "cuda"]:
211
+ self.mm_projector = self.mm_projector.cuda()
212
+ self.vision_tower = self.vision_tower.cuda()
213
+ # set device_map auto can autoamtically shard llm to different devices
214
+ self.llm, self.tokenizer = self.init_llm(llm_cfg, config, device_map=device_map)
215
+
216
+ # NOTE(ligeng): hard code to set padding_side to left
217
+ self.tokenizer.padding_side = "left"
218
+ # TODO(ligeng): need to add other decoders from config
219
+ self.encoders = {"image": BasicImageEncoder(self), "video": BasicVideoEncoder(self)}
220
+
221
+ self.post_config()
222
+ self.is_loaded = True
223
+
224
+ assert (
225
+ self.llm is not None or self.vision_tower is not None or self.mm_projector is not None
226
+ ), "At least one of the components must be instantiated."
227
+
228
+ @classmethod
229
+ def convert_vila_dev_ckpt_to_remote(
230
+ self,
231
+ model_path: str,
232
+ output_dir: str = None,
233
+ vila_version: str | None = None,
234
+ conv_mode: str | None = None,
235
+ copy: bool = False,
236
+ copy_weights: bool = True,
237
+ copy_code: bool = True,
238
+ *model_args,
239
+ **kwargs,
240
+ ):
241
+ # assert type(self) == VILAForCasualLM, "This method is only available for VILAForCasualLM."
242
+ assert model_path != output_dir, "model_path and output_dir cannot be the same"
243
+ if os.path.isdir(model_path):
244
+ model_path = model_path
245
+ else:
246
+ from huggingface_hub import HfApi, snapshot_download
247
+
248
+ model_path = snapshot_download(model_path)
249
+ print("downloading HF model to", model_path)
250
+
251
+ if check_dot_in_model_path(model_path) and output_dir is None:
252
+ raise ValueError(
253
+ f"Model path {model_path} contains a dot, which will affect the remote code loading. Please specify the output directory without dot in the path to fix this issue."
254
+ )
255
+ if output_dir is not None and "." in output_dir:
256
+ raise ValueError(
257
+ f"Output directory {output_dir} contains a dot, which will affect the remote code loading. Please specify a valid output directory without dots."
258
+ )
259
+
260
+ if copy:
261
+ print("copy is set to True, copying weights and code to output_dir")
262
+ copy_weights = copy_code = True
263
+ # copy weights and code to output_dir
264
+ self.copy_or_symlink_directory(model_path, output_dir, copy=copy_weights)
265
+ self.copy_remote_py_files(output_dir, copy=copy_code)
266
+
267
+ if vila_version is None:
268
+ vila_version = get_vila_version(output_dir)
269
+
270
+ cfg_path = os.path.join(output_dir, "config.json")
271
+ config = json.load(open(cfg_path))
272
+ config["version"] = "2.0" # nvila tag
273
+ config["architectures"] = ["VILAForCasualLM"]
274
+ config["auto_map"] = {
275
+ "AutoProcessor": "auto_processor.VILAProcessor",
276
+ "AutoConfig": "modeling_vila.VILAConfig",
277
+ "AutoModel": "modeling_vila.VILAForCasualLM",
278
+ "AutoModelForCausalLM": "modeling_vila.VILAForCasualLM",
279
+ }
280
+ # vila1.5 legacy support
281
+ config["model_type"] = "vila"
282
+ if vila_version in ["vila1.5", "vila-m3"]:
283
+ if conv_mode is None:
284
+ raise ValueError(f"Please specify the conversation mode for {output_dir}.")
285
+ config["chat_template"] = conv_mode
286
+ jinja_template = generate_jinja_template(conv_mode)
287
+ jinja_path = os.path.join(output_dir, f"{conv_mode}.jinja")
288
+ with open(jinja_path, "w") as f:
289
+ f.write(jinja_template)
290
+ json.dump(config, open(cfg_path, "w"), indent=2)
291
+
292
+ ##########################################################################################
293
+ config = AutoConfig.from_pretrained(output_dir, trust_remote_code=True)
294
+ tokenizer = load_tokenizer_then_handle_media_tokens_and_chat_template(output_dir, config)
295
+ tokenizer.save_pretrained(osp.join(output_dir, "llm"))
296
+ ##########################################################################################
297
+
298
+ @classmethod
299
+ def copy_or_symlink_directory(cls, model_path, output_dir, copy=True):
300
+ # Create output directory if it doesn't exist
301
+ os.makedirs(output_dir, exist_ok=True)
302
+ # Create symlinks for all files in model_path to output_dir
303
+ for item in os.listdir(model_path):
304
+ src_path = os.path.join(model_path, item)
305
+ dst_path = os.path.join(output_dir, item)
306
+
307
+ # Remove existing file/directory at destination if it exists
308
+ if os.path.exists(dst_path):
309
+ if os.path.islink(dst_path):
310
+ os.unlink(dst_path)
311
+ elif os.path.isdir(dst_path):
312
+ shutil.rmtree(dst_path)
313
+ else:
314
+ os.remove(dst_path)
315
+
316
+ # Create symlink
317
+ if copy:
318
+ if os.path.isdir(src_path):
319
+ shutil.copytree(src_path, dst_path)
320
+ else:
321
+ shutil.copy2(src_path, dst_path)
322
+ print(f"Copied {src_path} to {dst_path}")
323
+ else:
324
+ os.symlink(src_path, dst_path)
325
+ print(f"Created symlink from {src_path} to {dst_path}")
326
+
327
+ @classmethod
328
+ def copy_remote_py_files(cls, output_dir, copy=True):
329
+ ## copy .py and REAMDE for next loading remote code
330
+ current_file_path = os.path.abspath(__file__)
331
+ current_folder = os.path.dirname(current_file_path)
332
+ for file_name in os.listdir(current_folder):
333
+ if file_name == "INSTRUCTIONS.md":
334
+ src_fname = os.path.join(current_folder, file_name)
335
+ dst_fname = os.path.join(output_dir, "README.md")
336
+ if os.path.exists(dst_fname):
337
+ old_reamde = open(dst_fname).read()
338
+ else:
339
+ old_reamde = ""
340
+ with open(src_fname) as src, open(dst_fname, "w") as dst:
341
+ dst.write(src.read())
342
+ dst.write(old_reamde)
343
+ print("[HF remote code] REAMDE ", src_fname, "to", dst_fname)
344
+ if file_name.endswith(".py") or file_name.endswith(".jinja"):
345
+ full_file_name = os.path.join(current_folder, file_name)
346
+ if os.path.isfile(full_file_name):
347
+ if copy:
348
+ shutil.copy(full_file_name, output_dir)
349
+ print("[HF remote code] copying", full_file_name, "to", output_dir)
350
+ else:
351
+ # symlink to ease development
352
+ if os.path.exists(os.path.join(output_dir, file_name)):
353
+ os.remove(os.path.join(output_dir, file_name))
354
+ os.symlink(full_file_name, os.path.join(output_dir, file_name))
355
+ print("[HF remote code] linking", full_file_name, "to", output_dir)
356
+
357
+ def save_pretrained(self, output_dir, state_dict=None, **kwargs):
358
+ if state_dict is None:
359
+ # other wise fetch from deepspeed
360
+ # state_dict = accelerator.get_state_dict(is_deepspeed_enabled)
361
+ state_dict = self.state_dict()
362
+
363
+ if getattr(self, "tokenizer", None):
364
+ self.tokenizer.save_pretrained(osp.join(output_dir, "llm"))
365
+
366
+ if self.get_llm():
367
+ print(f"saving llm to {osp.join(output_dir, 'llm')}")
368
+ self.llm.config._name_or_path = osp.join(output_dir, "llm")
369
+ llm_state_dict = OrderedDict({k.split("llm.")[-1]: v for k, v in state_dict.items() if "llm" in k})
370
+ self.llm.save_pretrained(os.path.join(output_dir, "llm"), state_dict=llm_state_dict)
371
+ self.config.llm_cfg = self.llm.config
372
+
373
+ if self.get_vision_tower():
374
+ print(f"saving vision_tower to {osp.join(output_dir, 'vision_tower')}")
375
+ self.vision_tower.config._name_or_path = osp.join(output_dir, "vision_tower")
376
+ vision_tower_state_dict = OrderedDict(
377
+ {k.split("vision_tower.vision_tower.")[-1]: v for k, v in state_dict.items() if "vision_tower" in k}
378
+ )
379
+ self.vision_tower.vision_tower.save_pretrained(
380
+ os.path.join(output_dir, "vision_tower"),
381
+ state_dict=vision_tower_state_dict,
382
+ )
383
+ self.vision_tower.image_processor.save_pretrained(os.path.join(output_dir, "vision_tower"))
384
+ self.config.vision_tower_cfg = self.vision_tower.config
385
+ if hasattr(self.config.vision_tower_cfg, "auto_map"):
386
+ if "radio" not in self.get_vision_tower().__class__.__name__.lower():
387
+ delattr(self.config.vision_tower_cfg, "auto_map")
388
+
389
+ if self.get_mm_projector():
390
+ print(f"saving mm_projector to {osp.join(output_dir, 'mm_projector')}")
391
+ self.mm_projector.config._name_or_path = osp.join(output_dir, "mm_projector")
392
+ mm_projector_state_dict = OrderedDict(
393
+ {k.split("mm_projector.")[-1]: v for k, v in state_dict.items() if "mm_projector" in k}
394
+ )
395
+ self.mm_projector.save_pretrained(
396
+ os.path.join(output_dir, "mm_projector"),
397
+ state_dict=mm_projector_state_dict,
398
+ )
399
+ self.config.mm_projector_cfg = self.mm_projector.config
400
+
401
+ ## update and save top-level config
402
+ self.config._name_or_path = output_dir
403
+ self.config.architectures = [self.__class__.__name__]
404
+ self.config.save_pretrained(output_dir)
405
+
406
+ ## copy .py and REAMDE for next loading remote code
407
+ self.copy_remote_py_files(output_dir)
408
+
409
+ @classmethod
410
+ def from_pretrained(
411
+ cls,
412
+ pretrained_model_name_or_path: Optional[str] = None,
413
+ *model_args,
414
+ config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
415
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
416
+ ignore_mismatched_sizes: bool = False,
417
+ force_download: bool = False,
418
+ local_files_only: bool = False,
419
+ token: Optional[Union[str, bool]] = None,
420
+ revision: str = "main",
421
+ use_safetensors: Optional[bool] = None,
422
+ weights_only: bool = True,
423
+ **kwargs,
424
+ ):
425
+ # print("DEBUG2", kwargs); input()
426
+ config = AutoConfig.from_pretrained(pretrained_model_name_or_path, trust_remote_code=True)
427
+ return cls._from_config(config, **kwargs)
428
+
429
+ def init_llm(self, llm_config, config, *args, **kwargs):
430
+ self.llm, self.tokenizer = build_llm_and_tokenizer(llm_config, config, *args, **kwargs)
431
+ # hard coded for NVILA
432
+ # variables for XGrammar
433
+ # print("DEBUG", len(self.tokenizer.added_tokens_encoder.keys()), self.tokenizer.added_tokens_encoder.keys())
434
+ NUM_EXTRA_TOKENS = len(self.tokenizer.added_tokens_encoder.keys())
435
+
436
+ self.pad_token_list = (
437
+ self.tokenizer.pad_token_id,
438
+ self.tokenizer.eos_token_id,
439
+ self.tokenizer.tokenize("<|endoftext|>")[0], # for qwen
440
+ )
441
+
442
+ # TODO: SENTINEL_TOKEN is not added, need to check with Zhijian
443
+ self.vocab_size = self.tokenizer.vocab_size + NUM_EXTRA_TOKENS
444
+ # XGrammar tokenizer and grammar compiler
445
+ # lazy init only when specified json output during inference
446
+ self.grammar_compiler = None
447
+ self.llm.resize_token_embeddings(len(self.tokenizer))
448
+ return self.llm, self.tokenizer
449
+
450
+ def post_config(self):
451
+ ######################################################################
452
+ # TODO: need to check dtype with jason
453
+ self.llm = self.llm.to(torch.bfloat16)
454
+ self.mm_projector = self.mm_projector.to(torch.bfloat16)
455
+ self.vision_tower = self.vision_tower.to(torch.bfloat16)
456
+ ######################################################################
457
+ self.training = self.llm.training
458
+ if self.training:
459
+ self.train()
460
+ else:
461
+ self.eval()
462
+ ## configuration
463
+ if getattr(self.config, "llm_cfg", None) is None:
464
+ self.config.llm_cfg = self.llm.config
465
+ if getattr(self.config, "vision_tower_cfg", None) is None:
466
+ self.config.vision_tower_cfg = self.vision_tower.config
467
+ if getattr(self.config, "mm_projector_cfg", None) is None:
468
+ self.config.mm_projector_cfg = self.mm_projector.config
469
+
470
+ def get_llm(self):
471
+ llm = getattr(self, "llm", None)
472
+ if type(llm) is list:
473
+ llm = llm[0]
474
+ return llm
475
+
476
+ def get_lm_head(self):
477
+ lm_head = getattr(self.get_llm(), "lm_head", None)
478
+ return lm_head
479
+
480
+ def get_vision_tower(self):
481
+ vision_tower = getattr(self, "vision_tower", None)
482
+ if type(vision_tower) is list:
483
+ vision_tower = vision_tower[0]
484
+ return vision_tower
485
+
486
+ def get_mm_projector(self):
487
+ mm_projector = getattr(self, "mm_projector", None)
488
+ if type(mm_projector) is list:
489
+ mm_projector = mm_projector[0]
490
+ return mm_projector
491
+
492
+ def freezed_module_patch(self):
493
+ """
494
+ Huggingface will call model.train() at each training_step. To ensure the expected behaviors for modules like dropout, batchnorm, etc., we need to call model.eval() for the freezed modules.
495
+ """
496
+ if self.training:
497
+ if self.get_llm() and not getattr(self.config, "tune_language_model", False):
498
+ pass
499
+ # logging.warning("Caution: Your LLM is currently in training mode, ensuring accurate gradient computation. Please be vigilant, particularly regarding BatchNorm and Dropout operations.")
500
+ if self.get_vision_tower() and not getattr(self.config, "tune_vision_tower", False):
501
+ self.get_vision_tower().eval()
502
+ if self.get_mm_projector() and not getattr(self.config, "tune_mm_projector", False):
503
+ self.get_mm_projector().eval()
504
+
505
+
506
+ class VILAForCasualLM(VILAPretrainedModel):
507
+ def __init__(self, config: VILAConfig, *args, **kwargs):
508
+ super().__init__(config, *args, **kwargs)
509
+
510
+ def merge_features_for_dynamic_s2(self, image_features, block_sizes):
511
+ scales = self.get_vision_tower().scales
512
+ resize_output_to_scale_idx = self.get_vision_tower().resize_output_to_scale_idx
513
+
514
+ image_features_each_image = []
515
+ new_block_sizes = []
516
+ block_cnt = 0
517
+ for block_size_each_image in block_sizes:
518
+ if block_size_each_image is None:
519
+ cur_features = image_features[block_cnt : block_cnt + 1]
520
+ cur_features = rearrange(cur_features, "1 (h w) c -> 1 c h w", h=int(cur_features.shape[1] ** 0.5))
521
+ cur_features = cur_features.repeat(1, len(scales), 1, 1)
522
+ image_features_each_image.append(cur_features)
523
+ new_block_sizes.append((1, 1))
524
+ block_cnt += 1
525
+ else:
526
+ cur_features_each_scale = []
527
+ for scale in scales[:-1]:
528
+ num_blocks_this_scale = (scale // scales[0]) ** 2
529
+ cur_features_each_scale.append(
530
+ self.merge_chessboard(
531
+ image_features[block_cnt : block_cnt + num_blocks_this_scale],
532
+ num_split_h=scale // scales[0],
533
+ num_split_w=scale // scales[0],
534
+ )
535
+ ) # 1 * C * H * W
536
+ block_cnt += num_blocks_this_scale
537
+ num_blocks_last_scale = block_size_each_image[0] * block_size_each_image[1]
538
+ cur_features_each_scale.append(
539
+ self.merge_chessboard(
540
+ image_features[block_cnt : block_cnt + num_blocks_last_scale],
541
+ num_split_h=block_size_each_image[0],
542
+ num_split_w=block_size_each_image[1],
543
+ )
544
+ ) # 1 * C * H * W
545
+ block_cnt += num_blocks_last_scale
546
+
547
+ # resize and concat features from different scales
548
+ output_size = cur_features_each_scale[resize_output_to_scale_idx].shape[-2:]
549
+ cur_features = torch.cat(
550
+ [
551
+ F.interpolate(cur_features_each_scale[i].to(torch.float32), size=output_size, mode="area").to(
552
+ cur_features_each_scale[i].dtype
553
+ )
554
+ for i in range(len(cur_features_each_scale))
555
+ ],
556
+ dim=1,
557
+ )
558
+ # cur_features = rearrange(cur_features, "1 c h w -> (h w) c")
559
+
560
+ image_features_each_image.append(cur_features)
561
+
562
+ if resize_output_to_scale_idx == len(scales) - 1 or resize_output_to_scale_idx == -1:
563
+ new_block_sizes.append(block_size_each_image)
564
+ else:
565
+ new_block_sizes.append(
566
+ (
567
+ scales[resize_output_to_scale_idx] // scales[0],
568
+ scales[resize_output_to_scale_idx] // scales[0],
569
+ )
570
+ )
571
+
572
+ assert block_cnt == len(image_features)
573
+
574
+ return image_features_each_image, new_block_sizes
575
+
576
+ def encode_images(self, images, block_sizes: Optional[Optional[Tuple[int, ...]]] = None):
577
+ if block_sizes is None:
578
+ block_sizes = [None] * len(images)
579
+ if getattr(self.config, "dynamic_s2", False):
580
+ image_features = self.get_vision_tower()(images)
581
+ image_features, new_block_sizes = self.merge_features_for_dynamic_s2(image_features, block_sizes)
582
+
583
+ image_features = [
584
+ self.split_chessboard(x, block_size[0], block_size[1])
585
+ for x, block_size in zip(image_features, new_block_sizes)
586
+ ] # list of B * C * H * W tensors
587
+ image_features = torch.cat(
588
+ [rearrange(x, "b c h w -> b (h w) c") for x in image_features], dim=0
589
+ ) # B * N * C
590
+ image_features = self.get_mm_projector()(image_features)
591
+ image_features = list(
592
+ image_features.split([block_size[0] * block_size[1] for block_size in new_block_sizes], dim=0)
593
+ )
594
+ image_features = [
595
+ self.merge_chessboard(x, block_size[0], block_size[1])
596
+ for x, block_size in zip(image_features, new_block_sizes)
597
+ ] # list of 1 * C * H * W tensors
598
+ image_features = [rearrange(x, "1 c h w -> (h w) c") for x in image_features] # list of N * C tensors
599
+ if all([feature.shape[0] == image_features[0].shape[0] for feature in image_features]):
600
+ image_features = torch.stack(image_features, dim=0)
601
+ else:
602
+ image_features = self.get_vision_tower()(images)
603
+ image_features = self.get_mm_projector()(image_features)
604
+ return image_features
605
+
606
+ def train(self, mode: bool = True):
607
+ super().train(mode)
608
+ return self
609
+
610
+ def _embed(
611
+ self,
612
+ input_ids: torch.Tensor,
613
+ media: Dict[str, List[torch.Tensor]],
614
+ media_config: Dict[str, Dict[str, Any]],
615
+ labels: Optional[torch.Tensor],
616
+ attention_mask: Optional[torch.Tensor],
617
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
618
+ # NOTE(ligeng): deep copy to avoid modifying the original media and media_config
619
+ media = copy.deepcopy(media)
620
+ media_config = copy.deepcopy(media_config)
621
+
622
+ labels = labels if labels is not None else torch.full_like(input_ids, IGNORE_INDEX)
623
+ attention_mask = attention_mask if attention_mask is not None else torch.ones_like(input_ids, dtype=torch.bool)
624
+
625
+ PROCESS_GROUP_MANAGER = get_pg_manager()
626
+ if PROCESS_GROUP_MANAGER is not None:
627
+ for name in media:
628
+ self.encoders[name].end_tokens = None
629
+
630
+ # Extract text and media embeddings
631
+ text_embeds = self.llm.model.embed_tokens(input_ids)
632
+ if media is not None:
633
+ media_embeds = self.__embed_media_tokens(media, media_config)
634
+ else:
635
+ # no media was provided, so we just return an empty dict
636
+ media_embeds = {}
637
+
638
+ # This is a workaround to make sure the dummy embeddings are consumed
639
+ while media_embeds.get("dummy"):
640
+ dummy_embed = media_embeds["dummy"].popleft()
641
+ text_embeds += torch.sum(dummy_embed) * 0
642
+
643
+ # Remove padding
644
+ batch_size = labels.shape[0]
645
+ text_embeds = [text_embeds[k][attention_mask[k]] for k in range(batch_size)]
646
+ labels = [labels[k][attention_mask[k]] for k in range(batch_size)]
647
+
648
+ # Build inverse mapping from token ID to media name
649
+ media_tokens = {}
650
+ for name, token_id in self.tokenizer.media_token_ids.items():
651
+ media_tokens[token_id] = name
652
+
653
+ # Fuse text and media embeddings
654
+ inputs_m, labels_m = [], []
655
+ for k in range(batch_size):
656
+ inputs_mk, labels_mk = [], []
657
+ pos = 0
658
+ while pos < len(labels[k]):
659
+ if input_ids[k][pos].item() in media_tokens:
660
+ end = pos + 1
661
+ name = media_tokens[input_ids[k][pos].item()]
662
+ input = media_embeds[name].popleft()
663
+ label = torch.full([input.shape[0]], IGNORE_INDEX, device=labels[k].device, dtype=labels[k].dtype)
664
+ elif input_ids[k][pos].item() in self.pad_token_list:
665
+ # skip pad tokens
666
+ end = pos + 1
667
+ pos = end
668
+ continue
669
+ else:
670
+ end = pos
671
+ while end < len(labels[k]) and input_ids[k][end].item() not in media_tokens:
672
+ end += 1
673
+ input = text_embeds[k][pos:end]
674
+ label = labels[k][pos:end]
675
+
676
+ inputs_mk.append(input)
677
+ labels_mk.append(label)
678
+ pos = end
679
+ inputs_m.append(torch.cat(inputs_mk, dim=0))
680
+ labels_m.append(torch.cat(labels_mk, dim=0))
681
+ inputs, labels = inputs_m, labels_m
682
+
683
+ # Check if all media embeddings are consumed
684
+ for name in media_embeds:
685
+ if media_embeds[name]:
686
+ raise ValueError(f"Not all {name} embeddings are consumed! Still {len(media_embeds[name])} left.")
687
+
688
+ # Truncate sequences to `model_max_length` as media embeddings are inserted
689
+ inputs, labels = self.__truncate_sequence(inputs, labels)
690
+
691
+ # Pad sequences to the longest one in the batch
692
+ return self.__batchify_sequence(inputs, labels)
693
+
694
+ def __embed_media_tokens(
695
+ self,
696
+ media: Dict[str, List[torch.Tensor]],
697
+ media_config: Dict[str, Dict[str, Any]],
698
+ ) -> Dict[str, List[torch.Tensor]]:
699
+ embeds = defaultdict(deque)
700
+ for name in media:
701
+ if self.training:
702
+ # Gather metainfo of media objects from all ranks
703
+ info = [{"shape": tensor.shape, "dtype": tensor.dtype} for tensor in media.get(name, [])]
704
+ infos = list(chain(vila_all_gather(info)))
705
+
706
+ # The entire batch does not contain any media objects of this type.
707
+ if not infos:
708
+ continue
709
+
710
+ # Create a dummy tensor to ensure the encoder is called, otherwise the training will hang.
711
+ if media.get(name) is None or len(media[name]) == 0:
712
+ dummy = torch.zeros(infos[0]["shape"], dtype=infos[0]["dtype"], device=self.device)
713
+ embeds["dummy"].extend(self.encoders[name]([dummy], media_config[name]))
714
+ continue
715
+ embeds[name] = deque(self.encoders[name](media[name], media_config[name]))
716
+ return embeds
717
+
718
+ def __truncate_sequence(
719
+ self, inputs: List[torch.Tensor], labels: List[torch.Tensor]
720
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
721
+ if self.training and any(len(input) > self.tokenizer.model_max_length for input in inputs):
722
+ warnings.warn(f"Truncating sequences to `model_max_length` ({self.tokenizer.model_max_length}).")
723
+ inputs = [input[: self.tokenizer.model_max_length] for input in inputs]
724
+ labels = [label[: self.tokenizer.model_max_length] for label in labels]
725
+ return inputs, labels
726
+
727
+ def __batchify_sequence(
728
+ self, inputs: List[torch.Tensor], labels: List[torch.Tensor]
729
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
730
+ batch_size = len(inputs)
731
+ device = inputs[0].device
732
+ hidden_size = inputs[0].shape[1]
733
+ max_length = max(inputs[k].shape[0] for k in range(batch_size))
734
+ attention_mask = torch.ones((batch_size, max_length), dtype=torch.bool, device=device)
735
+
736
+ inputs_p, labels_p = [], []
737
+ for k in range(batch_size):
738
+ size_pk = max_length - inputs[k].shape[0]
739
+ inputs_pk = torch.zeros((size_pk, hidden_size), dtype=inputs[k].dtype, device=device)
740
+ labels_pk = torch.full((size_pk,), IGNORE_INDEX, dtype=labels[k].dtype, device=device)
741
+ if self.tokenizer.padding_side == "right":
742
+ attention_mask[k, inputs[k].shape[0] :] = False
743
+ inputs_pk = torch.cat([inputs[k], inputs_pk], dim=0)
744
+ labels_pk = torch.cat([labels[k], labels_pk], dim=0)
745
+ else:
746
+ attention_mask[k, : -inputs[k].shape[0]] = False
747
+ inputs_pk = torch.cat([inputs_pk, inputs[k]], dim=0)
748
+ labels_pk = torch.cat([labels_pk, labels[k]], dim=0)
749
+ inputs_p.append(inputs_pk)
750
+ labels_p.append(labels_pk)
751
+
752
+ inputs = torch.stack(inputs_p, dim=0)
753
+ labels = torch.stack(labels_p, dim=0)
754
+ return inputs, labels, attention_mask
755
+
756
+ def repack_multimodal_data(self, inputs_embeds, attention_mask, position_ids, labels):
757
+ # Handle sequence parallelism
758
+ PROCESS_GROUP_MANAGER = get_pg_manager()
759
+
760
+ # We do re-sharding instead of packing here to ensure the sequence length is the same across all ranks.
761
+ if PROCESS_GROUP_MANAGER is not None:
762
+ sp_degree = PROCESS_GROUP_MANAGER.sp_degree
763
+ sp_rank = PROCESS_GROUP_MANAGER.sp_rank
764
+ sp_group = PROCESS_GROUP_MANAGER.sp_pg
765
+ ring_degree = PROCESS_GROUP_MANAGER.ring_degree
766
+ ring_rank = PROCESS_GROUP_MANAGER.ring_rank
767
+ ring_type = PROCESS_GROUP_MANAGER.ring_type
768
+ ulysses_degree = PROCESS_GROUP_MANAGER.ulysses_degree
769
+ ulysses_rank = PROCESS_GROUP_MANAGER.ulysses_rank
770
+
771
+ bs, shard_seqlen = position_ids.shape
772
+ sp_seq_len = [torch.zeros(1, dtype=torch.int64, device=position_ids.device) for _ in range(sp_degree)]
773
+ dist.all_gather(sp_seq_len, torch.tensor(shard_seqlen, device=position_ids.device), group=sp_group)
774
+ sp_seq_len_cat = torch.cat(sp_seq_len, dim=0)
775
+
776
+ if sp_rank == 0:
777
+ original_start_id = 0
778
+ else:
779
+ original_start_id = torch.sum(sp_seq_len_cat[:sp_rank]).item()
780
+ original_end_id = torch.sum(sp_seq_len_cat[: sp_rank + 1]).item()
781
+
782
+ # Gather attention_mask, position_ids, labels and input_embeds
783
+ all_inputs_embeds = torch.zeros(
784
+ bs,
785
+ torch.sum(sp_seq_len_cat),
786
+ inputs_embeds.shape[-1],
787
+ dtype=inputs_embeds.dtype,
788
+ device=inputs_embeds.device,
789
+ ).contiguous()
790
+ all_inputs_embeds[:, original_start_id:original_end_id, :] += inputs_embeds
791
+ dist.barrier(group=sp_group)
792
+ dist.all_reduce(all_inputs_embeds, group=sp_group)
793
+ dist.barrier(group=sp_group)
794
+
795
+ attention_mask_list = [
796
+ torch.zeros((bs, sp_seq_len[i]), dtype=attention_mask.dtype, device=attention_mask.device)
797
+ for i in range(sp_degree)
798
+ ]
799
+ position_ids_list = [
800
+ torch.zeros((bs, sp_seq_len[i]), dtype=position_ids.dtype, device=position_ids.device)
801
+ for i in range(sp_degree)
802
+ ]
803
+ labels_list = [
804
+ torch.zeros((bs, sp_seq_len[i]), dtype=labels.dtype, device=labels.device) for i in range(sp_degree)
805
+ ]
806
+
807
+ dist.all_gather(attention_mask_list, attention_mask, group=sp_group)
808
+ dist.all_gather(position_ids_list, position_ids, group=sp_group)
809
+ dist.all_gather(labels_list, labels, group=sp_group)
810
+
811
+ effective_seqlen_list = [attention_mask_list[i].sum(dim=-1) for i in range(sp_degree)]
812
+ effective_seqlen = torch.stack(effective_seqlen_list, dim=-1)
813
+ effective_seqlen_batch_list = torch.unbind(effective_seqlen, dim=0)
814
+
815
+ global_attention_mask_list = []
816
+ global_position_ids_list = []
817
+ global_labels_list = []
818
+ global_inputs_embeds_list = []
819
+ for i in range(bs):
820
+ global_attention_mask_batch_list = []
821
+ global_position_ids_batch_list = []
822
+ global_labels_batch_list = []
823
+ global_inputs_embeds_batch_list = []
824
+ for j in range(sp_degree):
825
+ eff_len = effective_seqlen_batch_list[i][j]
826
+ prev_len = torch.sum(sp_seq_len_cat[:j]).item() if j > 0 else 0
827
+
828
+ global_attention_mask_batch_list.append(attention_mask_list[j][i, :eff_len])
829
+ global_position_ids_batch_list.append(position_ids_list[j][i, :eff_len])
830
+ global_labels_batch_list.append(labels_list[j][i, :eff_len])
831
+ global_inputs_embeds_batch_list.append(all_inputs_embeds[i, prev_len : prev_len + eff_len, :])
832
+ global_attention_mask_list.append(torch.cat(global_attention_mask_batch_list, dim=0))
833
+ global_position_ids_list.append(torch.cat(global_position_ids_batch_list, dim=0))
834
+ global_labels_list.append(torch.cat(global_labels_batch_list, dim=0))
835
+ global_inputs_embeds_list.append(torch.cat(global_inputs_embeds_batch_list, dim=0))
836
+
837
+ global_attention_mask = torch.nn.utils.rnn.pad_sequence(
838
+ global_attention_mask_list, batch_first=True, padding_value=False
839
+ )
840
+ global_position_ids = torch.nn.utils.rnn.pad_sequence(
841
+ global_position_ids_list, batch_first=True, padding_value=-1
842
+ )
843
+ global_labels = torch.nn.utils.rnn.pad_sequence(
844
+ global_labels_list, batch_first=True, padding_value=IGNORE_INDEX
845
+ )
846
+ global_inputs_embeds = torch.nn.utils.rnn.pad_sequence(
847
+ global_inputs_embeds_list, batch_first=True, padding_value=0
848
+ )
849
+
850
+ # Re-shard the inputs
851
+ if ring_degree > 1:
852
+ total_effective_seqlen = torch.sum(effective_seqlen, dim=1)
853
+ new_seqlen_per_rank = total_effective_seqlen // sp_degree
854
+ assert torch.all(
855
+ total_effective_seqlen % sp_degree == 0
856
+ ), "total_effective_seqlen must be divisible by sp_degree"
857
+
858
+ max_new_seqlen = torch.max(new_seqlen_per_rank).item()
859
+
860
+ new_attention_mask = torch.zeros(
861
+ (bs, max_new_seqlen), dtype=global_attention_mask.dtype, device=global_attention_mask.device
862
+ )
863
+ new_position_ids = torch.zeros(
864
+ (bs, max_new_seqlen), dtype=global_position_ids.dtype, device=global_position_ids.device
865
+ )
866
+ new_labels = torch.full(
867
+ (bs, max_new_seqlen), IGNORE_INDEX, dtype=global_labels.dtype, device=global_labels.device
868
+ )
869
+ new_inputs_embeds = torch.zeros(
870
+ (bs, max_new_seqlen, global_inputs_embeds.shape[-1]),
871
+ dtype=global_inputs_embeds.dtype,
872
+ device=global_inputs_embeds.device,
873
+ )
874
+
875
+ if ring_type == "ring_varlen":
876
+ for i in range(bs):
877
+ start_idx = new_seqlen_per_rank[i] * sp_rank
878
+ end_idx = start_idx + new_seqlen_per_rank[i]
879
+ new_attention_mask[i, : new_seqlen_per_rank[i]] = global_attention_mask[i, start_idx:end_idx]
880
+ new_position_ids[i, : new_seqlen_per_rank[i]] = global_position_ids[i, start_idx:end_idx]
881
+ new_labels[i, : new_seqlen_per_rank[i]] = global_labels[i, start_idx:end_idx]
882
+ new_inputs_embeds[i, : new_seqlen_per_rank[i], :] = global_inputs_embeds[
883
+ i, start_idx:end_idx, :
884
+ ]
885
+ elif ring_type == "zigzag_ring_varlen":
886
+ chunk_size = total_effective_seqlen // (2 * sp_degree)
887
+ for i in range(bs):
888
+ # Zigzag pattern indices
889
+ if sp_degree == ring_degree:
890
+ forward_rank_idx = sp_rank
891
+ backward_rank_idx = 2 * sp_degree - sp_rank - 1
892
+ else:
893
+ ulysses_offset = ulysses_rank * ring_degree * 2
894
+ forward_rank_idx = ring_rank + ulysses_offset
895
+ backward_rank_idx = sp_degree - ring_rank - 1 + ulysses_offset
896
+
897
+ # Calculate start and end indices for the forward and backward zigzag
898
+ start_idx_fwd = forward_rank_idx * chunk_size[i]
899
+ end_idx_fwd = start_idx_fwd + chunk_size[i]
900
+
901
+ start_idx_bwd = backward_rank_idx * chunk_size[i]
902
+ end_idx_bwd = start_idx_bwd + chunk_size[i]
903
+
904
+ # Fill new tensors with zigzag data
905
+ new_attention_mask[i, : chunk_size[i]] = global_attention_mask[i, start_idx_fwd:end_idx_fwd]
906
+ new_attention_mask[i, chunk_size[i] : 2 * chunk_size[i]] = global_attention_mask[
907
+ i, start_idx_bwd:end_idx_bwd
908
+ ]
909
+
910
+ new_position_ids[i, : chunk_size[i]] = global_position_ids[i, start_idx_fwd:end_idx_fwd]
911
+ new_position_ids[i, chunk_size[i] : 2 * chunk_size[i]] = global_position_ids[
912
+ i, start_idx_bwd:end_idx_bwd
913
+ ]
914
+
915
+ new_labels[i, : chunk_size[i]] = global_labels[i, start_idx_fwd:end_idx_fwd]
916
+ new_labels[i, chunk_size[i] : 2 * chunk_size[i]] = global_labels[i, start_idx_bwd:end_idx_bwd]
917
+
918
+ new_inputs_embeds[i, : chunk_size[i], :] = global_inputs_embeds[i, start_idx_fwd:end_idx_fwd, :]
919
+ new_inputs_embeds[i, chunk_size[i] : 2 * chunk_size[i], :] = global_inputs_embeds[
920
+ i, start_idx_bwd:end_idx_bwd, :
921
+ ]
922
+ else:
923
+ raise ValueError(f"Invalid ring_type: {ring_type}")
924
+ else:
925
+ global_seq_len = global_attention_mask.shape[-1]
926
+ seq_len_sharded = global_seq_len // sp_degree
927
+ start_idx_reshard = seq_len_sharded * sp_rank
928
+ end_idx_reshard = start_idx_reshard + seq_len_sharded if sp_rank < sp_degree - 1 else global_seq_len
929
+
930
+ new_attention_mask = torch.narrow(
931
+ global_attention_mask, 1, start_idx_reshard, end_idx_reshard - start_idx_reshard
932
+ )
933
+ new_position_ids = torch.narrow(
934
+ global_position_ids, 1, start_idx_reshard, end_idx_reshard - start_idx_reshard
935
+ )
936
+ new_labels = torch.narrow(global_labels, 1, start_idx_reshard, end_idx_reshard - start_idx_reshard)
937
+ new_inputs_embeds = torch.narrow(
938
+ global_inputs_embeds, 1, start_idx_reshard, end_idx_reshard - start_idx_reshard
939
+ )
940
+
941
+ return new_inputs_embeds, new_attention_mask, new_position_ids, new_labels
942
+
943
+ device = inputs_embeds.device
944
+ batch_size = inputs_embeds.shape[0]
945
+ seqlens = [attention_mask[k].sum().item() for k in range(batch_size)]
946
+
947
+ # Pack all sequences together
948
+ inputs_embeds_p = [inputs_embeds[k][attention_mask[k]] for k in range(batch_size)]
949
+ attention_mask_p = [torch.ones(seqlens[k], dtype=torch.int, device=device) for k in range(batch_size)]
950
+ position_ids_p = [torch.arange(seqlens[k], dtype=torch.int, device=device) for k in range(batch_size)]
951
+ labels_p = [labels[k][attention_mask[k]] for k in range(batch_size)]
952
+
953
+ # Add one dummy token at the end of the packed sequence to ensure that `_get_unpacked_data` will be called
954
+ inputs_embeds_p.append(torch.zeros(1, inputs_embeds.shape[-1], dtype=inputs_embeds.dtype, device=device))
955
+ attention_mask_p.append(torch.tensor([0], dtype=torch.int, device=device))
956
+ position_ids_p.append(torch.tensor([0], dtype=torch.int, device=device))
957
+ labels_p.append(torch.tensor([IGNORE_INDEX], dtype=torch.int, device=device))
958
+
959
+ # Mask the first token of each sequence to avoid contamination
960
+ for label in labels_p:
961
+ label[0] = IGNORE_INDEX
962
+
963
+ # Batch the data
964
+ inputs_embeds_p = torch.cat(inputs_embeds_p, dim=0).unsqueeze(0)
965
+ attention_mask_p = torch.cat(attention_mask_p, dim=0).unsqueeze(0)
966
+ position_ids_p = torch.cat(position_ids_p, dim=0).unsqueeze(0)
967
+ labels_p = torch.cat(labels_p, dim=0).unsqueeze(0)
968
+
969
+ if hasattr(
970
+ self, "pad_to_multiple_of"
971
+ ): # related to quantization, please refer to ModelArguments for more information.
972
+ assert len(labels_p.shape) == 2
973
+ batch_size, max_length, cur_length = labels_p.shape[0], labels_p.shape[1], labels_p.shape[1]
974
+ hidden_size = inputs_embeds_p.shape[-1]
975
+
976
+ if max_length % self.pad_to_multiple_of != 0:
977
+ max_length = ((max_length // self.pad_to_multiple_of) + 1) * self.pad_to_multiple_of
978
+ difference = max_length - cur_length
979
+
980
+ inputs_embeds_p = torch.cat(
981
+ (
982
+ inputs_embeds_p,
983
+ torch.full((batch_size, difference, hidden_size), self.llm.pad_token_id).to(inputs_embeds_p),
984
+ ),
985
+ dim=1,
986
+ )
987
+ labels_p = torch.cat((labels_p, torch.full((batch_size, difference), IGNORE_INDEX).to(labels_p)), dim=1)
988
+ attention_mask_p = torch.cat(
989
+ (
990
+ attention_mask_p,
991
+ torch.zeros((batch_size, difference), dtype=torch.bool).to(attention_mask_p),
992
+ ),
993
+ dim=1,
994
+ )
995
+ position_ids_p = torch.cat(
996
+ (position_ids_p, torch.full((batch_size, difference), -1).to(position_ids_p)), dim=1
997
+ )
998
+
999
+ return inputs_embeds_p, attention_mask_p, position_ids_p, labels_p
1000
+
1001
+ def get_xgr_logits_processor(self, response_format) -> List[LogitsProcessor]:
1002
+ raise NotImplementedError("This method is not implemented for VILA model.")
1003
+ # Convert response format to logits processor
1004
+ import xgrammar as xgr
1005
+
1006
+ logging.info("[XGrammar] Compiling grammar for contrained output")
1007
+
1008
+ if self.grammar_compiler is None:
1009
+ # logging.info(f"[XGrammar] {self.tokenizer}, {self.tokenizer.vocab_size}, {self.vocab_size}")
1010
+ self.grammar_compiler = xgr.GrammarCompiler(
1011
+ xgr.TokenizerInfo.from_huggingface(self.tokenizer, vocab_size=self.vocab_size)
1012
+ )
1013
+
1014
+ if response_format.type == "json_schema":
1015
+ compiled_grammar = self.grammar_compiler.compile_json_schema(
1016
+ response_format.json_schema.schema_,
1017
+ indent=2,
1018
+ )
1019
+ else:
1020
+ compiled_grammar = self.grammar_compiler.compile_builtin_json_grammar()
1021
+
1022
+ return [xgr.contrib.hf.LogitsProcessor(compiled_grammar)]
1023
+
1024
+ def forward(
1025
+ self,
1026
+ input_ids: torch.LongTensor = None,
1027
+ media: Optional[Dict[str, List[torch.Tensor]]] = None,
1028
+ images: Optional[torch.FloatTensor] = None,
1029
+ media_config: Optional[List] = None,
1030
+ pixel_values: Optional[torch.FloatTensor] = None,
1031
+ attention_mask: Optional[torch.Tensor] = None,
1032
+ position_ids: Optional[torch.LongTensor] = None,
1033
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1034
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1035
+ labels: Optional[torch.LongTensor] = None,
1036
+ packing: bool = True,
1037
+ force_packing: bool = False,
1038
+ seqlens_in_batch: Optional[torch.LongTensor] = None,
1039
+ dpo_forward: bool = False,
1040
+ **kwargs,
1041
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1042
+ self.freezed_module_patch()
1043
+
1044
+ if images is not None:
1045
+ if media is not None:
1046
+ raise ValueError("Both 'media' and 'images' are provided. Please provide only one.")
1047
+ print("The 'images' argument is deprecated. Please use 'media' instead.")
1048
+ media = {"image": images}
1049
+
1050
+ if media_config is None:
1051
+ media_config = defaultdict(dict)
1052
+
1053
+ if isinstance(media, torch.Tensor):
1054
+ media = {"video": media.chunk(input_ids.shape[0], dim=0)} #[media[i].unsqueeze(0) for i in range(media.shape[0])]}
1055
+
1056
+ if inputs_embeds is None:
1057
+ inputs_embeds, labels, attention_mask = self._embed(input_ids, media, media_config, labels, attention_mask)
1058
+
1059
+ if force_packing or (packing and self.training and not dpo_forward):
1060
+ if seqlens_in_batch is None:
1061
+ seqlens_in_batch = torch.sum(attention_mask, dim=1)
1062
+ set_seqlens_in_batch(seqlens_in_batch)
1063
+
1064
+ (inputs_embeds, attention_mask, position_ids, labels) = self.repack_multimodal_data(
1065
+ inputs_embeds, attention_mask, position_ids, labels
1066
+ )
1067
+
1068
+ outputs = self.llm(
1069
+ inputs_embeds=inputs_embeds,
1070
+ attention_mask=attention_mask,
1071
+ position_ids=position_ids,
1072
+ past_key_values=past_key_values,
1073
+ labels=labels,
1074
+ **kwargs,
1075
+ )
1076
+
1077
+ if self.training and getattr(self.config, "time_token_ids", []):
1078
+ outputs.loss = soft_cross_entropy(
1079
+ outputs.logits,
1080
+ labels,
1081
+ soft_tokens=self.config.time_token_ids,
1082
+ std=self.config.soft_ce_std,
1083
+ )
1084
+
1085
+ if dpo_forward:
1086
+ return outputs.logits, labels
1087
+
1088
+ return outputs
1089
+
1090
+ @torch.inference_mode()
1091
+ def generate(
1092
+ self,
1093
+ input_ids: Optional[torch.FloatTensor] = None,
1094
+ media: Optional[Dict[str, List[torch.Tensor]]] = None,
1095
+ media_config: Dict[str, Dict[str, Any]] = None,
1096
+ attention_mask: Optional[torch.LongTensor] = None,
1097
+ return_output_ids_only: bool = False,
1098
+ **generation_kwargs,
1099
+ ) -> torch.LongTensor:
1100
+ """
1101
+ input_tokens: <image> describe the image
1102
+ media: [Tensor(1, 3, 384, 384), ]
1103
+ ----------->
1104
+ input_tokens: 36000 001 002 003 004
1105
+ input_emds: <media emd> 001 002 003 004
1106
+ """
1107
+ # NOTE: hard code to move to GPU
1108
+ input_ids = input_ids.cuda()
1109
+ media = {k: [v.cuda() for v in media[k]] for k in media}
1110
+ if attention_mask is not None:
1111
+ attention_mask = attention_mask.cuda()
1112
+
1113
+ inputs_embeds, _, attention_mask = self._embed(input_ids, media, media_config, None, attention_mask)
1114
+ output_ids = self.llm.generate(inputs_embeds=inputs_embeds, attention_mask=attention_mask, **generation_kwargs)
1115
+
1116
+ if return_output_ids_only:
1117
+ return_value = output_ids
1118
+ else:
1119
+ # by default, return the input_ids and output_ids concatenated to keep consistency with the community VLMs like qwen
1120
+ generation_config = generation_kwargs.get("generation_config", None)
1121
+ if generation_config is not None:
1122
+ num_generations = generation_config.num_return_sequences
1123
+ repeat_input_ids = input_ids.repeat_interleave(num_generations, dim=0)
1124
+ return_value = torch.cat([repeat_input_ids, output_ids], dim=-1)
1125
+ else:
1126
+ return_value = torch.cat([input_ids, output_ids], dim=-1)
1127
+
1128
+ return return_value
1129
+
1130
+ @torch.inference_mode()
1131
+ def generate_content(
1132
+ self,
1133
+ prompt: Union[str, List],
1134
+ generation_config: Optional[GenerationConfig] = None,
1135
+ response_format=None,
1136
+ ) -> str:
1137
+ # TODO(zhijianl): Support directly taking conversation as input
1138
+ conversation = [{"from": "human", "value": prompt}]
1139
+
1140
+ # Convert response format to logits processor
1141
+ xgr_logits_processor = None
1142
+
1143
+ # Extract media from the conversation
1144
+
1145
+ # TODO (extract and preprocess should be done together, as the preprocess of image and video can be different, i.e. when dynamic res is used)
1146
+ media = extract_media(conversation, self.config)
1147
+
1148
+ # Process media
1149
+ media_config = defaultdict(dict)
1150
+ for name in media:
1151
+ if name == "image":
1152
+ if len(media["image"]) == 1 and self.config.image_aspect_ratio in ["dynamic", "dynamic_s2"]:
1153
+ self.config.image_processor = self.vision_tower.image_processor
1154
+ if self.config.image_aspect_ratio == "dynamic":
1155
+ images = process_image(media["image"][0], self.config, None, enable_dynamic_res=True).half()
1156
+ conversation[0]["value"] = conversation[0]["value"].replace(
1157
+ DEFAULT_IMAGE_TOKEN, f"{DEFAULT_IMAGE_TOKEN}\n" * images.shape[0]
1158
+ )
1159
+ else:
1160
+ if type(self.config.s2_scales) is str:
1161
+ self.config.s2_scales = list(map(int, self.config.s2_scales.split(",")))
1162
+ images, block_sizes = process_image(
1163
+ media["image"][0], self.config, None, enable_dynamic_s2=True
1164
+ )
1165
+ images = images.half()
1166
+ media_config[name]["block_sizes"] = [block_sizes]
1167
+ else:
1168
+ images = process_images(media["image"], self.vision_tower.image_processor, self.config).half()
1169
+ media[name] = [image for image in images]
1170
+ elif name == "video":
1171
+ if self.config.image_aspect_ratio == "dynamic" and self.config.video_max_tiles > 1:
1172
+ media[name] = [
1173
+ process_images(
1174
+ images,
1175
+ self.vision_tower.image_processor,
1176
+ self.config,
1177
+ enable_dynamic_res=True,
1178
+ max_tiles=self.config.video_max_tiles,
1179
+ ).half()
1180
+ for images in media[name]
1181
+ ]
1182
+ elif self.config.image_aspect_ratio == "dynamic_s2" and self.config.video_max_tiles > 1:
1183
+ self.config.image_processor = self.vision_tower.image_processor
1184
+ if type(self.config.s2_scales) is str:
1185
+ self.config.s2_scales = list(map(int, self.config.s2_scales.split(",")))
1186
+ media[name] = [
1187
+ torch.cat(
1188
+ [
1189
+ process_image(
1190
+ image,
1191
+ self.config,
1192
+ None,
1193
+ enable_dynamic_s2=True,
1194
+ max_tiles=self.config.video_max_tiles,
1195
+ )[0].half()
1196
+ for image in images
1197
+ ]
1198
+ )
1199
+ for images in media[name]
1200
+ ]
1201
+ else:
1202
+ media[name] = [
1203
+ process_images(images, self.vision_tower.image_processor, self.config).to(self.dtype).half()
1204
+ for images in media[name]
1205
+ ]
1206
+ else:
1207
+ raise ValueError(f"Unsupported media type: {name}")
1208
+
1209
+ # Tokenize the conversation
1210
+ input_ids = tokenize_conversation(conversation, self.tokenizer, add_generation_prompt=True).unsqueeze(0).cuda()
1211
+
1212
+ # Set up the generation config
1213
+ generation_config = generation_config or self.default_generation_config
1214
+
1215
+ # print("input_ids", input_ids.shape)
1216
+ # print(input_ids)
1217
+ # print(self.tokenizer.batch_decode(input_ids))
1218
+ # print("media", {k: len(v) for k, v in media.items()})
1219
+ # print("media_config", media_config)
1220
+ # print("generation_config", generation_config)
1221
+ # input("wait for debug")
1222
+ # Generate the response
1223
+ try:
1224
+ output_ids = self.generate(
1225
+ input_ids=input_ids,
1226
+ media=media,
1227
+ media_config=media_config,
1228
+ generation_config=generation_config,
1229
+ logits_processor=xgr_logits_processor, # structured generation
1230
+ )
1231
+ except ValueError:
1232
+ if not generation_config.do_sample:
1233
+ raise
1234
+ # FIXME(zhijianl): This is a temporary workaround for the sampling issue
1235
+ logging.warning("Generation failed with sampling, retrying with greedy decoding.")
1236
+ generation_config.do_sample = False
1237
+ output_ids = self.generate(
1238
+ input_ids=input_ids,
1239
+ media=media,
1240
+ media_config=media_config,
1241
+ generation_config=generation_config,
1242
+ logits_processor=xgr_logits_processor,
1243
+ )
1244
+
1245
+ # Decode the response
1246
+ response = self.tokenizer.decode(output_ids[0], skip_special_tokens=True).strip()
1247
+ return response
1248
+
1249
+ @property
1250
+ def default_generation_config(self) -> GenerationConfig:
1251
+ generation_config = copy.deepcopy(self.generation_config or GenerationConfig())
1252
+ if self.tokenizer.eos_token_id is None:
1253
+ raise ValueError("Tokenizer must have an EOS token")
1254
+ if generation_config.max_length == GenerationConfig().max_length:
1255
+ generation_config.max_length = self.tokenizer.model_max_length
1256
+ if generation_config.pad_token_id is None:
1257
+ generation_config.pad_token_id = self.tokenizer.pad_token_id or self.tokenizer.eos_token_id
1258
+ if generation_config.bos_token_id is None:
1259
+ generation_config.bos_token_id = self.tokenizer.bos_token_id or self.tokenizer.eos_token_id
1260
+ if generation_config.eos_token_id is None:
1261
+ generation_config.eos_token_id = self.tokenizer.eos_token_id
1262
+ return generation_config
siglip_encoder.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+ from accelerate.hooks import add_hook_to_module
21
+ from einops import rearrange
22
+ from s2wrapper import forward as multiscale_forward
23
+ from transformers import AutoConfig, PretrainedConfig, PreTrainedModel, SiglipImageProcessor
24
+ from transformers.image_processing_utils import BaseImageProcessor
25
+ from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled
26
+ from transformers.models.siglip import SiglipVisionModel
27
+
28
+
29
+ class VisionTower(nn.Module):
30
+ def __init__(self, vision_tower, args, delay_load=False):
31
+ super().__init__()
32
+
33
+ self.is_loaded = False
34
+
35
+ self.vision_tower_name = vision_tower
36
+ self.select_layer = getattr(args, "mm_vision_select_layer", -2)
37
+ self.select_feature = getattr(args, "mm_vision_select_feature", "patch")
38
+
39
+ self.cfg_only = None
40
+
41
+ def feature_select(self, image_forward_outs):
42
+ image_features = image_forward_outs.hidden_states[self.select_layer]
43
+ if self.select_feature == "patch":
44
+ image_features = image_features[:, 1:]
45
+ elif self.select_feature == "cls_patch":
46
+ image_features = image_features
47
+ else:
48
+ raise ValueError(f"Unexpected select feature: {self.select_feature}")
49
+ return image_features
50
+
51
+ def _maybe_resize_pos_embeds(
52
+ self,
53
+ model: PreTrainedModel,
54
+ image_processor: BaseImageProcessor,
55
+ resolution: int = -1,
56
+ interpolate_mode: str = "linear",
57
+ ):
58
+ if resolution in [model.config.image_size, -1]:
59
+ return
60
+ print(
61
+ f"Resizing vision model's position embeddings to support higher vision resolution: from {model.config.image_size} to {resolution} ..."
62
+ )
63
+ embeddings = model.vision_model.embeddings
64
+ patch_size = embeddings.patch_size
65
+ num_new_tokens = int((resolution // patch_size) ** 2)
66
+
67
+ old_embeddings = embeddings.position_embedding
68
+ match interpolate_mode:
69
+ case "linear":
70
+ ## Step 1: Calculate the corresponding patch ID (pid) in the current resolution (M patches) based on the target resolution (N patches). Formula: pid = pid / N * M
71
+ ## Step 2: Obtain new embeddings by interpolating between the embeddings of the two nearest calculated patch IDs. Formula: new_embeds = (pid - floor(pid)) * embeds[ceil(pid)] + (ceil(pid) - pid) * embeds[floor(pid)]
72
+ import torch
73
+ import torch.nn as nn
74
+
75
+ if is_deepspeed_zero3_enabled():
76
+ try:
77
+ import deepspeed
78
+ except ImportError:
79
+ raise ImportError("DeepSpeed is not installed. Please install it with `pip install deepspeed`.")
80
+ with deepspeed.zero.GatheredParameters([old_embeddings.weight], modifier_rank=None):
81
+ old_num_tokens, old_embedding_dim = old_embeddings.weight.size()
82
+ else:
83
+ old_num_tokens, old_embedding_dim = old_embeddings.weight.size()
84
+ new_embeddings = nn.Embedding(
85
+ num_new_tokens,
86
+ old_embedding_dim,
87
+ dtype=old_embeddings.weight.dtype,
88
+ device=old_embeddings.weight.device,
89
+ )
90
+ mapped_indices = (
91
+ torch.arange(num_new_tokens).to(old_embeddings.weight.device)
92
+ / (num_new_tokens - 1)
93
+ * (old_num_tokens - 1)
94
+ )
95
+ floor_indices = torch.clamp(mapped_indices.floor().long(), min=0, max=old_num_tokens - 1)
96
+ ceil_indices = torch.clamp(mapped_indices.ceil().long(), min=0, max=old_num_tokens - 1)
97
+ if is_deepspeed_zero3_enabled():
98
+ params = [old_embeddings.weight, new_embeddings.weight]
99
+ with deepspeed.zero.GatheredParameters(params, modifier_rank=0):
100
+ interpolated_embeds = (mapped_indices - floor_indices)[:, None] * old_embeddings.weight.data[
101
+ ceil_indices, :
102
+ ] + (ceil_indices - mapped_indices)[:, None] * old_embeddings.weight.data[floor_indices, :]
103
+ else:
104
+ interpolated_embeds = (mapped_indices - floor_indices)[:, None] * old_embeddings.weight.data[
105
+ ceil_indices, :
106
+ ] + (ceil_indices - mapped_indices)[:, None] * old_embeddings.weight.data[floor_indices, :]
107
+ new_embeddings.weight.data = interpolated_embeds
108
+ case _:
109
+ raise NotImplementedError
110
+
111
+ if hasattr(old_embeddings, "_hf_hook"):
112
+ hook = old_embeddings._hf_hook
113
+ add_hook_to_module(new_embeddings, hook)
114
+ new_embeddings.requires_grad_(old_embeddings.weight.requires_grad)
115
+ ## update vision encoder's configurations
116
+ model.config.image_size = resolution
117
+ if hasattr(image_processor, "crop_size"):
118
+ # CLIP vision tower
119
+ image_processor.crop_size = resolution
120
+ else:
121
+ # SIGLIP vision tower
122
+ assert hasattr(image_processor, "size")
123
+ image_processor.size = {"height": resolution, "width": resolution}
124
+ ## TODO define a '_reinitialize' method for VisionTower
125
+ embeddings.position_embedding = new_embeddings
126
+ embeddings.image_size = resolution
127
+ embeddings.num_patches = embeddings.num_positions = num_new_tokens
128
+ embeddings.position_ids = (
129
+ torch.arange(embeddings.num_positions).expand((1, -1)).to(old_embeddings.weight.device)
130
+ )
131
+
132
+ def forward(self, images):
133
+ if type(images) is list:
134
+ image_features = []
135
+ for image in images:
136
+ image_forward_out = self.vision_tower(
137
+ image.to(device=self.device, dtype=self.dtype).unsqueeze(0),
138
+ output_hidden_states=True,
139
+ )
140
+ image_feature = self.feature_select(image_forward_out).to(image.dtype)
141
+ image_features.append(image_feature)
142
+ else:
143
+ image_forward_outs = self.vision_tower(
144
+ images.to(device=self.device, dtype=self.dtype),
145
+ output_hidden_states=True,
146
+ )
147
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
148
+
149
+ return image_features
150
+
151
+ @property
152
+ def dummy_feature(self):
153
+ return torch.zeros(1, self.hidden_size, device=self.device, dtype=self.dtype)
154
+
155
+ @property
156
+ def dtype(self):
157
+ return self.vision_tower.dtype
158
+
159
+ @property
160
+ def device(self):
161
+ return self.vision_tower.device
162
+
163
+ @property
164
+ def config(self):
165
+ if self.is_loaded:
166
+ return self.vision_tower.config
167
+ else:
168
+ return self.cfg_only
169
+
170
+ @property
171
+ def hidden_size(self):
172
+ return self.config.hidden_size
173
+
174
+ @property
175
+ def num_patches(self):
176
+ return (self.config.image_size // self.config.patch_size) ** 2
177
+
178
+
179
+ class VisionTowerS2(VisionTower):
180
+ def __init__(self, vision_tower, args, delay_load=False):
181
+ super().__init__(vision_tower, args, delay_load)
182
+
183
+ self.scales = list(map(int, args.s2_scales.split(",")))
184
+ self.scales.sort()
185
+ self.max_split_size = args.s2_max_split_size
186
+ self.resize_output_to_scale_idx = getattr(args, "s2_resize_output_to_scale_idx", 0)
187
+
188
+ def forward_feature(self, images):
189
+ image_forward_outs = self.vision_tower(
190
+ images.to(device=self.device, dtype=self.dtype), output_hidden_states=True
191
+ )
192
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
193
+ return image_features
194
+
195
+ def forward(self, images):
196
+ if type(images) is list:
197
+ image_feature = []
198
+ for image in images:
199
+ image_feature = multiscale_forward(
200
+ self.forward_feature,
201
+ image.unsqueeze(0),
202
+ img_sizes=self.scales,
203
+ max_split_size=self.max_split_size,
204
+ resize_output_to_idx=self.resize_output_to_scale_idx,
205
+ )
206
+ image_features.append(image_feature)
207
+ else:
208
+ image_features = multiscale_forward(
209
+ self.forward_feature,
210
+ images,
211
+ img_sizes=self.scales,
212
+ max_split_size=self.max_split_size,
213
+ resize_output_to_idx=self.resize_output_to_scale_idx,
214
+ )
215
+
216
+ return image_features
217
+
218
+ @property
219
+ def hidden_size(self):
220
+ return self.config.hidden_size * len(self.scales)
221
+
222
+
223
+ class VisionTowerDynamicS2(VisionTower):
224
+ def __init__(self, vision_tower, args, delay_load=False):
225
+ super().__init__(vision_tower, args, delay_load)
226
+
227
+ self.scales = list(map(int, args.s2_scales.split(",")))
228
+ self.scales.sort()
229
+ self.max_split_size = args.s2_max_split_size
230
+ self.resize_output_to_scale_idx = getattr(args, "s2_resize_output_to_scale_idx", 0)
231
+
232
+ def forward_feature(self, images):
233
+ image_forward_outs = self.vision_tower(
234
+ images.to(device=self.device, dtype=self.dtype), output_hidden_states=True
235
+ )
236
+ image_features = self.feature_select(image_forward_outs).to(images.dtype)
237
+ return image_features
238
+
239
+ def forward(self, images):
240
+ assert type(images) is not list
241
+ image_features = self.forward_feature(images)
242
+
243
+ return image_features
244
+
245
+ @property
246
+ def hidden_size(self):
247
+ return self.config.hidden_size * len(self.scales)
248
+
249
+
250
+ class SiglipVisionTower(VisionTower):
251
+ def __init__(self, model_name_or_path: str, config: PretrainedConfig) -> None:
252
+ super().__init__(model_name_or_path, config)
253
+ # TODO(ligengl): why pass config here leading to errors?
254
+ self.vision_tower = SiglipVisionModel.from_pretrained(
255
+ model_name_or_path,
256
+ attn_implementation=config._attn_implementation,
257
+ torch_dtype=eval(config.model_dtype),
258
+ )
259
+ self.image_processor = SiglipImageProcessor.from_pretrained(model_name_or_path)
260
+ self.is_loaded = True
261
+
262
+
263
+ class SiglipVisionTowerS2(VisionTowerS2):
264
+ def __init__(self, model_name_or_path: str, config: PretrainedConfig) -> None:
265
+ super().__init__(model_name_or_path, config)
266
+ self.vision_tower = SiglipVisionModel.from_pretrained(
267
+ model_name_or_path,
268
+ attn_implementation=config._attn_implementation,
269
+ torch_dtype=eval(config.model_dtype),
270
+ )
271
+ self.image_processor = SiglipImageProcessor.from_pretrained(model_name_or_path)
272
+ # Make sure it crops/resizes the image to the largest scale in self.scales to maintain high-res information
273
+ self.image_processor.size["height"] = self.image_processor.size["width"] = self.scales[-1]
274
+ self.is_loaded = True
275
+
276
+
277
+ class SiglipVisionTowerDynamicS2(VisionTowerDynamicS2):
278
+ def __init__(self, model_name_or_path: str, config: PretrainedConfig) -> None:
279
+ super().__init__(model_name_or_path, config)
280
+ self.vision_tower = SiglipVisionModel.from_pretrained(
281
+ model_name_or_path,
282
+ attn_implementation="flash_attention_2",
283
+ torch_dtype=eval(config.model_dtype),
284
+ )
285
+ self.image_processor = SiglipImageProcessor.from_pretrained(model_name_or_path)
286
+ # Make sure it crops/resizes the image to the largest scale in self.scales to maintain high-res information
287
+ self.image_processor.size["height"] = self.image_processor.size["width"] = self.scales[0]
288
+ self.is_loaded = True
tokenizer_utils.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ from typing import Any, Dict, List, Optional, Sequence
18
+
19
+ import torch
20
+ import transformers
21
+
22
+ from .constants import IGNORE_INDEX, SENTINEL_TOKEN
23
+ from .conversation import SeparatorStyle, default_conversation
24
+ from .mm_utils import tokenizer_image_token
25
+
26
+ # __all__ = [
27
+ # "tokenize_conversation",
28
+ # "preprocess_conversation",
29
+ # "infer_stop_tokens",
30
+ # ]
31
+
32
+ DUMMY_CONVERSATION = [
33
+ {"from": "human", "value": "question"},
34
+ {"from": "gpt", "value": "answer"},
35
+ ] * 10
36
+
37
+
38
+ def tokenize_conversation_legacy(
39
+ messages: Sequence[Dict[str, str]],
40
+ tokenizer: transformers.PreTrainedTokenizer,
41
+ add_generation_prompt: bool = False,
42
+ overrides: Optional[Dict[str, str]] = None,
43
+ no_system_prompt: bool = False,
44
+ ) -> torch.Tensor:
45
+ conv = default_conversation.copy()
46
+ roles = {"human": conv.roles[0], "gpt": conv.roles[1]}
47
+
48
+ if no_system_prompt:
49
+ conv.system = ""
50
+
51
+ # Skip the first message if it is not from human
52
+ if messages[0]["from"] != "human":
53
+ messages = messages[1:]
54
+
55
+ # Add a generation prompt if needed
56
+ if add_generation_prompt:
57
+ messages.append({"from": "gpt", "value": None})
58
+
59
+ conv.messages = []
60
+ for turn, message in enumerate(messages):
61
+ role = roles[message["from"]]
62
+ assert role == conv.roles[turn % 2]
63
+ if overrides is not None and message["from"] in overrides:
64
+ conv.append_message(role, overrides[message["from"]])
65
+ else:
66
+ conv.append_message(role, message["value"])
67
+
68
+ return tokenizer_image_token(conv.get_prompt(), tokenizer, return_tensors="pt")
69
+
70
+
71
+ # NOTE(ligeng): add a return typing to help code analyze
72
+ def tokenize_conversation(
73
+ messages: Sequence[Dict[str, str]],
74
+ tokenizer: transformers.PreTrainedTokenizer,
75
+ add_generation_prompt: bool = False,
76
+ overrides: Optional[Dict[str, str]] = None,
77
+ no_system_prompt: bool = False,
78
+ return_ids_only=True,
79
+ ) -> torch.Tensor:
80
+ # print("messages", messages); input()
81
+ # Normalize the conversation before tokenization
82
+ for message in messages:
83
+ message["value"] = message["value"].strip()
84
+
85
+ if default_conversation.sep_style != SeparatorStyle.AUTO:
86
+ return tokenize_conversation_legacy(
87
+ messages,
88
+ tokenizer,
89
+ add_generation_prompt=add_generation_prompt,
90
+ overrides=overrides,
91
+ no_system_prompt=no_system_prompt,
92
+ )
93
+
94
+ conversation = []
95
+ for m in messages:
96
+ message = {}
97
+ if m["from"] == "human":
98
+ message["role"] = "user"
99
+ elif m["from"] == "gpt":
100
+ message["role"] = "assistant"
101
+ elif m["from"] == "system":
102
+ message["role"] = "system"
103
+ if no_system_prompt:
104
+ raise ValueError("System prompt is not allowed when no_system_prompt is True.")
105
+ else:
106
+ raise ValueError(f"Unexpected sender '{m['from']}' in conversation entry.")
107
+
108
+ message["content"] = m["value"]
109
+ if overrides is not None and m["from"] in overrides:
110
+ message["content"] = overrides[m["from"]]
111
+ conversation.append(message)
112
+
113
+ if no_system_prompt:
114
+ conversation = [{"role": "system", "content": ""}] + conversation
115
+
116
+ text = tokenizer.apply_chat_template(
117
+ conversation,
118
+ add_generation_prompt=add_generation_prompt,
119
+ tokenize=False,
120
+ )
121
+ return tokenizer_image_token(text, tokenizer, return_tensors="pt", return_ids=return_ids_only)
122
+
123
+
124
+ def _maybe_add_sentinel_token(tokenizer: transformers.PreTrainedTokenizer) -> None:
125
+ if not hasattr(tokenizer, "sentinel_token"):
126
+ tokenizer.add_tokens([SENTINEL_TOKEN], special_tokens=True)
127
+ tokenizer.sentinel_token = SENTINEL_TOKEN
128
+ tokenizer.sentinel_token_id = tokenizer.convert_tokens_to_ids(SENTINEL_TOKEN)
129
+
130
+
131
+ def preprocess_conversation(
132
+ conversation: Sequence[Dict[str, str]],
133
+ tokenizer: transformers.PreTrainedTokenizer,
134
+ no_system_prompt: bool = False,
135
+ retried: bool = False,
136
+ ) -> Dict[str, Any]:
137
+ inputs = tokenize_conversation(conversation, tokenizer, no_system_prompt=no_system_prompt)
138
+ labels = torch.ones_like(inputs) * IGNORE_INDEX
139
+
140
+ # Generate the template by replacing the assistant's response with a sentinel.
141
+ _maybe_add_sentinel_token(tokenizer)
142
+ template = tokenize_conversation(
143
+ conversation, tokenizer, overrides={"gpt": SENTINEL_TOKEN}, no_system_prompt=no_system_prompt
144
+ )
145
+
146
+ # Remove sentinel tokens from the template.
147
+ mask = torch.ones_like(template, dtype=torch.bool)
148
+ for k in range(template.size(0) - 1):
149
+ if template[k] == tokenizer.sentinel_token_id:
150
+ mask[k : k + 2] = False
151
+ # NOTE(zhijianl): This is to handle the corner case where there is an empty token before the sentinel token.
152
+ if k > 0 and retried:
153
+ mask[k - 1] = False
154
+ template = template[mask]
155
+
156
+ # Match the tokenized conversation with the template (with no assistant's response).
157
+ # Every token that is not matched will be included in the label for training.
158
+ p = 0
159
+ for k in range(inputs.size(0)):
160
+ if p < template.size(0) and inputs[k] == template[p]:
161
+ p += 1
162
+ else:
163
+ labels[k] = inputs[k]
164
+
165
+ # Mask all tokens in the label if the template is not fully matched.
166
+ if p < template.size(0):
167
+ if not retried:
168
+ return preprocess_conversation(
169
+ conversation,
170
+ tokenizer,
171
+ no_system_prompt=no_system_prompt,
172
+ retried=True,
173
+ )
174
+ print(f"Failed to process the conversation: '{conversation}'. All tokens will be masked in the label.")
175
+ labels[:] = IGNORE_INDEX
176
+
177
+ return {"input_ids": inputs, "labels": labels}
178
+
179
+
180
+ def infer_stop_tokens(tokenizer: transformers.PreTrainedTokenizer) -> List[str]:
181
+ _maybe_add_sentinel_token(tokenizer)
182
+ template = tokenize_conversation(DUMMY_CONVERSATION, tokenizer, overrides={"gpt": SENTINEL_TOKEN})
183
+
184
+ stop_tokens = {tokenizer.eos_token}
185
+ for k in range(template.size(0) - 1):
186
+ if template[k] == tokenizer.sentinel_token_id:
187
+ stop_token = tokenizer.decode(template[k + 1])
188
+ stop_tokens.add(stop_token)
189
+ return list(stop_tokens)
utils.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
17
+ import os
18
+ import os.path as osp
19
+
20
+ from huggingface_hub import repo_exists, snapshot_download
21
+ from huggingface_hub.utils import HFValidationError, validate_repo_id
22
+ from transformers import AutoConfig, AutoTokenizer, PretrainedConfig
23
+
24
+ from .configuration_vila import VILAConfig
25
+ from .constants import MEDIA_TOKENS
26
+ from .tokenizer_utils import infer_stop_tokens
27
+
28
+
29
+ def load_tokenizer_then_handle_media_tokens_and_chat_template(
30
+ model_name_or_path, config: VILAConfig, model_max_length=None
31
+ ):
32
+ # TODO(ligeng): a lot of copy-paste code, refactor to make a single function
33
+ tokenizer = AutoTokenizer.from_pretrained(
34
+ osp.join(model_name_or_path, "llm"), padding_side="right", use_fast=True, legacy=False
35
+ )
36
+ if model_max_length is not None:
37
+ tokenizer.model_max_length = model_max_length
38
+
39
+ # Load chat template if specified.
40
+ if getattr(config, "chat_template", None) is not None:
41
+ print(f"Using chat template: {config.chat_template}")
42
+ fpath = os.path.join(os.path.dirname(__file__), "chat_templates", f"{config.chat_template}.jinja")
43
+ if not os.path.exists(fpath):
44
+ fpath = os.path.join(model_name_or_path, f"{config.chat_template}.jinja")
45
+ with open(fpath) as fd:
46
+ chat_template = fd.read()
47
+ tokenizer.chat_template = chat_template.replace(" ", "").replace("\n", "")
48
+
49
+ # Set stop tokens for the tokenizer
50
+ tokenizer.stop_tokens = infer_stop_tokens(tokenizer)
51
+ tokenizer.stop_token_ids = tokenizer.convert_tokens_to_ids(tokenizer.stop_tokens)
52
+
53
+ # Add media tokens to the tokenizer
54
+ tokenizer.media_tokens = MEDIA_TOKENS
55
+ tokenizer.media_token_ids = {}
56
+ for name, token in MEDIA_TOKENS.items():
57
+ tokenizer.add_tokens([token], special_tokens=True)
58
+ tokenizer.media_token_ids[name] = tokenizer.convert_tokens_to_ids(token)
59
+
60
+ return tokenizer
61
+
62
+
63
+ def get_model_config(config):
64
+ default_keys = ["llm_cfg", "vision_tower_cfg", "mm_projector_cfg"]
65
+
66
+ if hasattr(config, "_name_or_path") and len(config._name_or_path) >= 2:
67
+ root_path = config._name_or_path
68
+ else:
69
+ root_path = config.resume_path
70
+
71
+ # download from huggingface
72
+ if root_path is not None and not osp.exists(root_path):
73
+ try:
74
+ valid_hf_repo = repo_exists(root_path)
75
+ except HFValidationError as e:
76
+ valid_hf_repo = False
77
+ if valid_hf_repo:
78
+ root_path = snapshot_download(root_path)
79
+
80
+ return_list = []
81
+ for key in default_keys:
82
+ cfg = getattr(config, key, None)
83
+ if isinstance(cfg, dict):
84
+ try:
85
+ return_list.append(os.path.join(root_path, key[:-4]))
86
+ except:
87
+ raise ValueError(f"Cannot find resume path in config for {key}!")
88
+ elif isinstance(cfg, PretrainedConfig):
89
+ return_list.append(os.path.join(root_path, key[:-4]))
90
+ elif isinstance(cfg, str):
91
+ return_list.append(cfg)
92
+
93
+ return return_list
94
+
95
+
96
+ def get_model_config_fp8(config):
97
+ default_keys = ["llm_cfg", "vision_tower_cfg", "mm_projector_cfg"]
98
+
99
+ if hasattr(config, "_name_or_path") and len(config._name_or_path) >= 2:
100
+ root_path = config._name_or_path
101
+ else:
102
+ root_path = config.resume_path
103
+
104
+ # download from huggingface
105
+ if root_path is not None and not osp.exists(root_path):
106
+ try:
107
+ valid_hf_repo = repo_exists(root_path)
108
+ except HFValidationError as e:
109
+ valid_hf_repo = False
110
+ if valid_hf_repo:
111
+ root_path = snapshot_download(root_path)
112
+
113
+ return_list = []
114
+ for key in default_keys:
115
+ cfg = getattr(config, key, None)
116
+ if isinstance(cfg, dict):
117
+ try:
118
+ return_list.append(os.path.join(root_path, key[:-4]))
119
+ except:
120
+ raise ValueError(f"Cannot find resume path in config for {key}!")
121
+ elif isinstance(cfg, PretrainedConfig):
122
+ return_list.append(os.path.join(root_path, key[:-4]))
123
+ elif isinstance(cfg, str):
124
+ return_list.append(cfg)
125
+
126
+ # fp8_llm
127
+ key = "fp8_llm_cfg"
128
+ directory_path = os.path.join(root_path, key[:-4])
129
+ assert os.path.isdir(directory_path) and os.listdir(
130
+ directory_path
131
+ ), "You need to first convert the model weights to FP8 explicitly."
132
+ return_list.append(directory_path)
133
+
134
+ return return_list
135
+
136
+
137
+ def get_model_config_fp8(config):
138
+ default_keys = ["llm_cfg", "vision_tower_cfg", "mm_projector_cfg"]
139
+
140
+ if hasattr(config, "_name_or_path") and len(config._name_or_path) >= 2:
141
+ root_path = config._name_or_path
142
+ else:
143
+ root_path = config.resume_path
144
+
145
+ # download from huggingface
146
+ if root_path is not None and not osp.exists(root_path):
147
+ try:
148
+ valid_hf_repo = repo_exists(root_path)
149
+ except HFValidationError as e:
150
+ valid_hf_repo = False
151
+ if valid_hf_repo:
152
+ root_path = snapshot_download(root_path)
153
+
154
+ return_list = []
155
+ for key in default_keys:
156
+ cfg = getattr(config, key, None)
157
+ if isinstance(cfg, dict):
158
+ try:
159
+ return_list.append(os.path.join(root_path, key[:-4]))
160
+ except:
161
+ raise ValueError(f"Cannot find resume path in config for {key}!")
162
+ elif isinstance(cfg, PretrainedConfig):
163
+ return_list.append(os.path.join(root_path, key[:-4]))
164
+ elif isinstance(cfg, str):
165
+ return_list.append(cfg)
166
+
167
+ # fp8_llm
168
+ key = "fp8_llm_cfg"
169
+ directory_path = os.path.join(root_path, key[:-4])
170
+ assert os.path.isdir(directory_path) and os.listdir(
171
+ directory_path
172
+ ), "You need to first convert the model weights to FP8 explicitly."
173
+ return_list.append(directory_path)
174
+
175
+ return return_list
176
+
177
+
178
+ def is_mm_model(model_path):
179
+ """
180
+ Check if the model at the given path is a visual language model.
181
+
182
+ Args:
183
+ model_path (str): The path to the model.
184
+
185
+ Returns:
186
+ bool: True if the model is an MM model, False otherwise.
187
+ """
188
+ config = AutoConfig.from_pretrained(model_path)
189
+ architectures = config.architectures
190
+ for architecture in architectures:
191
+ if "llava" in architecture.lower():
192
+ return True
193
+ return False
194
+
195
+
196
+ def auto_upgrade(config):
197
+ cfg = AutoConfig.from_pretrained(config)
198
+ if "llava" in config and "llava" not in cfg.model_type:
199
+ assert cfg.model_type == "llama"
200
+ print("You are using newer LLaVA code base, while the checkpoint of v0 is from older code base.")
201
+ print("You must upgrade the checkpoint to the new code base (this can be done automatically).")
202
+ confirm = input("Please confirm that you want to upgrade the checkpoint. [Y/N]")
203
+ if confirm.lower() in ["y", "yes"]:
204
+ print("Upgrading checkpoint...")
205
+ assert len(cfg.architectures) == 1
206
+ setattr(cfg.__class__, "model_type", "llava")
207
+ cfg.architectures[0] = "LlavaLlamaForCausalLM"
208
+ cfg.save_pretrained(config)
209
+ print("Checkpoint upgraded.")
210
+ else:
211
+ print("Checkpoint upgrade aborted.")
212
+ exit(1)
vision_tower/config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "./output/qwen2-7b-longvila-256f-internal-reasoning-0320/vision_tower",
3
+ "architectures": [
4
+ "SiglipVisionModel"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "hidden_act": "gelu_pytorch_tanh",
8
+ "hidden_size": 1152,
9
+ "image_size": 448,
10
+ "intermediate_size": 4304,
11
+ "layer_norm_eps": 1e-06,
12
+ "model_type": "siglip_vision_model",
13
+ "num_attention_heads": 16,
14
+ "num_channels": 3,
15
+ "num_hidden_layers": 27,
16
+ "num_image_tokens": 256,
17
+ "patch_size": 14,
18
+ "projection_dim": 2048,
19
+ "projector_hidden_act": "gelu_fast",
20
+ "torch_dtype": "bfloat16",
21
+ "transformers_version": "4.46.2",
22
+ "vision_use_head": false
23
+ }
vision_tower/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:13505aa6b25830c481ca8e9385cd73b3f178d09c68d0adcc80d2b8fccc6c411f
3
+ size 826707904
vision_tower/preprocessor_config.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_convert_rgb": null,
3
+ "do_normalize": true,
4
+ "do_rescale": true,
5
+ "do_resize": true,
6
+ "image_mean": [
7
+ 0.5,
8
+ 0.5,
9
+ 0.5
10
+ ],
11
+ "image_processor_type": "SiglipImageProcessor",
12
+ "image_std": [
13
+ 0.5,
14
+ 0.5,
15
+ 0.5
16
+ ],
17
+ "processor_class": "SiglipProcessor",
18
+ "resample": 3,
19
+ "rescale_factor": 0.00392156862745098,
20
+ "size": {
21
+ "height": 448,
22
+ "width": 448
23
+ }
24
+ }