Medical Vision–Language Model Interpretation and Robustness Analysis
This repository contains a practical, research‑grade toolkit to interrogate and compare visual attention and answer robustness of state‑of‑the‑art medical vision–language models (VLMs) on chest X‑ray question answering. It focuses on two representative models with different training recipes and interfaces:
The code provides consistent attention extraction across both models, quantitative attention quality metrics, and a reproducible robustness study over paraphrased question variants. The implementation is optimized for Colab usage but is modular enough to run locally with the appropriate dependencies and GPU.
attention_viz/
llava_rad_enhanced.py: Enhanced LLaVA‑Rad visualizer and attention extractor.medgemma_enhanced.py: Enhanced MedGemma attention extractor with fallbacks.compare_attention_colab.py: Single‑case, side‑by‑side comparison pipeline (answers + overlays).run_medical_vlm_analysis_colab.py: Full robustness study pipeline (batch evaluation + report/plots).colab_imports.py: Convenience imports and Colab path setup helpers.medgemma_launch_mimic_fixed.py: Compatibility alias for legacy notebook imports.medical-cxr-vqa-questions_sample*.csv: Example question files with paraphrase variants.archive/: Prior versions and experimental artifacts.pyproject.toml: Minimal project metadata (runtime deps are installed at runtime in Colab).(image_size / patch_size)^2 (default 336/14 → 24×24).Reference implementation: EnhancedLLaVARadVisualizer.extract_attention_robust and extract_visual_attention_multihead in attention_viz/llava_rad_enhanced.py.
Reference implementation: EnhancedAttentionExtractor.extract_token_conditioned_attention_robust in attention_viz/medgemma_enhanced.py.
A be the normalized attention over N patches. H(A) = -∑ A log A, H_max = log N, focus = 1 − H(A)/H_max (higher is more concentrated).1 − JS(A_i, A_j) across prompts; also compute JS distribution between models per sample.Reference implementation: AttentionMetrics in attention_viz/llava_rad_enhanced.py and usage throughout.
study_id, image_path, question, answer, question_variant, etc.).Reference implementation: run_medical_vlm_analysis_colab.py (see InferenceResult, run_robustness_study, analyze_results, visualize_results, generate_report).
The pipelines are designed for Colab GPUs where model weights can be installed on demand.
Upload attention_viz/run_medical_vlm_analysis_colab.py to Colab and run:
!python run_medical_vlm_analysis_colab.py --n_studies 25 --output_dir robustness_output
What it does:
/content/medical-vlm-intepret if missing.torch, torchvision, transformers>=4.36.0, opencv-python, scipy, matplotlib, pillow, bitsandbytes, accelerate, gradio.data_root: .../Robust_Medical_LLM_Datasetimage_root: .../MIMIC_JPG/hundred_vqacsv_path: .../attention_viz/medical-cxr-vqa-questions_sample.csvcsv_variants_path: .../attention_viz/medical-cxr-vqa-questions_sample_hardpositives.csvrobustness_output/:
robustness_results.jsonl, analysis_results.json, visualizations/*.png, robustness_report.md.from attention_viz.compare_attention_colab import setup_colab_environment, compare_models_on_input
IN_COLAB, paths = setup_colab_environment()
image_path = f"{paths['image_root']}/10000032.jpg"
prompt = "Is there right lower lobe consolidation suggestive of pneumonia?"
out = compare_models_on_input(
image_path=image_path,
prompt=prompt,
save_outputs=True,
output_dir=paths['output_dir']
)
This produces a side‑by‑side figure (input / LLaVA‑Rad overlay / MedGemma overlay) and optional multi‑head grids for LLaVA.
pyproject.toml is minimal). For local runs replicate the Colab installs:pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121
pip install "transformers>=4.36" opencv-python scipy matplotlib pillow bitsandbytes accelerate gradio
# Optional: LLaVA library (for native LLaVA‑Rad loading)
git clone https://github.com/haotian-liu/LLaVA.git
pip install -e LLaVA
bitsandbytes; set load_in_8bit=True (default) to fit consumer GPUs.llava-hf/llava-1.5-7b-hf if LLaVA library loading fails. MedGemma model id defaults to google/med-gemma-3-4b-it but can be swapped.The CSVs are examples; you must provide the actual images on disk and ensure the CSV paths point to them. Minimal required columns:
study_id: groups variants of the same case.image_path: relative path from image_root or absolute path.question: the natural‑language query.answer: short string answer for correctness (e.g., yes/no, present/absent).question_variant or variant_id for the paraphrase method.attention_viz/run_medical_vlm_analysis_colab.py--n_studies: number of unique study_ids to process.--output_dir: output directory for results and figures.--skip_setup: skip environment bootstrap when you manage packages manually.InferenceResult including answers, correctness, latency, attention metrics, and JS divergence.visualizations/.llava-hf/llava-1.5-7b-hf when appropriate.load_in_8bit=True), reduce max_new_tokens, or switch to smaller backbones.image_root/CSV paths printed during setup.If you use this code or ideas in your research, please cite this repository:
@software{medical_vlm_interpret_2025,
title = {Medical VLM Interpretation and Robustness Analysis},
author = {Binesh Kumar},
year = {2025},
url = {https://github.com/thedatasense/medical-vlm-intepret},
}
You may also wish to cite upstream model works (LLaVA, MedGemma) and any datasets you evaluate on (e.g., MIMIC‑CXR).
This repository includes code intended for research and educational purposes. Check the licenses of upstream models and datasets before redistribution or deployment.
20 commits
Jupyter Notebook
82.8%
Python
17.2%
Medical Vision–Language Model Interpretation and Robustness Analysis
This repository contains a practical, research‑grade toolkit to interrogate and compare visual attention and answer robustness of state‑of‑the‑art medical vision–language models (VLMs) on chest X‑ray question answering. It focuses on two representative models with different training recipes and interfaces:
The code provides consistent attention extraction across both models, quantitative attention quality metrics, and a reproducible robustness study over paraphrased question variants. The implementation is optimized for Colab usage but is modular enough to run locally with the appropriate dependencies and GPU.
attention_viz/
llava_rad_enhanced.py: Enhanced LLaVA‑Rad visualizer and attention extractor.medgemma_enhanced.py: Enhanced MedGemma attention extractor with fallbacks.compare_attention_colab.py: Single‑case, side‑by‑side comparison pipeline (answers + overlays).run_medical_vlm_analysis_colab.py: Full robustness study pipeline (batch evaluation + report/plots).colab_imports.py: Convenience imports and Colab path setup helpers.medgemma_launch_mimic_fixed.py: Compatibility alias for legacy notebook imports.medical-cxr-vqa-questions_sample*.csv: Example question files with paraphrase variants.archive/: Prior versions and experimental artifacts.pyproject.toml: Minimal project metadata (runtime deps are installed at runtime in Colab).(image_size / patch_size)^2 (default 336/14 → 24×24).Reference implementation: EnhancedLLaVARadVisualizer.extract_attention_robust and extract_visual_attention_multihead in attention_viz/llava_rad_enhanced.py.
Reference implementation: EnhancedAttentionExtractor.extract_token_conditioned_attention_robust in attention_viz/medgemma_enhanced.py.
A be the normalized attention over N patches. H(A) = -∑ A log A, H_max = log N, focus = 1 − H(A)/H_max (higher is more concentrated).1 − JS(A_i, A_j) across prompts; also compute JS distribution between models per sample.Reference implementation: AttentionMetrics in attention_viz/llava_rad_enhanced.py and usage throughout.
study_id, image_path, question, answer, question_variant, etc.).Reference implementation: run_medical_vlm_analysis_colab.py (see InferenceResult, run_robustness_study, analyze_results, visualize_results, generate_report).
The pipelines are designed for Colab GPUs where model weights can be installed on demand.
Upload attention_viz/run_medical_vlm_analysis_colab.py to Colab and run:
!python run_medical_vlm_analysis_colab.py --n_studies 25 --output_dir robustness_output
What it does:
/content/medical-vlm-intepret if missing.torch, torchvision, transformers>=4.36.0, opencv-python, scipy, matplotlib, pillow, bitsandbytes, accelerate, gradio.data_root: .../Robust_Medical_LLM_Datasetimage_root: .../MIMIC_JPG/hundred_vqacsv_path: .../attention_viz/medical-cxr-vqa-questions_sample.csvcsv_variants_path: .../attention_viz/medical-cxr-vqa-questions_sample_hardpositives.csvrobustness_output/:
robustness_results.jsonl, analysis_results.json, visualizations/*.png, robustness_report.md.from attention_viz.compare_attention_colab import setup_colab_environment, compare_models_on_input
IN_COLAB, paths = setup_colab_environment()
image_path = f"{paths['image_root']}/10000032.jpg"
prompt = "Is there right lower lobe consolidation suggestive of pneumonia?"
out = compare_models_on_input(
image_path=image_path,
prompt=prompt,
save_outputs=True,
output_dir=paths['output_dir']
)
This produces a side‑by‑side figure (input / LLaVA‑Rad overlay / MedGemma overlay) and optional multi‑head grids for LLaVA.
pyproject.toml is minimal). For local runs replicate the Colab installs:pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121
pip install "transformers>=4.36" opencv-python scipy matplotlib pillow bitsandbytes accelerate gradio
# Optional: LLaVA library (for native LLaVA‑Rad loading)
git clone https://github.com/haotian-liu/LLaVA.git
pip install -e LLaVA
bitsandbytes; set load_in_8bit=True (default) to fit consumer GPUs.llava-hf/llava-1.5-7b-hf if LLaVA library loading fails. MedGemma model id defaults to google/med-gemma-3-4b-it but can be swapped.The CSVs are examples; you must provide the actual images on disk and ensure the CSV paths point to them. Minimal required columns:
study_id: groups variants of the same case.image_path: relative path from image_root or absolute path.question: the natural‑language query.answer: short string answer for correctness (e.g., yes/no, present/absent).question_variant or variant_id for the paraphrase method.attention_viz/run_medical_vlm_analysis_colab.py--n_studies: number of unique study_ids to process.--output_dir: output directory for results and figures.--skip_setup: skip environment bootstrap when you manage packages manually.InferenceResult including answers, correctness, latency, attention metrics, and JS divergence.visualizations/.llava-hf/llava-1.5-7b-hf when appropriate.load_in_8bit=True), reduce max_new_tokens, or switch to smaller backbones.image_root/CSV paths printed during setup.If you use this code or ideas in your research, please cite this repository:
@software{medical_vlm_interpret_2025,
title = {Medical VLM Interpretation and Robustness Analysis},
author = {Binesh Kumar},
year = {2025},
url = {https://github.com/thedatasense/medical-vlm-intepret},
}
You may also wish to cite upstream model works (LLaVA, MedGemma) and any datasets you evaluate on (e.g., MIMIC‑CXR).
This repository includes code intended for research and educational purposes. Check the licenses of upstream models and datasets before redistribution or deployment.
20 commits
Jupyter Notebook
82.8%
Python
17.2%