Skip to main content

GlassBox-ViT

Explainability (XAI) for Vision Transformers


What is GlassBox-ViT?

GlassBox-ViT is an open-source explainability library designed specifically to address the interpretability challenges of Vision Transformers (ViTs). It provides a unified collection of XAI methods that work seamlessly with both standard architectures and custom models (they can be supported with manual target-layer configuration), enabling practitioners to understand what their vision models learn, where they attend, and why they make specific decisions.

It separates Black Box methods (compatible with any prediction function) from White Box techniques (leveraging native ViT representations), ensuring architectural clarity and respect for infrastructure constraints. Additionally, it provides complementary analysis tools for training sample influence tracing and model compression via knowledge distillation.

The fundamental problem it solves is straightforward: Vision Transformers remain opaque. Millions of parameters and complex attention mechanisms obscure the reasoning behind predictions. GlassBox-ViT bridges this gap by offering:

  • 13 XAI and model-analysis methods: 6 White Box, 5 Black Box, and 2 complementary analysis tools.
  • Unified and consistent visualizations for attention and attribution
  • Flexible architecture: Black Box methods work with arbitrary prediction functions; White Box methods require native Hugging Face ViT models for deeper insights.
  • Infrastructure-aware design: automatically adapts to user tensor devices and data types without explicit device management
  • Comprehensive documentation and practical examples for each method

Quick Start

Installation

pip install glassbox-vit

Or from source:

git clone https://github.com/oscninrob/GlassBox-ViT.git
cd GlassBox-ViT
pip install -e . 

If using uv as your virtual environment manager:

uv venv --python 3.12
source .venv/bin/activate
uv pip install glassbox-vit

If using cuda, verify that torch can access the GPU with:

uv run python -c "import torch; print(torch.cuda.is_available())"

Basic Usage

All image explainers follow a consistent workflow: create an explainer instance, then call generate() to generate visual explanations.

An example image used for generating explanations can be found in the examples/ directory.

from pathlib import Path

from glassbox_vit import GradCamExplainer
from huggingface_hub import download_bucket_files
from transformers import AutoImageProcessor, AutoModelForImageClassification
from PIL import Image


bucket = "z72pepee/tfm-explainability"
remote_dir = "vit-example-checkpoint-1170"

local_dir = Path("./checkpoint-1170")
local_dir.mkdir(parents=True, exist_ok=True)

download_bucket_files(
    bucket,
    files=[
        (
            f"{remote_dir}/config.json",
            local_dir / "config.json",
        ),
        (
            f"{remote_dir}/model.safetensors",
            local_dir / "model.safetensors",
        ),
        (
            f"{remote_dir}/preprocessor_config.json",
            local_dir / "preprocessor_config.json",
        ),
    ]
)

model = AutoModelForImageClassification.from_pretrained(local_dir)
processor = AutoImageProcessor.from_pretrained(local_dir)

image = Image.open("1b7fab84-c996-419a-bded-fc1b7c52869d.png").convert("RGB")

explainer = GradCamExplainer(model=model, processor=processor)

result = explainer.generate(image)

result["gradcam_image"].save("gradcam.png")

pred_id = result["predicted_label_id"]

print(f"Prediction ID: {pred_id}")
print(f"Confidence: {result['prediction_prob']:.4f}")
print(f"Label: {model.config.id2label[pred_id]}")

del explainer
Example input Grad-CAM output
Example dermoscopic image Grad-CAM explanation

Note: For detailed examples, refer to the examples/ directory.


Single-Image Explainers

These methods generate visual explanations for individual predictions.

White Box Methods

White Box methods require native Hugging Face ViT models and processors for direct access to internal representations.

Method Return Keys Key Feature
GradCAM gradcam_image, predicted_label_id, prediction_prob, explained_label_id Class-specific gradient-based saliency.
ScoreCAM scorecam_image, predicted_label_id, prediction_prob Score-weighted activation maps, gradient-free.
Integrated Gradients ig_image, predicted_label_id, prediction_prob Path-integral attribution from baseline to input.
Expected Gradients eg_image, predicted_label_id, prediction_prob Baseline-agnostic gradient attribution.
Rollout rollout_image, predicted_label_id, prediction_prob Attention flow analysis across ViT layers.
SmoothGrad smoothgrad_image, predicted_label_id, prediction_prob Gradient smoothing via input noise injection.
PCA Explainer pca_image, predicted_label_id, prediction_prob Principal component-based feature attribution.

Black Box Methods

Black Box methods accept any prediction function, making them compatible with arbitrary models and inference pipelines.

