Views
No views yet
google/medgemma-4b-it adapted for Visual Question Answering (VQA) on medical endoscopic imagery using the Kvasir-VQA dataset. It utilizes LoRA (Low-Rank Adaptation) for parameter-efficient fine-tuning.google/medgemma-4b-it model. MedGemma is a family of open-weight generative models specialized for the medical domain, built upon Google's Gemma. This adapter enables the base MedGemma model to answer questions about medical images, specifically those found in the Kvasir-VQA dataset which primarily consists of endoscopic images.google/medgemma-4b-ithttps://huggingface.co/kelkalot/medgemma-4b-it-sft-lora-kvasir-vqagoogle/medgemma-4b-it model to perform inference. Users can provide an image and a textual question to receive a textual answer generated by the model. This is primarily for research and exploration of multimodal AI in medicine.google/medgemma-4b-it model.1import torch
2from transformers import AutoModelForImageTextToText, AutoProcessor, pipeline
3from peft import PeftModel
4from PIL import Image
5import requests # For fetching image from URL
6from io import BytesIO
7# from IPython.display import display, HTML # For notebook display
8
9# --- Configuration ---
10base_model_name = "google/medgemma-4b-it"
11adapter_hub_id = "kelkalot/medgemma-4b-it-sft-lora-kvasir-vqa" # This model
12
13# Determine torch_dtype based on GPU capability
14if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8:
15 dtype = torch.bfloat16
16 print("Using torch.bfloat16.")
17else:
18 dtype = torch.float32
19 print("Warning: bfloat16 not supported or no GPU. Using float32.")
20
21# --- Load Processor ---
22# The processor should have been pushed with your adapter.
23try:
24 processor = AutoProcessor.from_pretrained(adapter_hub_id)
25 print(f"Loaded processor from adapter repository: {adapter_hub_id}")
26except Exception as e:
27 print(f"Could not load processor from {adapter_hub_id}: {e}. Loading from base model as fallback.")
28 processor = AutoProcessor.from_pretrained(base_model_name)
29processor.tokenizer.padding_side = "right"
30
31# --- Load Base Model ---
32print(f"Loading base model: {base_model_name}")
33base_model = AutoModelForImageTextToText.from_pretrained(
34 base_model_name,
35 torch_dtype=dtype,
36 device_map="auto" # Automatically uses GPU if available
37)
38
39# --- Apply LoRA Adapter ---
40print(f"Applying LoRA adapter from: {adapter_hub_id}")
41model = PeftModel.from_pretrained(base_model, adapter_hub_id)
42model = model.eval() # Set to evaluation mode
43
44print("Fine-tuned model ready.")
45
46# --- Create Pipeline ---
47device = model.device # Get device where PEFT model is loaded
48vqa_pipeline = pipeline(
49 "image-text-to-text",
50 model=model,
51 processor=processor,
52 device=device
53)
54print(f"Pipeline created on device: {device}")
55
56# --- Prepare Sample Input ---
57# Example image from Kvasir-VQA dataset (replace with your image path or URL)
58sample_image_url = "[https://huggingface.co/datasets/SimulaMet-HOST/Kvasir-VQA/resolve/main/images/cju0v82i38xlp0835wz7s6x0k.jpg](https://huggingface.co/datasets/SimulaMet-HOST/Kvasir-VQA/resolve/main/images/cju0v82i38xlp0835wz7s6x0k.jpg)"
59sample_question = "What is the main color of the area indicated by the green box?" # Corresponds to the example image
60
61pil_image = None
62try:
63 response = requests.get(sample_image_url)
64 response.raise_for_status()
65 pil_image = Image.open(BytesIO(response.content)).convert("RGB")
66except Exception as e:
67 print(f"Could not load sample image from URL ({sample_image_url}): {e}")
68
69if pil_image:
70 # Format messages for the pipeline (image embedded in messages)
71 messages = [
72 {"role": "user", "content": [
73 {"type": "text", "text": sample_question},
74 {"type": "image", "image": pil_image} # Embed the actual PIL image
75 ]},
76 ]
77
78 # --- Run Inference ---
79 print(f"\nQuestion: {sample_question}")
80 if vqa_pipeline.device.type == "cuda": torch.cuda.empty_cache()
81
82 output = vqa_pipeline(
83 text=[messages], # Pipeline expects a list of conversations
84 return_full_text=False,
85 max_new_tokens=50 # Adjust as needed
86 )
87
88 # Parse output (based on observed structure [[{'generated_text': '...'}]])
89 generated_text = "Could not parse output."
90 if output and isinstance(output, list) and len(output) > 0:
91 first_result_list = output[0]
92 if isinstance(first_result_list, list) and len(first_result_list) > 0 and isinstance(first_result_list[0], dict):
93 generated_text = first_result_list[0].get("generated_text", "Key 'generated_text' not found").strip()
94 elif isinstance(first_result_list, dict): # If output is [{...}]
95 generated_text = first_result_list.get("generated_text", "Key 'generated_text' not found").strip()
96
97 print(f"Model Answer: {generated_text}")
98
99 # For display in Jupyter/Colab:
100 # from IPython.display import display, HTML
101 # display(HTML(f"<h3>Question: {sample_question}</h3> <p style='color:green;'><b>Model Answer:</b> {generated_text}</p>"))
102 # display(pil_image.resize((300, int(300 * pil_image.height / pil_image.width))))
103else:
104 print("Sample image could not be loaded. Skipping inference example.")SimulaMet-HOST/Kvasir-VQA). This dataset contains pairs of endoscopic images and corresponding medical questions and answers.transformers and trl (SFTTrainer) libraries. 4-bit quantization (QLoRA) was employed to reduce memory footprint during training.AutoProcessor associated with google/medgemma-4b-it. Questions and answers were structured into a conversational format suitable for the SFTTrainer.r: 16alpha: 16dropout: 0.05all-linear layers1e-4bfloat16 mixed precision with 4-bit quantization (QLoRA)google/medgemma-4b-it is a Gemma-based multimodal model. This adapter fine-tunes it using LoRA for the objective of generating textual answers to textual questions conditioned on visual (image) input.transformers, peft, trl, datasets, evaluatebitsandbytes for quantization.1@article{borgli2020hyperkvasir,
2 title={HyperKvasir, a comprehensive multi-class image and video dataset for gastrointestinal endoscopy},
3 author={Borgli, Hanna and Thambawita, Vajira and Smedsrud, Pia H and Hicks, Steven and Jha, Debesh and Eskeland, Sigrun L and Randel, Kristin Ranheim and Pogorelov, Konstantin and Lux, Mathias and Nguyen, Duc Tien Dang and others},
4 journal={Scientific data},
5 volume={7},
6 number={1},
7 pages={283},
8 year={2020},
9 publisher={Nature Publishing Group UK London}
10}
11
12@inproceedings{gautam2024kvasir,
13 title={Kvasir-vqa: A text-image pair gi tract dataset},
14 author={Gautam, Sushant and Stor{\aa}s, Andrea M and Midoglu, Cise and Hicks, Steven A and Thambawita, Vajira and Halvorsen, P{\aa}l and Riegler, Michael A},
15 booktitle={Proceedings of the First International Workshop on Vision-Language Models for Biomedical Applications},
16 pages={3--12},
17 year={2024}
18}