Views
No views yet
pip install qwen-vl-utils1from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
2from qwen_vl_utils import process_vision_info
3
4# default: Load the model on the available device(s)
5model = Qwen2VLForConditionalGeneration.from_pretrained(
6 "AdaptLLM/biomed-Qwen2-VL-2B-Instruct", torch_dtype="auto", device_map="auto"
7)
8
9# We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
10# model = Qwen2VLForConditionalGeneration.from_pretrained(
11# "AdaptLLM/biomed-Qwen2-VL-2B-Instruct",
12# torch_dtype=torch.bfloat16,
13# attn_implementation="flash_attention_2",
14# device_map="auto",
15# )
16
17# default processer
18processor = AutoProcessor.from_pretrained("AdaptLLM/biomed-Qwen2-VL-2B-Instruct")
19
20# The default range for the number of visual tokens per image in the model is 4-16384. You can set min_pixels and max_pixels according to your needs, such as a token count range of 256-1280, to balance speed and memory usage.
21# min_pixels = 256*28*28
22# max_pixels = 1280*28*28
23# processor = AutoProcessor.from_pretrained("AdaptLLM/biomed-Qwen2-VL-2B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
24
25
26# NOTE: For AdaMLLM, always place the image at the beginning of the input instruction in the messages.
27messages = [
28 {
29 "role": "user",
30 "content": [
31 {
32 "type": "image",
33 "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
34 },
35 {"type": "text", "text": "Describe this image."},
36 ],
37 }
38]
39
40# Preparation for inference
41text = processor.apply_chat_template(
42 messages, tokenize=False, add_generation_prompt=True
43)
44image_inputs, video_inputs = process_vision_info(messages)
45inputs = processor(
46 text=[text],
47 images=image_inputs,
48 videos=video_inputs,
49 padding=True,
50 return_tensors="pt",
51)
52inputs = inputs.to("cuda")
53
54# Inference: Generation of the output
55generated_ids = model.generate(**inputs, max_new_tokens=128)
56generated_ids_trimmed = [
57 out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
58]
59output_text = processor.batch_decode(
60 generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
61)
62print(output_text)1@article{adamllm,
2 title={On Domain-Adaptive Post-Training for Multimodal Large Language Models},
3 author={Cheng, Daixuan and Huang, Shaohan and Zhu, Ziyu and Zhang, Xintong and Zhao, Wayne Xin and Luan, Zhongzhi and Dai, Bo and Zhang, Zhenliang},
4 journal={arXiv preprint arXiv:2411.19930},
5 year={2024}
6}1@inproceedings{
2cheng2024adapting,
3title={Adapting Large Language Models via Reading Comprehension},
4author={Daixuan Cheng and Shaohan Huang and Furu Wei},
5booktitle={The Twelfth International Conference on Learning Representations},
6year={2024},
7url={https://openreview.net/forum?id=y886UXPEZ0}
8}