File size: 9,303 Bytes
f6c543e
 
 
 
 
 
ce63dd0
f6c543e
 
 
37fbec9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390c178
37fbec9
 
 
 
 
 
 
 
390c178
 
37fbec9
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
---
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

<div align="center">

![Python](https://img.shields.io/badge/Python-3.10+-3776AB?style=flat-square&logo=python)
![PyTorch](https://img.shields.io/badge/PyTorch-2.1+-EE4C2C?style=flat-square&logo=pytorch)
![HuggingFace](https://img.shields.io/badge/HuggingFace-Transformers-FFD21E?style=flat-square&logo=huggingface)
![Gradio](https://img.shields.io/badge/Gradio-4.x-FF7C00?style=flat-square)
![MLflow](https://img.shields.io/badge/MLflow-Tracking-0194E2?style=flat-square)

**ViT-Base-16 Β· 14-Disease Multi-Label Classification Β· Attention Rollout XAI**

*Fine-tuned on NIH ChestX-ray14 (112,120 frontal chest X-rays)*

</div>

---

## 🎯 Overview

This project implements an **explainable medical AI system** for automated chest X-ray analysis. Unlike standard classification models, this system simultaneously:

1. **Predicts 14 diseases** in parallel (multi-label, not multi-class)
2. **Shows WHERE** in the X-ray the model is looking via Attention Rollout
3. **Compares against** published NIH baselines (AUC-ROC per class)
4. **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

```bash
# 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

```bash
# 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

```bash
python -m pytest tests/ -v
```

### 4. Train the Model

```bash
# 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:
```bash
mlflow ui --backend-store-uri ./experiments/mlflow
# Open http://localhost:5000
```

### 5. Launch Demo

```bash
# 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`](config/config.yaml). Key RTX 3050 settings:

```yaml
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

1. Wang, X. et al. (2017). *ChestX-ray8: Hospital-scale Chest X-ray Database and Benchmarks.* CVPR.
2. Dosovitskiy, A. et al. (2021). *An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale.* ICLR.
3. Abnar, S. & Zuidema, W. (2020). *Quantifying Attention Flow in Transformers.* arXiv:2005.00928.
4. 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 |