Telling BERT ’s Full Story: from Local Attention to Global Aggregation (2021)

Abstract: We take a deep look into the behaviour of self-attention heads in the transformer architecture. In light of recent work discouraging the use of attention distributions for explaining a model’s behaviour, we show that attention distributions can nevertheless provide insights into the local behaviour of attention heads. This way, we propose a distinction between local patterns revealed by attention and global patterns that refer back to the input, and analyze BERT from both angles. We use gradient attribution to analyze how the output of an attention head depends on the input tokens, effectively extending the local attention-based analysis to account for the mixing of information throughout the transformer layers. We find that there is a significant mismatch between attention and attribution distributions, caused by the mixing of context inside the model. We quantify this discrepancy and observe that interestingly, there are some patterns that persist across all layers despite the mixing.

## introduction the inception of the transformer architecture has sparked significant progress across a wide range of language understanding tasks. variants of transformers currently dominate the popular glue @xcite and super-glue @xcite benchmarks and have even achieved super human performance on multiple tasks. the main innovations behind the transformer architecture are the stacking of selfattention layers into a multi-layer self-attention architecture, as well as an unsupervised pre-training phase that primes the model to be fine-tuned on a wide range of language tasks. transformers and other self-attention-based models have been successfully adopted in other areas such as computer vision @xcite , music processing @xcite or protein research @xcite . their extraordinary empirical success has led researchers to investigate transformers in order to better understand the source of this success, but also in an attempt to explain model decisions. much of the research around interpretability and explainability is focused on analyzing the selfattention operation @xcite . in multilayer self-attention, every input computes an attention distribution over itself and all other inputs to produce ever more complex feature representations. in the case of language, a word in a sentence attends to itself and to all other words in order to compute an updated contextual representation of itself. it is tempting to directly rely on attention distributions to explain the model's predictions. the rationale is that if the attention distribution aligns with human intuition, we can conclude that the model learned robust features and obtained a deep understanding of language, in contrast to simply overfitting on spurious patterns. for example, if a transformer classifies an online comment as hate speech, but we find that the model mostly attended to neutral or even positive words, we would conclude that the model did not actually understand the text and that the correct prediction was either due to chance or to the exploitation of an underlying statistical bias in the data @xcite . however, recent studies @xcite question the ability of attention maps to provide a faithful explanation of the inner workings of transformer models. in particular, when the explanations refer to the model input, attention maps do not account for the mixing of information throughout the model. since selfattention mixes information among all input tokens, the hidden layers attend over mixtures of tokens. therefore, attention maps may be useful to investigate the local behavior of attention heads but not to draw conclusions about how input tokens relate to each other. in this work we take a detailed look at the inner workings of bert's attention heads, both by analyzing the self-attention distributions, and by using gradient attribution to account for the mixing of tokens throughout the model. we first show that self-attention distributions correlate strongly with hidden token attribution @xcite ) (hta) from hidden embedding to head output, this result validates hta. we then present novel location based attention patterns, revealing that bert, despite its bi-directional language modeling objective, attends to past embeddings in earlier layers, and to future ones in later layers. next, we use hta in order to extend the analysis to take the mixing of information into account, which allows to draw conclusions about the behaviour of an attention head with respect to the original input word. the patterns that emerge are different from the local attention-based patterns, giving us deeper insight into the operation of the model and emphasizing that local attention-based explanations are very different from global attribution-based explanations. finally, we contrast attention and hta distributions for individual examples. our results further highlight the discrepancy between local attention patterns and global attribution patterns. ## related work the good performance of attention @xcite models in natural language processing (nlp) arises from their ability to learn alignments between words. the transformer architecture @xcite is a multi-layer multihead self-attention architecture that is pre-trained in an unsupervised manner. the extraordinary performance of transformer models has accelerated progress in the field of nlp. currently, there is a growing number of different transformer models that vary in size, pre-training objective and/or other architectural elements @xcite @xcite @xcite @xcite . the success of transformers and the possibility of visualizing attention distributions @xcite , has motivated a line of research aiming to understand the inner workings of transformers and explain their decisions. many of these studies have focused on bert @xcite , a wellknown transformer model, leading to a body of research grouped under the term bertology @xcite . aforementioned research builds on previous work on the interpretability of attention distributions in other models apart from transformers. in particular, @xcite examine the attention distributions of lstm based encoderdecoder models and show a weak to moderate correlation between attention and dot-product gradient attribution. furthermore, they show that adversarial attention distributions that do not change the model's decision can be constructed. in the same line, @xcite find, through zeroing out attention weights, that gradient attribution is a better predictor of feature importance with respect to the model's output than attention weights. @xcite find that although adversarial attention distributions can be easily obtained, they perform worse on a simple diagnostic task. all of these works raise concerns about the ability of attention distributions to explain the decisions of a model. despite existing concerns surrounding the interpretability of attention distributions, very few works have studied how this problem affects transformers. @xcite show that, just as in other attention models, it is possible to manipulate self-attention in transformers in order to generate different attention masks that cause only a small drop in performance. @xcite find that attention distributions are not unique when the sequence length is larger than the head dimension and show that this can lead to the discovery of spurious patterns. furthermore, they show that although it is possible to map hidden tokens back to their corresponding input tokens, there is a very large degree of information mixing inside the model, which raises questions about straightforward interpretations of attention maps. recently, @xcite proposed a method to quantify information flow inside transformers. this method tracks the mixing of information due to attention but omits the effect of feed-forward networks. our work addresses this important issue by distinguishing between local and global aggregation patterns, where the former can be explained by attention distributions and the latter by attribution. we analyze bert from both angles and quantify the mismatch between these interpretations. we show that attention correlates well with attribution locally but not globally and therefore attention maps are inadequate to draw conclusions that refer to the input of the model. ## background on transformers the original transformer architecture @xcite is a sequence-to-sequence model consisting of an encoder and a decoder, both of which follow a multi-layer multi-head self-attention structure. conversely, most of the pre-trained transformer models that can be fine-tuned on supervised language understanding tasks only consist of an encoder. each transformer layer consists of a selfattention block and a non-linear feed forward block (mlp) with layer normalizations @xcite . the input to a transformer layer is a sequence of embeddings e @xmath0, ..., e l ds ] ∈ r de×ds , where l denotes the layer index, d e is the embedding dimension, and d s is the sequence length. we refer to the sequence of non-contextual input word embeddings as e 0 , and to the hidden contextual embeddings as e l , where @xmath1. note that e 0 refers to the word embeddings after position and sequence embeddings have been added. a self-attention block consists of n h separate attention heads. the attention heads independently perform the self-attention operation, and the results are then concatenated and projected back into the embedding space by a linear layer. the output of the attention block is then fed into the mlp. the self-attention operation itself is implemented by projecting each input token e @xmath2, key vector k @xmath3. we present the selfattention operation from the perspective of a single token e i attending to all input tokens. for that, the key vectors k i are aggregated into the key matrix @xmath4, ..., k ds ] ∈ r dq×ds and the value vectors v i are aggregated into the value matrix @xmath5, ..., v ds ] ∈ r dv×ds . the attention distribution a i of token e i over all input tokens is then computed as the attention vector a @xmath6. a i is then multiplied with the value matrix v to compute the output of the self-attention operation for a token i and a head h as the outputs of all heads {o 0,i , ..., o n h ,i } ∈ r de are then concatenated and fed through a linear layer to compute the output of the self-attention block for a single token. this linear layer can be thought of as an aggregation operation that projects the output of the independent heads back into embedding space. in practice, the attention distributions for all tokens are computed in parallel. ## extending hidden token attribution hidden token attribution @xcite ) is a gradient-based attribution method that quantifies how much information from each input token is contained in a given hidden embedding. for each layer l, this method defines the relative contribution c l i,j of an input token e 0 i to a hidden embedding e l j as: the contribution c l i,j is normalized by the sum of the attribution values to all input tokens and hence, ranges between 0 and 1. in this work, we apply hidden token attribution to the individual attention heads of bert. for a token e l j at layer l we back-propagate the gradients from the output o l h,j of each attention head h independently. this differs from the original method in that hidden token attribution propagates the gradients from the layer output. in general, using equation 1, we can compute the contribution between any two vectors in the model, as long as they are connected in the computation graph. we hence denote the contribution of any vector x to another vector y as c(x, y). in particular, we calculate two different contributions to the head output: previous layer contribution: contribution from the hidden embeddings at the input of the attention head to the output of the attention head: input contribution: contribution from tokens at the input of the transformer model to the output of an attention head h at layer l: c(e 0 i , o l h,j ) previous layer contribution allows us to study how attention heads operate locally and how hta distributions compare to attention distributions. input contribution enables us to extend the head attention patterns all the way back to the input, thereby controlling for the effect of information mixing. ## setup for our experiments we use the non-finetuned, uncased bert base model @xcite as provided in the original repository. 1 despite the recent explosion of new transformer variants, bert remains the most popular model for research into the interpretability of transformer models. the reason for this is that most of the newer models are architecturally similar to bert, and therefore, studies carried out on bert either are likely to generalize to these models or can be repeated with relatively little effort. we perform our experiments on 1800 examples from the development set of the mnli matched (mnlim) dataset. brunner et al. (2020) show that when the sequence length d s is larger than the head output dimension d v , the attention distributions are not identifiable. therefore, to guarantee that in our experiments we do not find spurious patterns that do not influence downstream parts of the model, we restrict the examples in our dataset to sequences of maximum length of 64 tokens, which is the head dimension of bert. thus, the examples in our dataset have sequence lengths ranging between 6 and 64 tokens, with a median length of 34 tokens. in total, this subset contains 63,456 tokens. ## hta: local validation the ability of attention distributions to provide explanations has been the target of a number of studies @xcite @xcite . in particular, @xcite show that attention distributions do not explain the model output and do not correlate well with attribution methods. however, if we are exclusively interested in how attention heads behave locally, i.e., without considering their impact on the model's decisions, it is sound to examine attention distributions. the reason for this is that self-attention is the only operation performed in attention heads, and hence, attention distributions precisely represent the information flow within the heads. as a consequence, we can use attention distributions as a reference to validate whether hta accurately quantifies how information mixes within 1 https://github.com/google-research/bert 1 2 3 4 5 6 7 8 9 10 11 transformers. to verify this, we compare attention distributions to previous layer contribution by computing the correlation between attention maps a h,i and the contribution c(e l-1 i , o l h,j ) for each head. a high correlation value would validate hta as accurately representing the flow of information within transformers. to calculate the correlation, first, we extract the attention maps for all the heads of bert for each of the tokens in the examples of our dataset. then, we pair each attention map to the corresponding contribution. note, that both attention maps and contributions are distributions that lie in the probability simplex, i.e., all the values are between 0 and 1 and their sum is 1. next, we calculate pearson's correlation coefficient for each attention-contribution pair and we aggregate the results into one value per head by computing the mean of the correlation values. figure 1 (top) shows the mean correlation value per head. for all heads except for two, pearson's correlation coefficient is larger than 0.7. furthermore, 90% of the heads show a correlation between attention and hidden token attribution of over 0.85. similarly, we calculate spearman's rank correlation coefficient r for each head. the results, displayed in figure 1 (bottom), show that only four heads have a spearman's correlation smaller than 0.9, and that 75% of the heads have a correlation coefficient larger than 0.95. note that in any case gradient attribution is a local first order approximation and thus introduces a small error that prevents perfect correlation. these high correlation values empirically demonstrate that hta does indeed represent the flow of information within attention heads with respect to the head inputs. therefore, to study the inner workings of transformers beyond attention heads one can rely on hidden token attribution and apply it at different points of the model. now that we have validated hta, we can investigate the behavior of the heads in more detail: examining the local patterns revealed by attention, the global patterns revealed by hta, and the discrepancies between both. ## local head analysis in this section we take a closer look into the local behaviour of attention heads. here, local means that we analyze how the intermediate tokens fed into the heads are processed, as opposed to how the model input propagates. to this end, we study attention distributions, but rather than studying each individual example, we aggregate the attention distributions, thus obtaining a general picture of how each head behaves. in particular, we study how much attention is paid to tokens in each relative position with respect to the attending token. for each head, we extract the attention maps for each token. then, we define the position of the attending token in the sentence as the origin (@xmath7, thereby generating a histogram where the horizontal axis represents the position of the neighbours and the vertical axis the amount of attention paid to a token. we sum the histograms of all tokens and then normalize the result. to normalize, we divide the value of attention at each position by the number of times that a token is at that relative position; given that the median length of the examples is 36, this normalization ensures that distant positions are not penalized for having fewer occurrences. figure 2 presents the histograms for the heads in layers 2, 5 and 10, the other layers can be found in appendix a. from these histograms, a clear pattern is observable. in the first layers, heads tend to aggregate more information from past tokens than from future tokens. in fact, the attention of heads 2, 5 and 7 in layer 2 to future tokens is negligible. however, this trend quickly reverses with increasing depth, and in later layers the aggregation of future hidden embeddings dominates for most heads. to illustrate this, we calculate the center of mass of the attention histograms per layer by 1 2 3 4 5 6 7 8 9 10 11 12 -30 -15 0 15 30 layer center of mass position english german arabic figure 4: mean center of mass for attention histograms per layer for english, german and arabic. the figure shows that bert follows the same trend regardless of the language, i.e., the models first attend to past and then to future hidden tokens. this suggests that despite its bidirectional training, bert tends to handle language like humans, from left to right. this is also inline with the sequential nature of language, i.e., the past context needs to be known to understand the future context. ## global head analysis although attention maps are an effective tool to understand the local behavior of attention heads, drawing conclusions that refer to the input words can be misleading. transformers are complex models that mix information from the entire input sequence at each layer. recent work @xcite has raised concerns about the interpretability of attention maps as representative of global context aggregation. in this section, we look into the individual heads and study what we call global patterns, i.e., aggregation patterns that refer to the model's input. to this end, we follow the same procedure we use in the previous section, but to generate input contribution c(e 0 i , o l h,j ) histograms instead of attention histograms. in figure 3 we show the histograms for layers 2, 5 and 10, i.e., the same layers as in figure 2 . the histograms for the whole model can be found in appendix b. furthermore, we calculate the center of mass per layer and compare them to the attention centers of mass in figure 5 . the histograms and the centers of mass show that 1 2 3 4 5 6 7 8 9 10 11 the global pattern of context aggregation is much more uniform than shown by the attention maps, especially after layer 4. this is intuitive: given that in the first layers the heads are attending mostly to the past context, on average, all the hidden tokens have a larger amount of past context. therefore, when in later layers the attention shifts to the future hidden tokens, the past context already contained in these tokens balances the contribution, resulting in a uniform pattern of global context aggregation. the difference in the patterns revealed by this global analysis and the local head analysis from the previous section shows a strong mismatch between attention distributions and global context aggregation in attention heads. in fact, local attention patterns can easily lead to spurious conclusions when used to interpret global context aggregation. next, we study this difference quantitatively. ## local attention vs. global attribution to quantify the discrepancy between attention distributions and input contribution, i.e., local and global patterns of context aggregation, we calculate the correlation between attention maps and input contribution c(e 0 i , o l h,j ). we follow the same methodology as in section 6 and report pearson's and spearman's correlation coefficient in figure 6 . in line with the mismatch between attention and contribution histograms (figures 2 and 3 ), we observe how the correlation between attention and input contribution quickly decreases in deeper layers. particularly, after only four layers pearson's correlation coefficient for most heads is smaller than 0.5 and in the last four layers the median head correlation value is smaller than 0.25. furthermore, spearman's correlation follows a very similar trend, with the median head correlation value falling un1 2 3 4 5 6 7 8 9 10 11 der 0.7 already at layer 3, and under 0.25 at the last layer. the results from this section point at the importance of information mixing: attention maps show how the heads behave locally, i.e., how they aggregate context, but not what context is in fact aggregated. knowing how the heads behave locally can give us a better understanding of transformer models that could be leveraged to further improve the performance of these models @xcite . however, attention maps are misleading when drawing conclusions about what input words are being aggregated into the contextual embeddings. ## conclusion we provide justification for using hta to study information flow within transformers. by studying attention distributions of bert we uncover an interesting pattern: in earlier layers, attention heads attend mostly to earlier tokens, whereas this trend quickly reverses with increasing depth. this is surprising, since bert is trained using bi-directional language modeling and it suggests that like humans, bert understands language from left to right. a problem with local attention patterns is that they do not reveal how the attention heads process the information contained in the input tokens. we thus use hidden token attribution to compute perhead attribution distributions over the input words. our results show that the mismatch between attention and attribution distributions increases with depth. this confirms the importance of accounting for information mixing when analyzing attention heads with respect to the input tokens. finally, we show how five different attention head patterns differ from their token attribution equivalents. our method and results are complementary to those in @xcite , we believe a combination of attention flow and hta may provide new interesting insights. in this work, we aim to set a clear border that distinguishes between local and global aggregation in transformer models. this distinction is important when trying to interpret the behavior of these models, and we hope that it will help future studies in their analyses. furthermore, our findings add new insights to the growing field of research on explaining transformers. this research, in turn, can help in guiding design decisions leading to further improvements of natural language processing architectures. c comparison of local vs. global head patterns attn l 0 h 0 hta l0 h0 attn l 0 h 1 hta l0 h1 attn l 0 h 2 hta l0 h2 attn l 0 h 3 hta l0 h3 attn l 0 h 4 hta l0 h4 attn l 0 h 5 hta l0 h5 attn l 0 h 6 hta l0 h6 attn l 0 h 7 hta l0 h7 attn l 0 h 8 hta l0 h8 attn l 0 h 9 hta l0 h9 attn l 0 h 10 hta l0 h10 attn l 0 h 11 hta l0 h11 attn l 1 h 0 hta l1 h0 attn l 1 h 1 hta l1 h1 attn l 1 h 2 hta l1 h2 attn l 1 h 3 hta l1 h3 attn l 1 h 4 hta l1 h4 attn l 1 h 5 hta l1 h5 attn l 1 h 6 hta l1 h6 attn l 1 h 7 hta l1 h7 attn l 1 h 8 hta l1 h8 attn l 1 h 9 hta l1 h9 attn l 1 h 10 hta l1 h10 attn l 1 h 11 hta l1 h11 attn l 3 h 0 hta l3 h0 attn l 3 h 1 hta l3 h1 attn l 3 h 2 hta l3 h2 attn l 3 h 3 hta l3 h3 attn l 3 h 4 hta l3 h4 attn l 3 h 5 hta l3 h5 attn l 3 h 6 hta l3 h6 attn l 3 h 7 hta l3 h7 attn l 3 h 8 hta l3 h8 attn l 3 h 9 hta l3 h9 attn l 3 h 10 hta l3 h10 attn l 3 h 11 hta l3 h11 attn l 5 h 0 hta l5 h0 attn l 5 h 1 hta l5 h1 attn l 5 h 2 hta l5 h2 attn l 5 h 3 hta l5 h3 attn l 5 h 4 hta l5 h4 attn l 5 h 5 hta l5 h5 attn l 5 h 6 hta l5 h6 attn l 5 h 7 hta l5 h7 attn l 5 h 8 hta l5 h8 attn l 5 h 9 hta l5 h9 attn l 5 h 10 hta l5 h10 attn l 5 h 11 hta l5 h11 attn l 7 h 0 hta l7 h0 attn l 7 h 1 hta l7 h1 attn l 7 h 2 hta l7 h2 attn l 7 h 3 hta l7 h3 attn l 7 h 4 hta l7 h4 attn l 7 h 5 hta l7 h5 attn l 7 h 6 hta l7 h6 attn l 7 h 7 hta l7 h7 attn l 7 h 8 hta l7 h8 attn l 7 h 9 hta l7 h9 attn l 7 h 10 hta l7 h10 attn l 7 h 11 hta l7 h11 figure 19: layer 8: rows 1 and 3 represent attention maps, rows 2 and 4 show the corresponding contribution maps. 123 attn l 8 h 0 hta l8 h0 attn l 8 h 1 hta l8 h1 attn l 8 h 2 hta l8 h2 attn l 8 h 3 hta l8 h3 attn l 8 h 4 hta l8 h4 attn l 8 h 5 hta l8 h5 attn l 8 h 6 hta l8 h6 attn l 8 h 7 hta l8 h7 attn l 8 h 8 hta l8 h8 attn l 8 h 9 hta l8 h9 attn l 8 h 10 hta l8 h10 attn l 8 h 11 hta l8 h11 attn l 9 h 0 hta l9 h0 attn l 9 h 1 hta l9 h1 attn l 9 h 2 hta l9 h2 attn l 9 h 3 hta l9 h3 attn l 9 h 4 hta l9 h4 attn l 9 h 5 hta l9 h5 attn l 9 h 6 hta l9 h6 attn l 9 h 7 hta l9 h7 attn l 9 h 8 hta l9 h8 attn l 9 h 9 hta l9 h9 attn l 9 h 10 hta l9 h10 attn l 9 h 11 hta l9 h11 attn l 11 h 0 hta l11 h0 attn l 11 h 1 hta l11 h1 attn l 11 h 2 hta l11 h2 attn l 11 h 3 hta l11 h3 attn l 11 h 4 hta l11 h4 attn l 11 h 5 hta l11 h5 attn l 11 h 6 hta l11 h6 attn l 11 h 7 hta l11 h7 attn l 11 h 8 hta l11 h8 attn l 11 h 9 hta l11 h9 attn l 11 h 10 hta l11 h10 attn l 11 h 11 hta l11 h11 figure 23: layer 12: rows 1 and 3 represent attention maps, rows 2 and 4 show the corresponding contribution maps.