AI Logic

Explainability (XAI)

Attention Rollout

Updated:

Diagram of Attention Rollout. The left side shows the flow of a Transformer encoder (input tokens, embedding, L layers of self-attention with a residual connection and FFN with a residual connection, the CLS of the last layer, classifier). The right side shows an example with 5 tokens and 3 layers: the residual is added to the raw attention, the layers are multiplied together, and the CLS row is taken out; unlike the nearly uniform raw attention of layer 3, the subject key receives the largest value

What is Attention Rollout?

Attention Rollout is a method that approximates how much the output of a Transformer attends to each input token by multiplying the attention weights of all layers together, from the input up to the top layer. Abnar and Zuidema proposed it in 2020, together with a second method, Attention Flow.

The self-attention of a Transformer mixes in information from other tokens with every layer. As a result, the attention weights of higher layers are attention over "already mixed embeddings" rather than over "input tokens", and they are unreliable as an explanation of which input words mattered. In fact, in the model studied in the paper, the raw attention weights above layer 3 were nearly uniform.

Attention Rollout treats the attention weights of each layer as "the fraction of information carried up from the layer below", adds the residual connections, and multiplies the per-layer matrices together. This estimates, from the attention weights alone, how much information the top-layer embeddings received from each input token. The computation consists only of matrix multiplications and requires no backpropagation. The ViT paper also uses it to draw maps of attention from the output token to the input image.

Think of a game of telephone. Raw attention only tells how much each person heard from their neighbors. Attention Rollout traces this back to the first person and multiplies the fractions together, estimating "how much of the last person's story comes from each of the first people".

Computation steps

The explanation follows the equations in Section 3 of Abnar and Zuidema (2020), who proposed the method. Let LL be the number of Transformer layers and WattW_{\mathrm{att}} the attention matrix of layer ll (rows are the attending positions, columns are the attended positions).

  1. Run the input through the forward pass and extract the attention weights of each layer. For multi-head attention, average over the heads in each layer, as in the paper's analysis.
  2. To account for the residual connections, add the identity matrix to the attention matrix and renormalize, giving A=0.5 Watt+0.5 IA = 0.5\,W_{\mathrm{att}} + 0.5\,I.
  3. Starting from layer 1, multiply the attention matrices together (Eq. 1).
  4. From the top-layer A~\tilde{A}, take the row of the position of interest (the [CLS] token for classification). This approximates the attention to each input token.

The residual connections are added for the following reason. When an attention layer has a residual connection, the values of the next layer are Vl+1=Vl+WattVl=(Watt+I) VlV_{l+1} = V_l + W_{\mathrm{att}} V_l = (W_{\mathrm{att}} + I)\, V_l. Looking at the information flow through attention weights alone misses this path, which strongly links each position to itself.

A=0.5 Watt+0.5 IA = 0.5\,W_{\mathrm{att}} + 0.5\,I

If the attention weights are treated as the weights of edges connecting nodes in adjacent layers (the fraction of information carried), the information carried along one path is the product of its edge weights, and the information carried between two nodes is the sum over all paths. Written in matrix form, the attention from layer lil_i to layer ljl_j (j<ij < i) is obtained by repeating the following multiplication. To obtain the attention down to the input, set j=0j = 0.

