Views
No views yet
pip install git+https://github.com/TIGER-AI-Lab/Mantis.git1from PIL import Image
2import torch
3import torch.nn as nn
4import os
5from mantis.models.mllava import chat_mllava
6from mantis.models.mllava import MLlavaProcessor, LlavaForConditionalGeneration
7import argparse
8
9class Med_Mantis_Inference(nn.Module):
10 def __init__(
11 self,
12 device="cuda:0",
13 model_path="path_to_your_download_model",
14 ):
15 super(Med_Mantis_Inference, self).__init__()
16 self.device = device
17 self.model_path = model_path
18 self.processor, self.model = self.load_model()
19
20 def load_model(self):
21 processor = MLlavaProcessor.from_pretrained(self.model_path)
22 model = LlavaForConditionalGeneration.from_pretrained(
23 self.merged_model_path,
24 device_map=self.device,
25 torch_dtype=torch.bfloat16,
26 # attn_implementation="flash_attention_2",
27 )
28 return processor, model
29
30 def forward(self, images_path, usr_text_list):
31 if isinstance(usr_text_list, str):
32 usr_text_list = [usr_text_list]
33
34 images = []
35 for img_path in images_path:
36 images.append(Image.open(img_path).convert('RGB'))
37
38 generation_kwargs = {
39 "max_new_tokens": 1024,
40 "num_beams": 1,
41 "do_sample": False
42 }
43
44 response_list = []
45 for qs_id, text in enumerate(usr_text_list):
46 if qs_id == 0:
47 response, history = chat_mllava(
48 text, images, self.model, self.processor, **generation_kwargs
49 )
50 else:
51 response, history = chat_mllava(
52 text, images, self.model, self.processor, history=history, **generation_kwargs
53 )
54 response_list.append(response)
55
56 if len(response_list) == 1:
57 return response_list[0]
58 else:
59 return response_list
60
61
62if __name__ == "__main__":
63 parser = argparse.ArgumentParser()
64 parser.add_argument("--device", type=str, default="cuda:0")
65 parser.add_argument(
66 "--model_path",
67 type=str,
68 default="path_to_your_download_model"
69 )
70 args = parser.parse_args()
71
72 Med_Mantis_model = Med_Mantis_Inference(
73 device=args.device,
74 model_path=args.model_path
75 )
76 print("Successfully loaded the merged model")
77
78 images_path = [
79 "path_to_test_img_1",
80 "path_to_test_img_2"
81 ]
82 usr_text_list = "User question"
83
84 # Inference
85 result = Med_Mantis_model(images_path, usr_text_list)
86 print(result)