Downloads · 30 days
0
kelkalot/medgemma-4b-it-sft-lora-kvasir-vqa
medgemma-4b-it-sft-lora-kvasir-vqa is a machine learning model from kelkalot. Use it for the machine learning task on the model card, and read the license before you ship it in a product. It is set up for transformers. The card lists the license as apache-2.0.
This model is a fine-tuned version of 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-…
Downloads · 30 days
0
Access
Public
Updated May 23, 2025
Repo size
8.6 GB
Likes
5
Public
Click a slice to open those files.
.pt5.7 GB · 50%
From the Hugging Face model README
This model is a fine-tuned version of 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.
This repository contains a LoRA adapter for the 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-vqaThis model adapter is intended for direct use in Visual Question Answering tasks involving medical endoscopic images similar to those in the Kvasir-VQA dataset. It can be loaded with the base google/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.
Example applications:
The LoRA adapter could potentially be further fine-tuned on more specific medical VQA datasets or integrated into larger medical AI systems that require image understanding and question answering capabilities.
Users (both direct and downstream) must be fully aware of the risks, biases, and limitations of this model.
Use the code below to load the fine-tuned model and run inference. Ensure you have accepted the terms of use for the base google/medgemma-4b-it model.
import torch
from transformers import AutoModelForImageTextToText, AutoProcessor, pipeline
from peft import PeftModel
from PIL import Image
import requests # For fetching image from URL
from io import BytesIO
# from IPython.display import display, HTML # For notebook display
# --- Configuration ---
base_model_name = "google/medgemma-4b-it"
adapter_hub_id = "kelkalot/medgemma-4b-it-sft-lora-kvasir-vqa" # This model
# Determine torch_dtype based on GPU capability
if torch.cuda.is_available() and torch.cuda.get_device_capability()[0] >= 8:
dtype = torch.bfloat16
print("Using torch.bfloat16.")
else:
dtype = torch.float32
print("Warning: bfloat16 not supported or no GPU. Using float32.")
# --- Load Processor ---
# The processor should have been pushed with your adapter.
try:
processor = AutoProcessor.from_pretrained(adapter_hub_id)
print(f"Loaded processor from adapter repository: {adapter_hub_id}")
except Exception as e:
print(f"Could not load processor from {adapter_hub_id}: {e}. Loading from base model as fallback.")
processor = AutoProcessor.from_pretrained(base_model_name)
processor.tokenizer.padding_side = "right"
# --- Load Base Model ---
print(f"Loading base model: {base_model_name}")
base_model = AutoModelForImageTextToText.from_pretrained(
base_model_name,
torch_dtype=dtype,
device_map="auto" # Automatically uses GPU if available
)
# --- Apply LoRA Adapter ---
print(f"Applying LoRA adapter from: {adapter_hub_id}")
model = PeftModel.from_pretrained(base_model, adapter_hub_id)
model = model.eval() # Set to evaluation mode
print("Fine-tuned model ready.")
# --- Create Pipeline ---
device = model.device # Get device where PEFT model is loaded
vqa_pipeline = pipeline(
"image-text-to-text",
model=model,
processor=processor,
device=device
)
print(f"Pipeline created on device: {device}")
# --- Prepare Sample Input ---
# Example image from Kvasir-VQA dataset (replace with your image path or URL)
sample_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)"
sample_question = "What is the main color of the area indicated by the green box?" # Corresponds to the example image
pil_image = None
try:
response = requests.get(sample_image_url)
response.raise_for_status()
pil_image = Image.open(BytesIO(response.content)).convert("RGB")
except Exception as e:
print(f"Could not load sample image from URL ({sample_image_url}): {e}")
if pil_image:
# Format messages for the pipeline (image embedded in messages)
messages = [
{"role": "user", "content": [
{"type": "text", "text": sample_question},
{"type": "image", "image": pil_image} # Embed the actual PIL image
]},
]
# --- Run Inference ---
print(f"\nQuestion: {sample_question}")
if vqa_pipeline.device.type == "cuda": torch.cuda.empty_cache()
output = vqa_pipeline(
text=[messages], # Pipeline expects a list of conversations
return_full_text=False,
max_new_tokens=50 # Adjust as needed
)
# Parse output (based on observed structure [[{'generated_text': '...'}]])
generated_text = "Could not parse output."
if output and isinstance(output, list) and len(output) > 0:
first_result_list = output[0]
if isinstance(first_result_list, list) and len(first_result_list) > 0 and isinstance(first_result_list[0], dict):
generated_text = first_result_list[0].get("generated_text", "Key 'generated_text' not found").strip()
elif isinstance(first_result_list, dict): # If output is [{...}]
generated_text = first_result_list.get("generated_text", "Key 'generated_text' not found").strip()
print(f"Model Answer: {generated_text}")
# For display in Jupyter/Colab:
# from IPython.display import display, HTML
# display(HTML(f"<h3>Question: {sample_question}</h3> <p style='color:green;'><b>Model Answer:</b> {generated_text}</p>"))
# display(pil_image.resize((300, int(300 * pil_image.height / pil_image.width))))
else:
print("Sample image could not be loaded. Skipping inference example.")
This model was fine-tuned on the Kvasir-VQA dataset (SimulaMet-HOST/Kvasir-VQA). This dataset contains pairs of endoscopic images and corresponding medical questions and answers.
The model was fine-tuned using Parameter-Efficient Fine-Tuning (PEFT) with LoRA (Low-Rank Adaptation) via the Hugging Face transformers and trl (SFTTrainer) libraries. 4-bit quantization (QLoRA) was employed to reduce memory footprint during training.
Input images and text prompts were processed using the 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)Fine-tuning was performed on a Google Colab A100 GPU (40GB). Training time for the specified subset and 1 epoch was approximately 45-60 minutes.
Fine-tuning with LoRA on the Kvasir-VQA dataset showed an improvement in the model's ability to answer questions specific to the dataset's domain compared to the baseline model.
The base model 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.Please cite the original Kvasir-VQA dataset and MedGemma if you use this model in your research.
Kvasir-VQA & Kvasir Dataset Collection:
@article{borgli2020hyperkvasir,
title={HyperKvasir, a comprehensive multi-class image and video dataset for gastrointestinal endoscopy},
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},
journal={Scientific data},
volume={7},
number={1},
pages={283},
year={2020},
publisher={Nature Publishing Group UK London}
}
@inproceedings{gautam2024kvasir,
title={Kvasir-vqa: A text-image pair gi tract dataset},
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},
booktitle={Proceedings of the First International Workshop on Vision-Language Models for Biomedical Applications},
pages={3--12},
year={2024}
}