Views
No views yet
@inproceedings{li2025chemvlm,
title={Chemvlm: Exploring the power of multimodal large language models in chemistry area},
author={Li, Junxian and Zhang, Di and Wang, Xunzhi and Hao, Zeying and Lei, Jingdi and Tan, Qian and Zhou, Cai and Liu, Wei and Yang, Yaotian and Xiong, Xinrui and others},
booktitle={Proceedings of the AAAI Conference on Artificial Intelligence},
volume={39},
number={1},
pages={415--423},
year={2025}
}transformers.Please use transformers==4.37.2 to ensure the model works normally.
1from transformers import AutoTokenizer, AutoModel
2import torch
3import torchvision.transforms as T
4from PIL import Image
5
6from torchvision.transforms.functional import InterpolationMode
7
8
9IMAGENET_MEAN = (0.485, 0.456, 0.406)
10IMAGENET_STD = (0.229, 0.224, 0.225)
11
12
13def build_transform(input_size):
14 MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
15 transform = T.Compose([
16 T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
17 T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
18 T.ToTensor(),
19 T.Normalize(mean=MEAN, std=STD)
20 ])
21 return transform
22
23
24def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
25 best_ratio_diff = float('inf')
26 best_ratio = (1, 1)
27 area = width * height
28 for ratio in target_ratios:
29 target_aspect_ratio = ratio[0] / ratio[1]
30 ratio_diff = abs(aspect_ratio - target_aspect_ratio)
31 if ratio_diff < best_ratio_diff:
32 best_ratio_diff = ratio_diff
33 best_ratio = ratio
34 elif ratio_diff == best_ratio_diff:
35 if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
36 best_ratio = ratio
37 return best_ratio
38
39
40def dynamic_preprocess(image, min_num=1, max_num=6, image_size=448, use_thumbnail=False):
41 orig_width, orig_height = image.size
42 aspect_ratio = orig_width / orig_height
43
44 # calculate the existing image aspect ratio
45 target_ratios = set(
46 (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
47 i * j <= max_num and i * j >= min_num)
48 target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
49
50 # find the closest aspect ratio to the target
51 target_aspect_ratio = find_closest_aspect_ratio(
52 aspect_ratio, target_ratios, orig_width, orig_height, image_size)
53
54 # calculate the target width and height
55 target_width = image_size * target_aspect_ratio[0]
56 target_height = image_size * target_aspect_ratio[1]
57 blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
58
59 # resize the image
60 resized_img = image.resize((target_width, target_height))
61 processed_images = []
62 for i in range(blocks):
63 box = (
64 (i % (target_width // image_size)) * image_size,
65 (i // (target_width // image_size)) * image_size,
66 ((i % (target_width // image_size)) + 1) * image_size,
67 ((i // (target_width // image_size)) + 1) * image_size
68 )
69 # split the image
70 split_img = resized_img.crop(box)
71 processed_images.append(split_img)
72 assert len(processed_images) == blocks
73 if use_thumbnail and len(processed_images) != 1:
74 thumbnail_img = image.resize((image_size, image_size))
75 processed_images.append(thumbnail_img)
76 return processed_images
77
78
79def load_image(image_file, input_size=448, max_num=6):
80 image = Image.open(image_file).convert('RGB')
81 transform = build_transform(input_size=input_size)
82 images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
83 pixel_values = [transform(image) for image in images]
84 pixel_values = torch.stack(pixel_values)
85 return pixel_values
86
87path = "AI4Chem/ChemVLM-26B"
88# If you have an 80G A100 GPU, you can put the entire model on a single GPU.
89model = AutoModel.from_pretrained(
90 path,
91 torch_dtype=torch.bfloat16,
92 low_cpu_mem_usage=True,
93 trust_remote_code=True).eval().cuda()
94# Otherwise, you need to set device_map='auto' to use multiple GPUs for inference.
95# import os
96# os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
97# model = AutoModel.from_pretrained(
98# path,
99# torch_dtype=torch.bfloat16,
100# low_cpu_mem_usage=True,
101# trust_remote_code=True,
102# device_map='auto').eval()
103
104tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
105# set the max number of tiles in `max_num`
106pixel_values = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()
107
108generation_config = dict(
109 num_beams=1,
110 max_new_tokens=512,
111 do_sample=False,
112)
113
114# single-round single-image conversation
115question = "请详细描述图片" # Please describe the picture in detail
116response = model.chat(tokenizer, pixel_values, question, generation_config)
117print(question, response)
118
119# multi-round single-image conversation
120question = "请详细描述图片" # Please describe the picture in detail
121response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
122print(question, response)
123
124question = "请根据图片写一首诗" # Please write a poem according to the picture
125response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
126print(question, response)
127
128# multi-round multi-image conversation
129pixel_values1 = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()
130pixel_values2 = load_image('./examples/image2.jpg', max_num=6).to(torch.bfloat16).cuda()
131pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
132
133question = "详细描述这两张图片" # Describe the two pictures in detail
134response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
135print(question, response)
136
137question = "这两张图片的相同点和区别分别是什么" # What are the similarities and differences between these two pictures
138response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
139print(question, response)
140
141# batch inference (single image per sample)
142pixel_values1 = load_image('./examples/image1.jpg', max_num=6).to(torch.bfloat16).cuda()
143pixel_values2 = load_image('./examples/image2.jpg', max_num=6).to(torch.bfloat16).cuda()
144image_counts = [pixel_values1.size(0), pixel_values2.size(0)]
145pixel_values = torch.cat((pixel_values1, pixel_values2), dim=0)
146
147questions = ["Describe the image in detail."] * len(image_counts)
148responses = model.batch_chat(tokenizer, pixel_values,
149 image_counts=image_counts,
150 questions=questions,
151 generation_config=generation_config)
152for question, response in zip(questions, responses):
153 print(question)
154 print(response)