A~(li)={A(li) A~(li−1)(i>j)A(li)(i=j)(1)\tilde{A}(l_i) = \begin{cases} A(l_i)\, \tilde{A}(l_{i-1}) & (i > j) \\ A(l_i) & (i = j) \end{cases} \qquad (1)

The right side of the top figure is an example with 3 layers and 5 tokens: 4 words of "the key to the cabinets" plus [CLS]. The raw attention of layer 1 concentrates on the subject "key", while layers 2 and 3 are nearly uniform. The [CLS] row of the raw attention in layer 3 is 0.20 for every token and reveals nothing. In the [CLS] row of the multiplied rollout, "key" is the largest, showing that the information gathered in layer 1 is carried up to the higher layers.

The amount of computation is O(d⋅n2)O(d \cdot n^2), where dd is the depth and nn is the number of tokens.

Difference from Attention Flow

Alongside Attention Rollout, the paper proposes a second method, Attention Flow. Both use a graph whose edge weights are the attention weights (a directed graph whose nodes are the input tokens and the embeddings of each layer), and both add the residual connections in the same way. They differ in how they interpret the attention weights.

AspectAttention RolloutAttention Flow
Interpretation of attention weightsFraction of information carriedUpper bound on the amount that can be carried (capacity)
Weight of a single pathProduct of the edge weightsMinimum of the edge weights
How it is computedMultiply the matrices together (Eq. 1)Compute the maximum flow from the upper layer to the input with a max-flow algorithm
Amount of computationO(d⋅n2)O(d \cdot n^2)O(d2⋅n4)O(d^2 \cdot n^4)
Resulting attentionSharply concentrated on a few tokensSpread over the set of important tokens, with smaller differences

The paper explains that Rollout makes the strict assumption that information is carried only in proportion to the attention, while Flow makes the looser assumption that capacity is used as fully as possible. Because many simplifications are involved, Rollout's strictness does not necessarily translate into accuracy, and in the paper's experiments Flow gave somewhat more reliable results.

Experiments in the paper

The paper studies the task of predicting whether the verb of a sentence is singular or plural (subject-verb agreement, the dataset of Linzen et al. 2016). For example, for the verb following "the key to the cabinets", attending to "key" predicts the singular correctly, while "cabinets" is a misleading cue. The model is a Transformer encoder with 6 layers, 8 heads, and embedding dimension 128, built from GPT-2 blocks without masking. As in BERT, a [CLS] token is placed at the front, and its last-layer embedding is fed to the classifier. The accuracy is 0.96.

For evaluation, the [CLS] attention of each method was compared with token importance obtained by other methods, using Spearman's rank correlation. The other methods are blank-out, which replaces tokens one at a time with the unknown-word symbol and measures how much the probability of the correct class drops, and input gradients. The results on 2000 test examples (mean ± standard deviation) are as follows.

Correlation with blank-outLayer 1Layer 2Layer 3Layer 4Layer 5Layer 6
Raw attention0.69±0.270.10±0.43−0.11±0.49−0.09±0.520.20±0.450.29±0.39
Attention Rollout0.32±0.260.38±0.270.51±0.260.62±0.260.70±0.250.71±0.24
Attention Flow0.32±0.260.44±0.290.70±0.250.70±0.220.71±0.220.70±0.22
Correlation with input gradientsLayer 1Layer 2Layer 3Layer 4Layer 5Layer 6
Raw attention0.53±0.330.16±0.38−0.06±0.420.00±0.470.24±0.400.46±0.35
Attention Rollout0.22±0.310.27±0.320.39±0.320.47±0.320.53±0.320.54±0.31
Attention Flow0.22±0.310.31±0.340.54±0.320.61±0.280.60±0.280.61±0.28

Raw attention has low correlation except in layer 1, whereas Rollout and Flow correlate more strongly in higher layers. In layer 1, Rollout and Flow only add the residual connection to the raw attention, so the two give the same values.

The paper also examines DistilBERT fine-tuned for sentiment analysis on SST-2. The correlation with input gradients is quite low for every method, around 0.08–0.14, but Rollout and Flow slightly outperform raw attention.

Caveats in practice

Attention Rollout approximates the information flow from the attention weights alone and relies on many simplifications.

  • It ignores paths other than the attention weights: transformations inside the FFN are not considered. It also assumes that the residual connection mixes in with the same weight, 0.5, as the attention.
  • It averages the heads: the paper's analysis averages the heads in each layer. Heads can be examined one at a time, but then the mixing of information across heads in the FFN must be taken into account.
  • It does not distinguish output classes: the attention weights do not depend on the predicted class, so it cannot show separately "evidence for which class".

Keep the following points in mind as well.

  • Decoders need a correction: the paper's analysis concerns encoders without masking. In decoders, which hide future tokens, attention tends to concentrate on earlier tokens, and Rollout is also biased toward them. The paper recommends normalizing over the range that attention can reach before using it.
  • An explanation, not a proof: citing earlier work arguing that equating attention weights with explanations is a mistake, the paper positions Rollout as a tool that converts attention weights into attention over the input tokens.

Comparison with other explanation methods

The table compares Attention Rollout with methods commonly used to explain Transformers, from the same viewpoints.

MethodWhat it usesMixing across layersPer-class distinctionAmount of computation
Raw attention weightsAttention matrix of one layerNot consideredNot possible1 forward pass
Attention RolloutProduct of the attention matrices of all layers (with residual connections added)ConsideredNot possible1 forward pass and matrix products
Attention FlowMaximum flow with the attention of all layers as capacitiesConsideredNot possible1 forward pass and a max-flow computation (heavy)
Gradient saliency map, Integrated GradientsGradient of the output with respect to the inputConsidered (differentiates the whole model)Possible1 to several hundred backward passes

Rough guidelines for choosing:

  • To get a quick, rough look at where a Transformer is looking in the input: use Attention Rollout. As long as the attention weights can be extracted, it needs only matrix multiplications.
  • To see the set of important tokens in a more reliable form: use Attention Flow. However, the computation becomes heavy when there are many tokens.
  • To get evidence for each predicted class: use a gradient-based method.

PyTorch example

Show code
python
import torch
import torch.nn as nn

'''
Compute Attention Rollout from the attention weights of each layer of a Transformer encoder
(Abnar & Zuidema 2020: A = 0.5 W_att + 0.5 I, Ã(l) = A(l) Ã(l-1))
'''


def attention_rollout(attentions):
  # attentions: list of per-layer attention weights [B, n, n] (heads already averaged; row = attending side)
  n = attentions[0].size(-1)
  eye = torch.eye(n, device=attentions[0].device)
  rollout = None
  for w in attentions:                                 # starting from layer 1
    a = 0.5 * w + 0.5 * eye                            # step 2: add the residual connection
    a = a / a.sum(dim=-1, keepdim=True)                # renormalize so each row sums to 1
    rollout = a if rollout is None else a @ rollout    # step 3 (Eq. 1)
  return rollout                                       # [B, n, n]


class EncoderLayer(nn.Module):
  def __init__(self, d_model=128, n_heads=8):
    super().__init__()
    self.norm1 = nn.LayerNorm(d_model)
    self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True)
    self.norm2 = nn.LayerNorm(d_model)
    self.ffn = nn.Sequential(nn.Linear(d_model, 4 * d_model), nn.GELU(), nn.Linear(4 * d_model, d_model))

  def forward(self, x):
    h = self.norm1(x)
    # average_attn_weights=True returns the weights averaged over heads [B, n, n] (step 1)
    out, w = self.attn(h, h, h, need_weights=True, average_attn_weights=True)
    x = x + out                      # self-attention + residual connection
    x = x + self.ffn(self.norm2(x))  # FFN + residual connection
    return x, w