Method Return Keys Key Feature
LIME lime_image, predicted_label_id, prediction_prob Local linear approximation via superpixel perturbation.
SHAP shap_image, predicted_label_id, prediction_prob Shapley value-based feature importance.
RISE rise_image, predicted_label_id, prediction_prob Randomized Input Sampling for Explanations.
Patch Occlusion patch_image, predicted_label_id, prediction_prob Evaluates feature importance by systematically occluding input patches.

Using Black Box Methods with Hugging Face Models

Since Black Box methods are model-agnostic, they usually require a wrapper function that takes raw numpy images as input (often generated as perturbations by the explainer) and returns a numpy array of class probabilities.

You can use the following bridge function to seamlessly connect your Hugging Face models and processors to any Black Box explainer:

import torch
from PIL import Image

# --- BRIDGE FUNCTION ---
def hf_prediction_function(images_numpy):
    '''
    Converts numpy image perturbations into model probabilities.
    '''
    # Convert numpy arrays to PIL Images
    imgs_pil = [Image.fromarray((img).astype('uint8')) for img in images_numpy]
    
    # Process images and send to device
    inputs = processor(images=imgs_pil, return_tensors="pt").to(device)
    
    # Forward pass
    with torch.no_grad():
        outputs = model(**inputs)
        
    # Return probabilities as a numpy array
    return torch.nn.functional.softmax(outputs.logits, dim=-1).cpu().numpy()

Complementary Analysis Tools

These tools provide analysis beyond single-image explanation, with distinct workflows and outputs.

TracIn (Training Sample Influence)

TracIn traces the influence of training samples on test predictions. Build an index from your training dataset, then query with test images to identify the most influential training samples.

Typical Workflow:

  1. Initialize TracIn with model checkpoints.
  2. Build an influence index from training data.
  3. Query with test images to retrieve ranked influential samples.

Output: JSON containing training samples with influence scores per test image.

Distilling (Knowledge Distillation)

Distilling creates a compressed student model from a larger teacher ViT, enabling efficient deployment while retaining predictive performance.

Typical Workflow:

  1. Define teacher model and student architecture.
  2. Train the student to mimic teacher outputs.
  3. Deploy the lighter student model.

Output: Trained student model with knowledge transferred.


Architecture

Module Organization

glassbox-vit/
├── glassbox_vit/
│   ├── __init__.py
│   ├── lime_explainer.py
│   ├── shap_explainer.py
│   ├── rise_explainer.py
│   ├── rollout_explainer.py
│   ├── patch_explainer.py
│   ├── gradcam_explainer.py
│   ├── scorecam_explainer.py
│   ├── smoothgrad_explainer.py
│   ├── expected_gradients.py
│   ├── integrated_gradients.py
│   ├── pca_explainer.py
│   ├── tracin_explainer.py
│   └── distilling.py
│   
├── examples/
│   
└── README.md

Documentation

Comprehensive examples demonstrating each technique are located in the examples/ directory.

For theoretical background and citations, refer to the References section below.

License

GlassBox-ViT is distributed under the MIT License. See LICENSE file for details.

Contact

For bug reports, feature requests, or general inquiries, please use the GitHub Issues tracker.

Metadata

Release files for glassbox-vit 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for glassbox-vit 0.1.3
File Size Uploaded Provenance Actions
glassbox_vit-0.1.3.tar.gz 29.5 kB Without provenance Details for glassbox_vit-0.1.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for glassbox-vit 0.1.3
File Interpreter ABI Platform Actions
glassbox_vit-0.1.3-py3-none-any.whl Python 3 none any Details for glassbox_vit-0.1.3-py3-none-any.whl

Total release size: 66.8 kB

Release files / glassbox_vit-0.1.3.tar.gz

Download URL glassbox_vit-0.1.3.tar.gz
Size 29.5 kB
Tags Source
SHA-256 checksum
How to use checksums
0374e89c78aca9b204700f1d98f4a62d5ddceba61c9a77f23df34a16a349bf86
BLAKE2b-256 checksum
How to use checksums
dbd80992658f20ca4805dea251a5d573cde812dc15bb3e4b825c792a8e0e8606
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.18

Release files / glassbox_vit-0.1.3-py3-none-any.whl

Download URL glassbox_vit-0.1.3-py3-none-any.whl
Size 37.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8b3e7a288a7206cc19d7c7fed1898f575b8e62d3cbe9fbf72f34f2a18b47708b
BLAKE2b-256 checksum
How to use checksums
501b730b67198a9b99f78e1da30b8f98083c5d6cc92c96937a264c9ca0a99c1d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.18

Security for glassbox-vit 0.1.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page