A newer version of the Gradio SDK is available: 6.22.0
title: ChestViT Explainable XRay AI
emoji: π«
colorFrom: indigo
colorTo: blue
sdk: gradio
sdk_version: 5.33.0
app_file: app.py
pinned: false
Multi-Task Vision Transformer for Chest X-Ray Disease Classification & Explainability
ViT-Base-16 Β· 14-Disease Multi-Label Classification Β· Attention Rollout XAI
Fine-tuned on NIH ChestX-ray14 (112,120 frontal chest X-rays)
π― Overview
This project implements an explainable medical AI system for automated chest X-ray analysis. Unlike standard classification models, this system simultaneously:
- Predicts 14 diseases in parallel (multi-label, not multi-class)
- Shows WHERE in the X-ray the model is looking via Attention Rollout
- Compares against published NIH baselines (AUC-ROC per class)
- Serves a live demo via a Gradio dashboard
The core insight: Vision Transformers (ViTs) divide images into 16Γ16 patches and route information through 12 attention layers. Attention Rollout traces this information flow back to the input patches β telling us exactly which lung regions drove each disease prediction.
π Architecture
Chest X-Ray Input (PNG, 1024Γ1024)
β
βΌ
βββββββββββββββββββββββββ
β CLAHE Preprocessing β β Contrast Limited Adaptive Histogram Equalization
β + Albumentations β β Radiologically-realistic augmentation
βββββββββββββββββββββββββ
β 224Γ224Γ3
βΌ
βββββββββββββββββββββββββββββββββββββββββββββ
β ViT-Base-16 β
β (google/vit-base-patch16-224-in21k) β
β β
β βββββββββββββββββββββββββββββββββββββββ β
β β 196 Patches (14Γ14 grid, 16px/ea) β β
β β + [CLS] token = 197 total tokens β β
β βββββββββββββββββββββββββββββββββββββββ β
β β β
β 12 Transformer Layers β
β (12 heads Γ 64 dim = 768 hidden dim) β
β β β
β [CLS] token β Dropout β Linear(768β14) β
βββββββββββββββββββββββββββββββββββββββββββββ
β
ββββ Logits β Sigmoid β 14 disease probabilities
β
ββββ Attention weights (12 layers Γ 12 heads)
β
βΌ
Attention Rollout Algorithm
(14Γ14 patch attention map)
β
βΌ
224Γ224 heatmap overlay on X-ray
π Results
| Disease | ViT AUC | NIH Baseline | Ξ AUC |
|---|---|---|---|
| Atelectasis | β | 0.7003 | β |
| Cardiomegaly | β | 0.8100 | β |
| Effusion | β | 0.7585 | β |
| Infiltration | β | 0.6614 | β |
| Mass | β | 0.6933 | β |
| Nodule | β | 0.6689 | β |
| Pneumonia | β | 0.6580 | β |
| Pneumothorax | β | 0.7993 | β |
| Consolidation | β | 0.7032 | β |
| Edema | β | 0.8052 | β |
| Emphysema | β | 0.8330 | β |
| Fibrosis | β | 0.7859 | β |
| Pleural_Thickening | β | 0.6835 | β |
| Hernia | β | 0.8717 | β |
| MACRO AVERAGE | β | 0.7523 | β |
Results will populate after training. NIH baseline from Wang et al. (2017).
π Quick Start
1. Install Dependencies
# Create virtual environment
python -m venv venv
venv\Scripts\activate # Windows
# source venv/bin/activate # Linux/macOS
# Install dependencies
pip install -r requirements.txt
2. Download Dataset
# First: set up Kaggle API credentials
# 1. Go to https://www.kaggle.com β Account β Settings β Create New API Token
# 2. Place kaggle.json at: C:\Users\<YourName>\.kaggle\kaggle.json
# Then download NIH ChestX-ray14 (~42 GB)
python data/download.py
3. Run Unit Tests
python -m pytest tests/ -v
4. Train the Model
# Full training (5 epochs, ~8-12 hours on RTX 3050)
python training/train.py
# Quick smoke test (20% of data)
# Edit config/config.yaml β dataset.train_fraction: 0.2
python training/train.py
Monitor training in real-time:
mlflow ui --backend-store-uri ./experiments/mlflow
# Open http://localhost:5000
5. Launch Demo
# With trained model
python app/gradio_app.py
# DEMO MODE (random weights, for UI preview only)
set DEMO_MODE=1 # Windows
python app/gradio_app.py
π Project Structure
.
βββ config/
β βββ config.yaml # All hyperparameters and paths
βββ data/
β βββ download.py # Kaggle API dataset download
β βββ preprocessing.py # CLAHE + Albumentations pipeline
β βββ dataset.py # ChestXrayDataset + DataLoaders
β βββ raw/ # Downloaded dataset (not in git)
βββ models/
β βββ vit_model.py # ViT-Base-16 with multi-label head
βββ explainability/
β βββ attention_rollout.py # Attention Rollout algorithm
βββ training/
β βββ losses.py # Weighted BCE + Focal Loss
β βββ train.py # Training loop (mixed precision, MLflow)
β βββ evaluate.py # AUC-ROC per class, ROC plots
βββ app/
β βββ gradio_app.py # Gradio dashboard
βββ tests/
β βββ test_modules.py # Unit tests (no dataset required)
βββ checkpoints/ # Saved model weights (not in git)
βββ results/ # ROC curves, metrics CSV
βββ experiments/
β βββ mlflow/ # MLflow tracking database
βββ config_loader.py # YAML config loader
βββ requirements.txt
βοΈ Configuration
All settings are in config/config.yaml. Key RTX 3050 settings:
training:
batch_size: 8 # Fits in 4 GB VRAM
gradient_accumulation_steps: 4 # Effective batch = 32
mixed_precision: true # fp16 β mandatory for 4 GB VRAM
num_epochs: 5
model:
name: "google/vit-base-patch16-224-in21k"
gradient_checkpointing: true # Saves ~30% VRAM
dataset:
train_fraction: 1.0 # Set 0.2 for quick smoke test
π₯ Attention Rollout: Why Not Grad-CAM?
| Method | Grad-CAM | Attention Rollout |
|---|---|---|
| Designed for | CNNs | Transformers |
| Spatial resolution | Depends on last conv layer | 14Γ14 patch grid |
| Accounts for skip connections | No | Yes (identity matrix) |
| Computational cost | Requires backward pass | Forward pass only |
| ViT-specific | No | Yes |
Attention Rollout (Abnar & Zuidema, 2020) is mathematically derived from the transformer's own attention mechanism, making it the correct tool for ViT explainability.
π₯ Clinical Context
β οΈ This is a research/educational project, NOT a medical device. Results should not be used for clinical diagnosis without radiologist review.
The NIH ChestX-ray14 dataset has known limitations (Rajpurkar et al., 2018, and others). AUC-ROC is the clinically relevant metric because:
- Accuracy is misleading with class imbalance (>53% "No Finding")
- AUC measures discriminative ability across all thresholds
- Radiologists can set their own confidence threshold per clinical context
π References
- Wang, X. et al. (2017). ChestX-ray8: Hospital-scale Chest X-ray Database and Benchmarks. CVPR.
- Dosovitskiy, A. et al. (2021). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. ICLR.
- Abnar, S. & Zuidema, W. (2020). Quantifying Attention Flow in Transformers. arXiv:2005.00928.
- Rajpurkar, P. et al. (2017). CheXNet: Radiologist-Level Pneumonia Detection on Chest X-Rays with Deep Learning. arXiv:1711.05225.
π Tech Stack
| Tool | Version | Purpose |
|---|---|---|
| PyTorch | 2.1+ | Training framework |
| HuggingFace Transformers | 4.37+ | ViT-Base-16 backbone |
| OpenCV | 4.9+ | CLAHE preprocessing |
| Albumentations | 1.3+ | Image augmentation |
| scikit-learn | 1.4+ | AUC-ROC metrics |
| MLflow | 2.10+ | Experiment tracking |
| Gradio | 4.x | Demo dashboard |
| Kaggle API | 1.6+ | Dataset download |