lwlwlw commited on
Commit
592418d
1 Parent(s): ab08acb

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +174 -2
README.md CHANGED
@@ -3,5 +3,177 @@ license: mit
3
  ---
4
  Finetune based on ChemLLM-20B and InterViT-6B
5
 
6
- Demo
7
- https://v.chemllm.org/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
4
  Finetune based on ChemLLM-20B and InterViT-6B
5
 
6
+
7
+ ## Model Usage
8
+
9
+ We provide an example code to run ChemVLM-26B using `transformers`.
10
+
11
+ You can also use our [online demo](https://v.chemllm.org/) for a quick experience of this model.
12
+
13
+ > Please use transformers==4.37.2 to ensure the model works normally.
14
+
15
+ ```python
16
+ from transformers import AutoTokenizer, AutoModel
17
+ import torch
18
+ import torchvision.transforms as T
19
+ from PIL import Image
20
+
21
+ from torchvision.transforms.functional import InterpolationMode
22
+
23
+
24
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
25
+ IMAGENET_STD = (0.229, 0.224, 0.225)
26
+
27
+
28
+ def build_transform(input_size):
29
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
30
+ transform = T.Compose([
31
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
32
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
33
+ T.ToTensor(),
34
+ T.Normalize(mean=MEAN, std=STD)
35
+ ])
36
+ return transform
37
+
38
+
39
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
40
+ best_ratio_diff = float('inf')
41
+ best_ratio = (1, 1)
42
+ area = width * height
43
+ for ratio in target_ratios:
44
+ target_aspect_ratio = ratio[0] / ratio[1]
45
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
46
+ if ratio_diff < best_ratio_diff:
47
+ best_ratio_diff = ratio_diff
48
+ best_ratio = ratio
49
+ elif ratio_diff == best_ratio_diff:
50
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
51
+ best_ratio = ratio
52
+ return best_ratio
53
+
54
+
55
+ def dynamic_preprocess(image, min_num=1, max_num=6, image_size=448, use_thumbnail=False):
56
+ orig_width, orig_height = image.size
57
+ aspect_ratio = orig_width / orig_height
58
+
59
+ # calculate the existing image aspect ratio
60
+ target_ratios = set(
61
+ (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
62
+ i * j <= max_num and i * j >= min_num)
63
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
64
+
65
+ # find the closest aspect ratio to the target
66
+ target_aspect_ratio = find_closest_aspect_ratio(
67
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
68
+
69
+ # calculate the target width and height
70
+ target_width = image_size * target_aspect_ratio[0]
71
+ target_height = image_size * target_aspect_ratio[1]
72
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
73
+
74
+ # resize the image
75
+ resized_img = image.resize((target_width, target_height))
76
+ processed_images = []
77
+ for i in range(blocks):
78
+ box = (
79
+ (i % (target_width // image_size)) * image_size,
80
+ (i // (target_width // image_size)) * image_size,
81
+ ((i % (target_width // image_size)) + 1) * image_size,
82
+ ((i // (target_width // image_size)) + 1) * image_size
83
+ )
84
+ # split the image
85
+ split_img = resized_img.crop(box)
86
+ processed_images.append(split_img)
87
+ assert len(processed_images) == blocks
88
+ if use_thumbnail and len(processed_images) != 1:
89
+ thumbnail_img = image.resize((image_size, image_size))
90
+ processed_images.append(thumbnail_img)
91
+ return processed_images
92
+
93
+
94
+ def load_image(image_file, input_size=448, max_num=6):
95
+ image = Image.open(image_file).convert('RGB')
96
+ transform = build_transform(input_size=input_size)
97
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
98
+ pixel_values = [transform(image) for image in images]
99
+ pixel_values = torch.stack(pixel_values)
100
+ return pixel_values
101
+
102
+ path = "OpenGVLab/InternVL-Chat-V1-5"
103
+ # If you have an 80G A100 GPU, you can put the entire model on a single GPU.
104
+ model = AutoModel.from_pretrained(
105
+ path,
106
+ torch_dtype=torch.bfloat16,
107
+ low_cpu_mem_usage=True,
108
+ trust_remote_code=True).eval().cuda()
109
+ # Otherwise, you need to set device_map='auto' to use multiple GPUs for inference.
110
+ # import os
111
+ # os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
112
+ # model = AutoModel.from_pretrained(
113
+ # path,
114
+ # torch_dtype=torch.bfloat16,
115
+ # low_cpu_mem_usage=True,
116
+ # trust_remote_code=True,
117
+ # device_map='auto').eval()
118
+
119
+ tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
120
+ # set the max number of tiles in `max_num`
121
+ pixel_values = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()
122
+
123
+ generation_config = dict(
124
+ num_beams=1,
125
+ max_new_tokens=512,
126
+ do_sample=False,
127
+ )
128
+
129
+ # single-round single-image conversation
130
+ question = "请详细描述图片" # Please describe the picture in detail
131
+ response = model.chat(tokenizer, pixel_values, question, generation_config)
132
+ print(question, response)
133
+
134
+ # multi-round single-image conversation
135
+ question = "请详细描述图片" # Please describe the picture in detail
136
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
137
+ print(question, response)
138
+
139
+ question = "请根据图片写一首诗" # Please write a poem according to the picture
140
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
141
+ print(question, response)
142
+
143
+ # multi-round multi-image conversation
144
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()
145
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=6).to(torch.bfloat16).cuda()
146
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
147
+
148
+ question = "详细描述这两张图片" # Describe the two pictures in detail
149
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
150
+ print(question, response)
151
+
152
+ question = "这两张图片的相同点和区别分别是什么" # What are the similarities and differences between these two pictures
153
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
154
+ print(question, response)
155
+
156
+ # batch inference (single image per sample)
157
+ pixel_values1 = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()
158
+ pixel_values2 = load_image('./examples/image2.jpg', max_num=6).to(torch.bfloat16).cuda()
159
+ image_counts = [pixel_values1.size(0), pixel_values2.size(0)]
160
+ pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
161
+
162
+ questions = ["Describe the image in detail."] * len(image_counts)
163
+ responses = model.batch_chat(tokenizer, pixel_values,
164
+ image_counts=image_counts,
165
+ questions=questions,
166
+ generation_config=generation_config)
167
+ for question, response in zip(questions, responses):
168
+ print(question)
169
+ print(response)
170
+ ```
171
+
172
+ ## License
173
+
174
+ This project is released under the MIT license.
175
+
176
+ ## Acknowledgement
177
+
178
+ ChemVLM is built on [InternVL](https://github.com/OpenGVLab/InternVL).
179
+ InternVL is built with reference to the code of the following projects: [OpenAI CLIP](https://github.com/openai/CLIP), [Open CLIP](https://github.com/mlfoundations/open_clip), [CLIP Benchmark](https://github.com/LAION-AI/CLIP_benchmark), [EVA](https://github.com/baaivision/EVA/tree/master), [InternImage](https://github.com/OpenGVLab/InternImage), [ViT-Adapter](https://github.com/czczup/ViT-Adapter), [MMSegmentation](https://github.com/open-mmlab/mmsegmentation), [Transformers](https://github.com/huggingface/transformers), [DINOv2](https://github.com/facebookresearch/dinov2), [BLIP-2](https://github.com/salesforce/LAVIS/tree/main/projects/blip2), [Qwen-VL](https://github.com/QwenLM/Qwen-VL/tree/master/eval_mm), and [LLaVA-1.5](https://github.com/haotian-liu/LLaVA). Thanks for their awesome work!