Explainability for any 🤗 Transformers models in 2 lines.
Transformers Interpret is a model explainability tool designed to work exclusively with the 🤗 [transformers][transformers] package.
In line with the philosophy of the Transformers package Transformers Interpret allows any transformers model to be explained in just two lines. Explainers are available for both text and computer vision models. Visualizations are also available in notebooks and as savable png and html files.
Check out the streamlit demo app here
pip install transformers-interpret
Let's start by initializing a transformers' model and tokenizer, and running it through the `SequenceClassificationExplainer`. For this example we are using `distilbert-base-uncased-finetuned-sst-2-english`, a distilbert model finetuned on a sentiment analysis task. ```python from transformers import AutoModelForSequenceClassification, AutoTokenizer model_name = "distilbert-base-uncased-finetuned-sst-2-english" model = AutoModelForSequenceClassification.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrained(model_name) # With both the model and tokenizer initialized we are now able to get explanations on an example text. from transformers_interpret import SequenceClassificationExplainer cls_explainer = SequenceClassificationExplainer( model, tokenizer) word_attributions = cls_explainer("I love you, I like you") ``` Which will return the following list of tuples: ```python >>> word_attributions [('[CLS]', 0.0), ('i', 0.2778544699186709), ('love', 0.7792370723380415), ('you', 0.38560088858031094), (',', -0.01769750505546915), ('i', 0.12071898121557832), ('like', 0.19091105304734457), ('you', 0.33994871536713467), ('[SEP]', 0.0)] ``` Positive attribution numbers indicate a word contributes positively towards the predicted class, while negative numbers indicate a word contributes negatively towards the predicted class. Here we can see that **I love you** gets the most attention. You can use `predicted_class_index` in case you'd want to know what the predicted class actually is: ```python >>> cls_explainer.predicted_class_index array(1) ``` And if the model has label names for each class, we can see these too using `predicted_class_name`: ```python >>> cls_explainer.predicted_class_name 'POSITIVE' ``` #### Visualize Classification attributions Sometimes the numeric attributions can be difficult to read particularly in instances where there is a lot of text. To help with that we also provide the `visualize()` method that utilizes Captum's in built viz library to create a HTML file highlighting the attributions. If you are in a notebook, calls to the `visualize()` method will display the visualization in-line. Alternatively you can pass a filepath in as an argument and an HTML file will be created, allowing you to view the explanation HTML in your browser. ```python cls_explainer.visualize("distilbert_viz.html") ``` #### Explaining Attributions for Non Predicted Class Attribution explanations are not limited to the predicted class. Let's test a more complex sentence that contains mixed sentiments. In the example below we pass `class_name="NEGATIVE"` as an argument indicating we would like the attributions to be explained for the **NEGATIVE** class regardless of what the actual prediction is. Effectively because this is a binary classifier we are getting the inverse attributions. ```python cls_explainer = SequenceClassificationExplainer(model, tokenizer) attributions = cls_explainer("I love you, I like you, I also kinda dislike you", class_name="NEGATIVE") ``` In this case, `predicted_class_name` still returns a prediction of the **POSITIVE** class, because the model has generated the same prediction but nonetheless we are interested in looking at the attributions for the negative class regardless of the predicted result. ```python >>> cls_explainer.predicted_class_name 'POSITIVE' ``` But when we visualize the attributions we can see that the words "**...kinda dislike**" are contributing to a prediction of the "NEGATIVE" class. ```python cls_explainer.visualize("distilbert_negative_attr.html") ``` Getting attributions for different classes is particularly insightful for multiclass problems as it allows you to inspect model predictions for a number of different classes and sanity-check that the model is "looking" at the right things. For a detailed explanation of this example please checkout this [multiclass classification notebook.](notebooks/multiclass_classification_example.ipynb) ### Pairwise Sequence Classification The `PairwiseSequenceClassificationExplainer` is a variant of the the `SequenceClassificationExplainer` that is designed to work with classification models that expect the input sequence to be two inputs separated by a models' separator token. Common examples of this are [NLI models](https://arxiv.org/abs/1705.02364) and [Cross-Encoders ](https://www.sbert.net/docs/pretrained_cross-encoders.html) which are commonly used to score two inputs similarity to one another. This explainer calculates pairwise attributions for two passed inputs `text1` and `text2` using the model and tokenizer given in the constructor. Also, since a common use case for pairwise sequence classification is to compare two inputs similarity - models of this nature typically only have a single output node rather than multiple for each class. The pairwise sequence classification has some useful utility functions to make interpreting single node outputs clearer. By default for models that output a single node the attributions are with respect to the inputs pushing the scores closer to 1.0, however if you want to see the attributions with respect to scores closer to 0.0 you can pass `flip_sign=True`. For similarity based models this is useful, as the model might predict a score closer to 0.0 for the two inputs and in that case we would flip the attributions sign to explain why the two inputs are dissimilar. Let's start by initializing a cross-encoder model and tokenizer from the suite of [pre-trained cross-encoders ](https://www.sbert.net/docs/pretrained_cross-encoders.html)provided by [sentence-transformers](https://github.com/UKPLab/sentence-transformers). For this example we are using `"cross-encoder/ms-marco-MiniLM-L-6-v2"`, a high quality cross-encoder trained on the [MSMarco dataset](https://github.com/microsoft/MSMARCO-Passage-Ranking) a passage ranking dataset for question answering and machine reading comprehension. ```python from transformers import AutoModelForSequenceClassification, AutoTokenizer from transformers_interpret import PairwiseSequenceClassificationExplainer model = AutoModelForSequenceClassification.from_pretrained("cross-encoder/ms-marco-MiniLM-L-6-v2") tokenizer = AutoTokenizer.from_pretrained("cross-encoder/ms-marco-MiniLM-L-6-v2") pairwise_explainer = PairwiseSequenceClassificationExplainer(model, tokenizer) # the pairwise explainer requires two string inputs to be passed, in this case given the nature of the model # we pass a query string and a context string. The question we are asking of our model is "does this context contain a valid answer to our question" # the higher the score the better the fit. query = "How many people live in Berlin?" context = "Berlin has a population of 3,520,031 registered inhabitants in an area of 891.82 square kilometers." pairwise_attr = pairwise_explainer(query, context) ``` Which returns the following attributions: ```python >>> pairwise_attr [('[CLS]', 0.0), ('how', -0.037558652124213034), ('many', -0.40348581975409786), ('people', -0.29756140282349425), ('live', -0.48979015417391764), ('in', -0.17844527885888117), ('berlin', 0.3737346097442739), ('?', -0.2281428913480142), ('[SEP]', 0.0), ('berlin', 0.18282430604641564), ('has', 0.039114659489254834), ('a', 0.0820056652212297), ('population', 0.35712150914643026), ('of', 0.09680870840224687), ('3', 0.04791760029513795), (',', 0.040330986539774266), ('520', 0.16307677913176166), (',', -0.005919693904602767), ('03', 0.019431649515841844), ('##1', -0.0243808667024702), ('registered', 0.07748341753369632), ('inhabitants', 0.23904087299731255), ('in', 0.07553221327346359), ('an', 0.033112821611999875), ('area', -0.025378852244447532), ('of', 0.026526373859562906), ('89', 0.0030700151809002147), ('##1', -0.000410387092186983), ('.', -0.0193147139126114), ('82', 0.0073800833347678774), ('square', 0.028988305990861576), ('kilometers', 0.02071182933829008), ('.', -0.025901070914318036), ('[SEP]', 0.0)] ``` #### Visualize Pairwise Classification attributions Visualizing the pairwise attributions is no different to the sequence classification explaine. We can see that in both the `query` and `context` there is a lot of positive attribution for the word `berlin` as well the words `population` and `inhabitants` in the `context`, good signs that our model understands the textual context of the question asked. ```python pairwise_explainer.visualize("cross_encoder_attr.html") ``` If we were more interested in highlighting the input attributions that pushed the model away from the positive class of this single node output we could pass: ```python pairwise_attr = explainer(query, context, flip_sign=True) ``` This simply inverts the sign of the attributions ensuring that they are with respect to the model outputting 0 rather than 1.
This explainer is an extension of the `SequenceClassificationExplainer` and is thus compatible with all sequence classification models from the Transformers package. The key change in this explainer is that it caclulates attributions for each label in the model's config and returns a dictionary of word attributions w.r.t to each label. The `visualize()` method also displays a table of attributions with attributions calculated per label.
```python
from transformers import AutoModelForSequenceClassification, AutoTokenizer
from transformers_interpret import MultiLabelClassificationExplainer
model_name = "j-hartmann/emotion-english-distilroberta-base"
model = AutoModelForSequenceClassification.from_pretrained(model_name)
tokenizer = AutoTokenizer.from_pretrained(model_name)
cls_explainer = MultiLabelClassificationExplainer(model, tokenizer)
word_attributions = cls_explainer("There were many aspects of the film I liked, but it was frightening and gross in parts. My parents hated it.")
```
This produces a dictionary of word attributions mapping labels to a list of tuples for each word and it's attribution score.
Click to see word attribution dictionary
```python
>>> word_attributions
{'anger': [('', 0.0),
('There', 0.09002208622000409),
('were', -0.025129709879675187),
('many', -0.028852677974079328),
('aspects', -0.06341968013631565),
('of', -0.03587626320752477),
('the', -0.014813095892961287),
('film', -0.14087587475098232),
('I', 0.007367876912617766),
('liked', -0.09816592066307557),
(',', -0.014259517291745674),
('but', -0.08087144668471376),
('it', -0.10185214349220136),
('was', -0.07132244710777856),
('frightening', -0.4125361737439814),
('and', -0.021761663818889918),
('gross', -0.10423745223600908),
('in', -0.02383646952201854),
('parts', -0.027137622525091033),
('.', -0.02960415694062459),
('My', 0.05642774605113695),
('parents', 0.11146648216326158),
('hated', 0.8497975489280364),
('it', 0.05358116678115284),
('.', -0.013566277162080632),
('', 0.09293256725788422),
('', 0.0)],
'disgust': [('', 0.0),
('There', -0.035296263203072),
('were', -0.010224922196739717),
('many', -0.03747571761725605),
('aspects', 0.007696321643436715),
('of', 0.0026740873113235107),
('the', 0.0025752851265661335),
('film', -0.040890035285783645),
('I', -0.014710007408208579),
('liked', 0.025696806663391577),
(',', -0.00739107098314569),
('but', 0.007353791868893654),
('it', -0.00821368234753605),
('was', 0.005439709067819798),
('frightening', -0.8135974168445725),
('and', -0.002334953123414774),
('gross', 0.2366024374426269),
('in', 0.04314772995234148),
('parts', 0.05590472194035334),
('.', -0.04362554293972562),
('My', -0.04252694977895808),
('parents', 0.051580790911406944),
('hated', 0.5067406070057585),
('it', 0.0527491071885104),
('.', -0.008280280618652273),
('', 0.07412384603053103),
('', 0.0)],
'fear': [('', 0.0),
('There', -0.019615758046045408),
('were', 0.008033402634196246),
('many', 0.027772367717635423),
('aspects', 0.01334130725685673),
('of', 0.009186049991879768),
('the', 0.005828877177384549),
('film', 0.09882910753644959),
('I', 0.01753565003544039),
('liked', 0.02062597344466885),
(',', -0.004469530636560965),
('but', -0.019660439408176984),
('it', 0.0488084071292538),
('was', 0.03830859527501167),
('frightening', 0.9526443954511705),
('and', 0.02535156284103706),
('gross', -0.10635301961551227),
('in', -0.019190425328209065),
('parts', -0.01713006453323631),
('.', 0.015043169035757302),
('My', 0.017068079071414916),
('parents', -0.0630781275517486),
('hated', -0.23630028921273583),
('it', -0.056057044429020306),
('.', 0.0015102052077844612),
('', -0.010045048665404609),
('', 0.0)],
'joy': [('', 0.0),
('There', 0.04881772670614576),
('were', -0.0379316152427468),
('many', -0.007955371089444285),
('aspects', 0.04437296429416574),
('of', -0.06407011137335743),
('the', -0.07331568926973099),
('film', 0.21588462483311055),
('I', 0.04885724513463952),
('liked', 0.5309510543276107),
(',', 0.1339765195225006),
('but', 0.09394079060730279),
('it', -0.1462792330432028),
('was', -0.1358591558323458),
('frightening', -0.22184169339341142),
('and', -0.07504142930419291),
('gross', -0.005472075984252812),
('in', -0.0942152657437379),
('parts', -0.19345218754215965),
('.', 0.11096247277185402),
('My', 0.06604512262645984),
('parents', 0.026376541098236207),
('hated', -0.4988319510231699),
('it', -0.17532499366236615),
('.', -0.022609976138939034),
('', -0.43417114685294833),
('', 0.0)],
'neutral': [('', 0.0),
('There', 0.045984598036642205),
('were', 0.017142566357474697),
('many', 0.011419348619472542),
('aspects', 0.02558593440287365),
('of', 0.0186162232003498),
('the', 0.015616416841815963),
('film', -0.021190511300570092),
('I', -0.03572427925026324),
('liked', 0.027062554960050455),
(',', 0.02089914209290366),
('but', 0.025872618597570115),
('it', -0.002980407262316265),
('was', -0.022218157611174086),
('frightening', -0.2982516449116045),
('and', -0.01604643529040792),
('gross', -0.04573829263548096),
('in', -0.006511536166676108),
('parts', -0.011744224307968652),
('.', -0.01817041167875332),
('My', -0.07362312722231429),
('parents', -0.06910711601816408),
('hated', -0.9418903509267312),
('it', 0.022201795222373488),
('.', 0.025694319747309045),
('', 0.04276690822325994),
('', 0.0)],
'sadness': [('', 0.0),
('There', 0.028237893283377526),
('were', -0.04489910545229568),
('many', 0.004996044977269471),
('aspects', -0.1231292680125582),
('of', -0.04552690725956671),
('the', -0.022077819961347042),
('film', -0.14155752357877663),
('I', 0.04135347872193571),
('liked', -0.3097732540526099),
(',', 0.045114660009053134),
('but', 0.0963352125332619),
('it', -0.08120617610094617),
('was', -0.08516150809170213),
('frightening', -0.10386889639962761),
('and', -0.03931986389970189),
('gross', -0.2145059013625132),
('in', -0.03465423285571697),
('parts', -0.08676627134611635),
('.', 0.19025217371906333),
('My', 0.2582092561303794),
('parents', 0.15432351476960307),
('hated', 0.7262186310977987),
('it', -0.029160655114499095),
('.', -0.002758524253450406),
('', -0.33846410359182094),
('', 0.0)],
'surprise': [('', 0.0),
('There', 0.07196110795254315),
('were', 0.1434314520711312),
('many', 0.08812238369489701),
('aspects', 0.013432396769890982),
('of', -0.07127508805657243),
('the', -0.14079766624810955),
('film', -0.16881201614906485),
('I', 0.040595668935112135),
('liked', 0.03239855530171577),
(',', -0.17676382558158257),
('but', -0.03797939330341559),
('it', -0.029191325089641736),
('was', 0.01758013584108571),
('frightening', -0.221738963726823),
('and', -0.05126920277135527),
('gross', -0.33986913466614044),
('in', -0.018180366628697),
('parts', 0.02939418603252064),
('.', 0.018080129971003226),
('My', -0.08060162218059498),
('parents', 0.04351719139081836),
('hated', -0.6919028585285265),
('it', 0.0009574844165327357),
('.', -0.059473118237873344),
('', -0.465690452620123),
('', 0.0)]}
```
The `ImageClassificationExplainer` is designed to work with all models from the Transformers library that are trained for image classification (Swin, ViT etc). It provides attributions for every pixel in that image that can be easily visualized using the explainers built in `visualize` method. Initialising an image classification is very simple, all you need a is a image classification model finetuned or trained to work with Huggingface and its feature extractor. For this example we are using `google/vit-base-patch16-224`, a Vision Transformer (ViT) model pre-trained on ImageNet-21k that predicts from 1000 possible classes. ```python from transformers import AutoFeatureExtractor, AutoModelForImageClassification from transformers_interpret import ImageClassificationExplainer from PIL import Image import requests model_name = "google/vit-base-patch16-224" model = AutoModelForImageClassification.from_pretrained(model_name) feature_extractor = AutoFeatureExtractor.from_pretrained(model_name) # With both the model and feature extractor initialized we are now able to get explanations on an image, we will use a simple image of a golden retriever. image_link = "https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fstatic.onecms.io%2Fwp-content%2Fuploads%2Fsites%2F47%2F2020%2F08%2F16%2Fgolden-retriever-177213599-2000.jpg" image = Image.open(requests.get(image_link, stream=True).raw) image_classification_explainer = ImageClassificationExplainer(model=model, feature_extractor=feature_extractor) image_attributions = image_classification_explainer( image ) print(image_attributions.shape) ``` Which will return the following list of tuples: ```python >>> torch.Size([1, 3, 224, 224]) ``` #### Visualizing Image Attributions Because we are dealing with images visualization is even more straightforward than in text models. Attrbutions can be easily visualized using the `visualize` method of the explainer. There are currently 4 supported visualization methods. - `heatmap` - a heatmap of positive and negative attributions is drawn in using the dimensions of the image. - `overlay` - the heatmap is overlayed over a grayscaled version of the original image - `masked_image` - the absolute value of attrbutions is used to create a mask over original image - `alpha_scaling` - Sets alpha channel (transparency) of each pixel to be equal to normalized attribution value. #### Heatmap ```python image_classification_explainer.visualize( method="heatmap", side_by_side=True, outlier_threshold=0.03 ) ``` #### Overlay ```python image_classification_explainer.visualize( method="overlay", side_by_side=True, outlier_threshold=0.03 ) ``` #### Masked Image ```python image_classification_explainer.visualize( method="masked_image", side_by_side=True, outlier_threshold=0.03 ) ``` #### Alpha Scaling ```python image_classification_explainer.visualize( method="alpha_scaling", side_by_side=True, outlier_threshold=0.03 ) ```
This package is still in active development and there is much more planned. For a 1.0.0 release we're aiming to have:
If you would like to make a contribution please checkout our contribution guidelines
The maintainer of this repository is @cdpierse.
If you have any questions, suggestions, or would like to make a contribution (please do 😁), feel free to get in touch at charlespierse@gmail.com
I'd also highly suggest checking out Captum if you find model explainability and interpretability interesting.
This package stands on the shoulders of the the incredible work being done by the teams at Pytorch Captum and Hugging Face and would not exist if not for the amazing job they are both doing in the fields of ML and model interpretability respectively.
All of the attributions within this package are calculated using PyTorch's explainability package [Captum](https://captum.ai/). See below for some useful links related to Captum. - [Captum Algorithm Overview](https://captum.ai/docs/algorithms) - [Bert QA Example](https://captum.ai/tutorials/Bert_SQUAD_Interpret) this an implementation acheived purely using Captum. - [API Reference](https://captum.ai/api/) - [Model Interpretability with Captum - Narine Kokhilkyan (Video)](https://www.youtube.com/watch?v=iVSIFm0UN9I)
Integrated Gradients (IG) and a variation of it Layer Integrated Gradients (LIG) are the core attribution methods on which Transformers Interpret is currently built. Below are some useful resources including the original paper and some video links explaining the inner mechanics. If you are curious about what is going on inside of Transformers Interpret I highly recommend checking out at least one of these resources. - [Axiomatic Attributions for Deep Networks](https://arxiv.org/abs/1703.01365) the original paper [2017] where Integrated Gradients was specified. - [Fiddler AI YouTube video on IG](https://www.youtube.com/watch?v=9AaDc35JYiI) - [Henry AI Labs YouTube Primer on IG](https://www.youtube.com/watch?v=MB8KYX5UzKw) - [Explaining Explanations: Axiomatic Feature Interactions for Deep Networks](http://export.arxiv.org/abs/2002.04138) more recent paper [2020] extending the work of the original paper.