File size: 18,772 Bytes
fb88467
 
 
 
 
 
 
4814c8e
abe8077
4814c8e
 
 
 
 
 
 
 
 
a1b1ca8
4814c8e
 
 
 
 
 
 
 
5826098
be5c319
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5826098
4814c8e
 
 
 
 
 
 
 
 
a1b1ca8
4814c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1b1ca8
4814c8e
 
 
 
e6105b1
4814c8e
 
 
 
 
5826098
be5c319
 
 
 
 
 
 
 
 
 
 
 
38107f5
be5c319
 
 
 
 
5826098
4814c8e
 
 
 
be5c319
4814c8e
 
be5c319
4814c8e
be5c319
 
 
 
 
4814c8e
 
 
be5c319
4814c8e
 
a1b1ca8
4814c8e
 
 
 
 
be5c319
4814c8e
 
be5c319
 
4814c8e
 
 
 
 
be5c319
4814c8e
 
 
 
 
 
be5c319
 
 
 
 
4814c8e
 
 
be5c319
4814c8e
 
 
 
 
 
be5c319
 
 
 
 
4814c8e
 
 
be5c319
4814c8e
 
 
 
 
be5c319
 
 
 
 
4814c8e
 
 
be5c319
4814c8e
 
 
 
 
be5c319
 
 
 
 
4814c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be5c319
 
 
 
38107f5
be5c319
 
38107f5
 
be5c319
 
 
 
 
4814c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38107f5
4814c8e
 
 
 
 
 
 
 
 
be5c319
 
 
 
 
 
 
4814c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a090f9b
4814c8e
a090f9b
4814c8e
a090f9b
 
 
 
 
 
 
 
4814c8e
a090f9b
 
 
 
 
4814c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1b1ca8
4814c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5826098
be5c319
 
 
 
 
 
 
 
 
5826098
4814c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0101a8b
4814c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
2c7422a
9e20c7f
 
 
 
 
 
 
 
 
 
 
2c7422a
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
---
sdk: gradio
sdk_version: "4.19.0"
app_file: "app.py"
pinned: false
---

<div align="center">
<img src="assets/dashboard.png" alt="Dashboard Preview" width="800"/>