torch.manual_seed(0)
layers = nn.ModuleList([EncoderLayer() for _ in range(6)])
layers.eval()  # disable Dropout
x = torch.randn(1, 5, 128)          # example: embeddings of [CLS] and 4 tokens
attentions = []
with torch.no_grad():               # no backpropagation needed
  for layer in layers:
    x, w = layer(x)
    attentions.append(w)
rollout = attention_rollout(attentions)
cls_to_tokens = rollout[0, 0]       # step 4: [CLS] row = attention to each input token
print(cls_to_tokens, cls_to_tokens.sum())  # the row sums to 1

FAQ

Q. Why shouldn't raw attention weights be used as they are?
A.

Because attention in higher layers is attention not over the input tokens but over embeddings that already contain information mixed in from other tokens. In the paper's model, raw attention above layer 3 became nearly uniform, and its correlation with token importance obtained by blank-out was low except in layer 1 (−0.11 to 0.29 in layers 2–6).

Q. Can it be used with ViT?
A.

Yes. The ViT paper, which splits an image into small regions (patches) and treats them as tokens, uses Attention Rollout to draw maps of attention from the output token to the input image. It averages the attention weights of ViT-L/16 over all heads and multiplies the matrices of all layers in sequence.

Q. Why is the weight of the residual connection 0.5?
A.

The output of an attention layer is Vl+1=(Watt+I) VlV_{l+1} = (W_{\mathrm{att}} + I)\, V_l, so adding the identity matrix to the attention matrix and renormalizing each row to sum to 1 gives A=0.5 Watt+0.5 IA = 0.5\,W_{\mathrm{att}} + 0.5\,I. Each row of the attention matrix already sums to 1, so each row of Watt+IW_{\mathrm{att}} + I sums to 2, which is divided by 2.

References

  1. S. Abnar and W. Zuidema, "Quantifying Attention Flow in Transformers," Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics (ACL), pp. 4190–4197, 2020(arXiv:2005.00928).
  2. A. Dosovitskiy et al., "An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale," arXiv:2010.11929, 2020.