qwenvl.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from transformers import Qwen2_5_VLForConditionalGeneration, AutoTokenizer, AutoProcessor
  2. from qwen_vl_utils import process_vision_info
  3. model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
  4. "../models/Qwen2.5-VL-3B-Instruct", torch_dtype="auto", device_map="auto"
  5. )
  6. # We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
  7. # model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
  8. # "Qwen/Qwen2.5-VL-3B-Instruct",
  9. # torch_dtype=torch.bfloat16,
  10. # attn_implementation="flash_attention_2",
  11. # device_map="auto",
  12. # )
  13. # default processer
  14. processor = AutoProcessor.from_pretrained("../models/Qwen2.5-VL-3B-Instruct")
  15. # The default range for the number of visual tokens per image in the model is 4-16384.
  16. # You can set min_pixels and max_pixels according to your needs, such as a token range of 256-1280, to balance performance and cost.
  17. # min_pixels = 256*28*28
  18. # max_pixels = 1280*28*28
  19. # processor = AutoProcessor.from_pretrained("Qwen/Qwen2.5-VL-3B-Instruct", min_pixels=min_pixels, max_pixels=max_pixels)
  20. if __name__ == "__main__":
  21. messages = [
  22. {
  23. "role": "user",
  24. "content": [
  25. {
  26. "type": "image",
  27. "image": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
  28. },
  29. {"type": "text", "text": "Describe this image."},
  30. ],
  31. }
  32. ]
  33. # Preparation for inference
  34. text = processor.apply_chat_template(
  35. messages, tokenize=False, add_generation_prompt=True
  36. )
  37. image_inputs, video_inputs = process_vision_info(messages)
  38. inputs = processor(
  39. text=[text],
  40. images=image_inputs,
  41. videos=video_inputs,
  42. padding=True,
  43. return_tensors="pt",
  44. )
  45. inputs = inputs.to("cuda")
  46. # Inference: Generation of the output
  47. generated_ids = model.generate(**inputs, max_new_tokens=128)
  48. generated_ids_trimmed = [
  49. out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
  50. ]
  51. output_text = processor.batch_decode(
  52. generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
  53. )
  54. print(output_text)