![Python](https://img.shields.io/badge/Python-3.8+-blue.svg)
![PyTorch](https://img.shields.io/badge/PyTorch-2.2+-ee4c2c.svg)
![Transformers](https://img.shields.io/badge/πŸ€—-Transformers-yellow.svg)
![Gradio](https://img.shields.io/badge/Gradio-4.19+-orange.svg)
![License](https://img.shields.io/badge/License-MIT-green.svg)

**A Comprehensive Explainability and Validation Dashboard for Vision Transformers**

[πŸš€ Live Demo](#live-demo) | [πŸ“– Features](#features) | [πŸ’‘ Usage Guide](#usage-guide) | [🀝 Contributing](#contributing)

</div>


## 🌟 Overview

The **ViT Auditing Toolkit** is an advanced, interactive dashboard designed to help researchers, ML practitioners, and AI auditors understand, validate, and improve Vision Transformer (ViT) models. It provides a comprehensive suite of explainability techniques and auditing tools through an intuitive web interface.

### οΏ½ Purpose & Scope

This toolkit is designed as an **Explainable AI (XAI) and Human-Centered AI (HCAI) analysis tool** to help you:

- **Understand model decisions** through visualization and interpretation
- **Identify potential issues** in model behavior before deployment
- **Explore model robustness** through systematic testing
- **Analyze fairness** across different data characteristics
- **Build trust** in AI systems through transparency

**Important**: This is an **exploratory and educational tool** for model analysis and research. For production-level auditing:
- Use comprehensive, representative validation datasets (not single images)
- Conduct systematic bias testing with diverse demographic groups
- Combine automated analysis with domain expert review
- Follow established AI fairness and auditing frameworks

We encourage researchers and practitioners to use this toolkit as a **starting point** for deeper investigation into model behavior, complementing it with rigorous testing protocols and domain expertise.

### �🎭 Why This Toolkit?

- **πŸ” Transparency**: Understand what your ViT models actually "see" and learn
- **βœ… Validation**: Verify model reliability through systematic testing
- **βš–οΈ Fairness**: Detect potential biases across different data subgroups  
- **πŸ›‘οΈ Robustness**: Test prediction stability under various perturbations
- **πŸ“Š Calibration**: Ensure confidence scores reflect true prediction accuracy

---

<a id="features"></a>
## ✨ Features

### πŸ”¬ Basic Explainability
Visualize and understand model predictions through multiple state-of-the-art techniques:

- **🎨 Attention Visualization**: See which image patches the transformer focuses on at each layer and head
- **πŸ”₯ GradCAM**: Gradient-weighted Class Activation Mapping for highlighting discriminative regions
- **πŸ’« GradientSHAP**: Shapley value-based attribution for pixel-level importance

### πŸ”„ Counterfactual Analysis
Test model robustness by systematically perturbing image regions:

- **Patch Perturbation**: Apply blur, blackout, grayscale, or noise to image patches
- **Sensitivity Mapping**: Identify which regions are critical for predictions
- **Prediction Stability**: Measure confidence changes and prediction flip rates

### πŸ“Š Confidence Calibration
Evaluate whether model confidence scores accurately reflect prediction reliability:

- **Calibration Curves**: Visual assessment of confidence vs accuracy alignment
- **Reliability Diagrams**: Binned analysis of prediction calibration
- **Metrics Dashboard**: Mean confidence, overconfidence rate, and underconfidence rate

### βš–οΈ Bias Detection
Identify performance disparities across different data subgroups:

- **Subgroup Analysis**: Compare performance across demographic or environmental variations
- **Fairness Metrics**: Detect systematic biases in model predictions
- **Comparative Visualization**: Side-by-side analysis of confidence distributions

---

<a id="live-demo"></a>
## πŸš€ Live Demo

Try the toolkit instantly on Hugging Face Spaces:

### πŸ‘‰ [Launch Interactive Demo](https://huggingface.co/spaces/Dyra1204/ViT-Auditing-Toolkit)

*No installation required! Upload an image and start exploring.*

---

## �️ Test Images Included

The project includes **20 curated test images** organized by analysis type:

```bash
examples/
β”œβ”€β”€ basic_explainability/    # 5 images - Clear objects for explanation testing
β”œβ”€β”€ counterfactual/          # 4 images - Centered subjects for robustness testing
β”œβ”€β”€ calibration/             # 3 images - Varied quality for confidence testing
β”œβ”€β”€ bias_detection/          # 4 images - Different conditions for fairness testing
└── general/                 # 4 images - Miscellaneous testing
```

**Quick Download**: Run `python examples/download_samples.py` to get all test images instantly!

See [examples/README.md](examples/README.md) for detailed image descriptions and testing guidelines.

---

## οΏ½πŸ“Έ Screenshots

<div align="center">

### Basic Explainability Interface
<img src="assets/basic-explainability-interface.png" alt="Basic Explainability" width="700"/>

### Counterfactual Analysis
<img src="assets/counterfactual-analysis.png" alt="Counterfactual Analysis" width="700"/>

### Confidence Calibration 
<img src="assets/confidence-calibration.png" alt="Confidence Calibration" width="700"/>

### Bias Detection
<img src="assets/bias-detection.png" alt="Bias Detection" width="700"/>

</div>


---

<a id="usage-guide"></a>
## 🎯 Usage Guide

### Quick Start (3 Steps)

1. **Select a Model**: Choose between ViT-Base or ViT-Large from the dropdown
2. **Upload Your Image**: Any image you want to analyze (JPG, PNG, etc.) or use provided examples
3. **Choose Analysis Type**: Select from 4 tabs based on your needs

**πŸ’‘ Tip**: Use images from the `examples/` directory for quick testing!

### Detailed Workflow

#### πŸ” For Understanding Predictions:
```
1. Go to "Basic Explainability" tab
2. Upload your image (try: examples/basic_explainability/cat_portrait.jpg)
3. Select explanation method (Attention/GradCAM/SHAP)
4. Adjust layer/head indices if needed
5. Click "Analyze Image"
6. View predictions and visual explanations
```

**Example Images to Try**:
- `cat_portrait.jpg` - Clear subject for attention visualization
- `sports_car.jpg` - Distinct features for GradCAM
- `bird_flying.jpg` - Dynamic action for SHAP analysis

#### πŸ”„ For Testing Robustness:
```
1. Go to "Counterfactual Analysis" tab
2. Upload your image (try: examples/counterfactual/flower.jpg)
3. Set patch size (16-64 pixels)
4. Choose perturbation type (blur/blackout/gray/noise)
5. Click "Run Analysis"
6. Review sensitivity maps and metrics
```

**Example Images to Try**:
- `face_portrait.jpg` - Test facial feature importance
- `car_side.jpg` - Identify critical vehicle components
- `flower.jpg` - Simple object for baseline testing

#### πŸ“Š For Validating Confidence:
```
1. Go to "Confidence Calibration" tab
2. Upload a sample image (try: examples/calibration/clear_panda.jpg)
3. Adjust number of bins for analysis
4. Click "Analyze Calibration"
5. Review calibration curves and metrics
```

**Example Images to Try**:
- `clear_panda.jpg` - High-quality image (high confidence expected)
- `workspace.jpg` - Complex scene (varied confidence)
- `outdoor_scene.jpg` - Medium difficulty

#### βš–οΈ For Detecting Bias:
```
1. Go to "Bias Detection" tab
2. Upload a sample image (try: examples/bias_detection/dog_daylight.jpg)
3. Click "Detect Bias"
4. Compare performance across generated subgroups
5. Review fairness metrics
```

**Example Images to Try**:
- `dog_daylight.jpg` - Test lighting variations
- `cat_indoor.jpg` - Indoor vs outdoor performance
- `urban_scene.jpg` - Environmental bias detection

---

## πŸ’» Local Installation

### Prerequisites

- Python 3.8 or higher
- CUDA-compatible GPU (optional, but recommended for faster inference)
- 8GB+ RAM

### Step 1: Clone the Repository

```bash
git clone https://github.com/dyra-12/ViT-XAI-Dashboard.git
cd ViT-XAI-Dashboard
```

### Step 2: Create Virtual Environment (Recommended)

```bash
# Using venv
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# OR using conda
conda create -n vit-audit python=3.10
conda activate vit-audit
```

### Step 3: Install Dependencies

```bash
pip install -r requirements.txt
```

### Step 4: Download Test Images (Optional but Recommended)

```bash
# Download 20 curated test images for all tabs
python examples/download_samples.py

# Or use the bash script
chmod +x examples/download_samples.sh
./examples/download_samples.sh
```

This creates an `examples/` directory with images organized by tab.

### Step 5: Run the Application

```bash
python app.py
```

The dashboard will be available at `http://localhost:7860`

### 🐳 Docker Installation (Alternative)

```bash
# Build the Docker image
docker build -t vit-auditing-toolkit .

# Run the container
docker run -p 7860:7860 vit-auditing-toolkit
```

---

## πŸ—οΈ Project Structure

```
ViT-XAI-Dashboard/
β”‚
β”œβ”€β”€ app.py                      # Main Gradio application
β”œβ”€β”€ requirements.txt            # Python dependencies
β”œβ”€β”€ README.md                   # This file
β”œβ”€β”€ examples/download_samples.py         # Script to download test images
β”‚
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ model_loader.py         # ViT model loading from Hugging Face
β”‚   β”œβ”€β”€ predictor.py            # Prediction and classification logic
β”‚   β”œβ”€β”€ explainer.py            # XAI methods (Attention, GradCAM, SHAP)
β”‚   β”œβ”€β”€ auditor.py              # Advanced auditing tools
β”‚   └── utils.py                # Helper functions and preprocessing
β”‚
β”œβ”€β”€ examples/                   # 20 curated test images
β”‚   β”œβ”€β”€ basic_explainability/   # Images for Tab 1 testing
β”‚   β”œβ”€β”€ counterfactual/         # Images for Tab 2 testing
β”‚   β”œβ”€β”€ calibration/            # Images for Tab 3 testing
β”‚   β”œβ”€β”€ bias_detection/         # Images for Tab 4 testing
β”‚   └── general/                # General purpose test images
β”‚
└── tests/
    β”œβ”€β”€ test_phase1_complete.py # Basic functionality tests
    └── test_advanced_features.py # Advanced auditing tests
```

---

## 🧠 Technical Details

### Vision Transformers (ViT)

Vision Transformers apply the transformer architecture (originally designed for NLP) to computer vision tasks. Key concepts:

- **Patch Embedding**: Images are split into fixed-size patches (e.g., 16Γ—16 pixels)
- **Self-Attention**: Each patch attends to all other patches to capture global context
- **Layer Hierarchy**: Multiple transformer layers progressively refine representations
- **Classification Token**: A special [CLS] token aggregates information for final prediction

**Advantages:**
- Strong performance on large-scale datasets
- Captures long-range dependencies better than CNNs
- More interpretable through attention mechanisms

### Explainability Techniques

#### 1. Attention Visualization
**Method**: Direct visualization of transformer attention weights  
**Purpose**: Shows which image patches the model focuses on  
**Implementation**: Extracts attention matrices from specified layers/heads

```python
# Example: Layer 6, Head 0 typically captures semantic patterns
attention_map = model.encoder.layer[6].attention.self.attention_weights
```

#### 2. GradCAM (Gradient-weighted Class Activation Mapping)
**Method**: Uses gradients flowing into the final conv layer  
**Purpose**: Highlights discriminative regions for target class  
**Implementation**: Via Captum's `LayerGradCam`

```python
# Generates heatmap showing which regions support the prediction
gradcam = LayerGradCam(model, target_layer)
attribution = gradcam.attribute(input, target=predicted_class)
```

#### 3. GradientSHAP (Gradient-based Shapley Values)
**Method**: Combines Shapley values with gradient information  
**Purpose**: Pixel-level attribution with theoretical guarantees  
**Implementation**: Via Captum's `GradientShap`

```python
# Computes fair attribution using random baselines
gradient_shap = GradientShap(model)
attributions = gradient_shap.attribute(input, baselines=random_baselines)
```

### Auditing Methodologies

#### Counterfactual Analysis
Systematically modifies image regions to test:
- **Robustness**: Does the prediction remain stable?
- **Feature Importance**: Which regions matter most?
- **Adversarial Vulnerability**: How easy is it to fool the model?

#### Confidence Calibration
Measures alignment between predicted confidence and actual accuracy:
- **Well-calibrated**: 80% confidence β†’ 80% correct
- **Overconfident**: 90% confidence β†’ 60% correct (problem!)
- **Underconfident**: 50% confidence β†’ 80% correct (less critical)

#### Bias Detection
Compares performance across subgroups to identify:
- **Demographic bias**: Different accuracy for different groups
- **Environmental bias**: Performance varies with lighting, quality, etc.
- **Systematic patterns**: Consistent over/under-performance

---

### πŸ”§ Supported Models

The dashboard now supports multiple architectures (ViT family and others). The models currently exposed in the UI are:

| Display name | Hugging Face ID | Notes |
|--------------:|-----------------|-------|
| ViT-Base | `google/vit-base-patch16-224` | ViT β€” attention visualizations and GradCAM supported |
| ViT-Large | `google/vit-large-patch16-224` | ViT β€” attention visualizations and GradCAM supported |
| ResNet-50 | `microsoft/resnet-50` | CNN β€” GradCAM supported; attention visualization not applicable |
| Swin Transformer | `microsoft/swin-base-patch4-window7-224` | Swin β€” GradCAM supported; attention visualization limited to ViT-style models |
| DeiT | `facebook/deit-base-patch16-224` | ViT-like β€” attention visualizations and GradCAM supported |
| EfficientNet-B7 | `google/efficientnet-b7` | CNN β€” loaded via Hugging Face when possible; if HF loading triggers a torch.load restriction, the app falls back to `timm` (no torch upgrade required). GradCAM supported; attention visualization not applicable |

Notes:
- Attention visualizations (patch-level attention maps) are meaningful for ViT-style models (ViT, DeiT). For CNNs (ResNet, EfficientNet) and some hierarchical transformers (Swin), the dashboard will use GradCAM or a last-conv fallback instead of patch attention.
- EfficientNet on the Hugging Face hub can trigger a torch.load security restriction in older torch versions. The toolkit will transparently fall back to a `timm`-based loader to avoid requiring a torch upgrade; this is handled automatically in `src/model_loader.py`.

**Easy to extend**: Add more models to `src/model_loader.py` under `SUPPORTED_MODELS` and they will appear in the app dropdown.

---

## πŸ“¦ Dependencies

### Core Libraries

- **PyTorch** (β‰₯2.2.0): Deep learning framework
- **Transformers** (β‰₯4.35.0): Hugging Face model hub
- **Gradio** (β‰₯4.19.0): Web interface framework
- **Captum** (β‰₯0.7.0): Model interpretability library

### Supporting Libraries

- **Pillow**: Image processing
- **Matplotlib**: Visualization
- **NumPy**: Numerical computations

See `requirements.txt` for complete list with version constraints.

---

## πŸŽ“ Use Cases

### Research
- **Interpretability Studies**: Analyze transformer attention patterns
- **Benchmark Explainability**: Compare XAI methods systematically
- **Model Auditing**: Validate models before deployment

### Industry
- **Model Validation**: Ensure reliability before production
- **Bias Auditing**: Detect and mitigate fairness issues
- **Regulatory Compliance**: Document model decision-making

### Education
- **Teaching Tool**: Demonstrate XAI concepts interactively
- **Student Projects**: Foundation for ML course assignments
- **Research Training**: Hands-on experience with modern techniques

---

<a id="contributing"></a>
## 🀝 Contributing

Contributions are welcome! Here's how you can help:

### Ways to Contribute

1. **πŸ› Bug Reports**: Open an issue with detailed reproduction steps
2. **✨ Feature Requests**: Suggest new explainability methods or auditing tools
3. **πŸ“ Documentation**: Improve guides, add examples, fix typos
4. **πŸ’» Code**: Submit pull requests for new features or fixes
5. **🎨 UI/UX**: Enhance the dashboard design and user experience

### Development Setup

```bash
# Fork and clone the repository
git clone https://github.com/YOUR-USERNAME/ViT-XAI-Dashboard.git
cd ViT-XAI-Dashboard

# Create a feature branch
git checkout -b feature/your-feature-name

# Make changes and test
python -m pytest tests/

# Commit and push
git commit -m "Add: your feature description"
git push origin feature/your-feature-name

# Open a pull request
```

### Code Style
- Follow PEP 8 guidelines
- Add docstrings to all functions
- Include type hints where applicable
- Write unit tests for new features

---

## οΏ½ Additional Resources

- **[QUICKSTART.md](QUICKSTART.md)** - Get started in 5 minutes
- **[TESTING.md](TESTING.md)** - Comprehensive testing guide with 22 test cases
- **[CONTRIBUTING.md](CONTRIBUTING.md)** - Guidelines for contributors
- **[CHEATSHEET.md](CHEATSHEET.md)** - Quick reference for common tasks
- **[examples/README.md](examples/README.md)** - Detailed test image guide

---

## οΏ½πŸ“„ License

This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.

```
MIT License

Copyright (c) 2024 ViT Auditing Toolkit Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

[Full license text...]
```

---

##  Contact & Support

- **GitHub Issues**: [Report bugs or request features](https://github.com/dyra-12/ViT-XAI-Dashboard/issues)
- **Discussions**: [Ask questions or share ideas](https://github.com/dyra-12/ViT-XAI-Dashboard/discussions)
- **Email**: dyra12@example.com

---

<div align="center">

**Built with ❀️ by the community**

[⬆ Back to Top](#-vit-auditing-toolkit)

</div>
=======
title: ViT Auditing Toolkit
emoji: πŸ’»
colorFrom: gray
colorTo: red
sdk: gradio
sdk_version: 5.49.1
app_file: app.py
pinned: false
---

Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
>>>>>>> hf/main