Views
No views yet
KeyError: 'qwen2_vl' or ImportError: cannot import name 'Qwen2VLForConditionalGeneration' from 'transformers', try installing the latest version of the transformers library from source:pip install git+https://github.com/huggingface/transformers1from PIL import Image
2from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
3from transformers import BitsAndBytesConfig
4import torch
5
6model_id = "Ertugrul/Qwen2-VL-7B-Captioner-Relaxed"
7
8model = Qwen2VLForConditionalGeneration.from_pretrained(
9 model_id, torch_dtype=torch.bfloat16, device_map="auto"
10)
11processor = AutoProcessor.from_pretrained(model_id)
12
13conversation = [
14 {
15 "role": "user",
16 "content": [
17 {
18 "type": "image",
19 },
20 {"type": "text", "text": "Describe this image."},
21 ],
22 }
23]
24
25
26
27image = Image.open(r"PATH_TO_YOUR_IMAGE")
28
29# you can resize the image here if it's not fitting to vram, or set model max sizes.
30# image = image.resize((1024, 1024)) # like this
31
32text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
33
34inputs = processor(
35 text=[text_prompt], images=[image], padding=True, return_tensors="pt"
36)
37inputs = inputs.to("cuda")
38
39with torch.no_grad():
40 with torch.autocast(device_type="cuda", dtype=torch.bfloat16):
41 output_ids = model.generate(**inputs, max_new_tokens=384, do_sample=True, temperature=0.7, use_cache=True, top_k=50)
42
43
44generated_ids = [
45 output_ids[len(input_ids) :]
46 for input_ids, output_ids in zip(inputs.input_ids, output_ids)
47]
48output_text = processor.batch_decode(
49 generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
50)[0]
51print(output_text)