{'fraction_non_alphanumeric': 0.03242489656413024, 'fraction_numerical': 0.007375427235114229, 'mean_word_length': 5.059128065395095, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 0, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
AttViz: Online exploration of self-attention for transparent neural language modeling

Neural language models are becoming the prevailing methodology for the tasks of query answering, text classification, disambiguation, completion and translation. Commonly comprised of hundreds of millions of parameters, these neural network models offer state-of-the-art performance at the cost of interpretability; humans are no longer capable of tracing and understanding how decisions are being made. The attention mechanism, introduced initially for the task of translation, has been successfully adopted for other language-related tasks. We propose AttViz, an online toolkit for exploration of self-attention---real values associated with individual text tokens. We show how existing deep learning pipelines can produce outputs suitable for AttViz, offering novel visualizations of the attention heads and their aggregations with minimal effort, online. We show on examples of news segments how the proposed system can be used to inspect and potentially better understand what a model has learned (or emphasized).


Introduction
Contemporary machine learning that addresses text-related tasks adheres to the use of large language models-deep neural network architectures that have gone through extensive unsupervised pre-training in order to capture context-dependent meaning of individual tokens (Devlin et al., 2019;Liu et al., 2019;Yang et al., 2019). Even though pre-training of such multi-million parameter neural networks can be expensive (Radford et al., 2019), many pre-trained models have been made freely available to the wider research community, unveiling the opportunity for the exploration of how, and why such large models perform well. One of the main problems with neural language models is their interpretability. Even though the models learn the task well (even at super-human levels), understanding the reasons for predictions and inspection of whether the models picked up irrelevant biases or spurious correlations can be a non-trivial task.
Approaches to understanding black-box (non-interpretable) neural network models often resort to post-hoc approximations, e.g., SHAP (Lundberg and , and similar are not necessary internal to the model itself. A potential way of extracting the token relevance is the attention mechanism (Bahdanau et al., 2014;Luong et al., 2015). The attention mechanism learns token pair-value mappings, potentially encoding relations between token pairs. When inspected as self-relations, the attention of a token w.r.t. itself (the diagonal element of the token attention matrix) potentially offers some insight into the importance of that token. Similar findings were also recently discussed when considering tabular data (Arik and Pfister, 2019). However, analytically, as well as numerically, exploration of attention can be a cumbersome task, resulting in the rise of approaches aimed at attention visualization. Visualization of (latent) embedding spaces is becoming ubiquitous in contemporary machine learning. For example, the Google's Embedding Projector 1 has offered numerous visualizations for non-savvy users, making embedding projections to low dimensional (human-understandable) vector spaces simple and available online. Even though visualization of simple embedding spaces is already accessible, visualization of complex neural network models' interior representations distributed across multiple embeddings (e.g., attention vectors), however, can be a challenging task. The works of (Liu et al., 2018a) and (Yanagimto et al., 2018) are examples of attempts at unveiling the workings of black-box attention layers and offering an interface for human researches to learn and inspect their models. (Liu et al., 2018a) visualize , as well as offer possible coloring of the attention space. Further, (Yanagimto et al., 2018) visualized self-attention with examples in sentiment analysis. The main contributions of AttViz are multi-fold, and can be stated as follows. AttViz focuses exclusively on self-attention and introduces two novel ways of visualizing this property while being available online and accessible to a wider audience. AttViz can interactively aggregate the attention vectors and offers simultaneous exploration of the output probability space, as well as the attention space.
The remainder of this work is structured as follows. In Section 2, we discuss the works, related to the proposed AttViz approach. In Section 3, we present the key ideas and technical implementation of AttViz, followed by our use case -a study of news segments in Section 5. Finally, we discuss (in Section 6) the overall capabilities of AttViz.

Attention visualization
Visualization of the attention mechanism for text has recently emerged as an active research area due to an increased popularity of attention based methods in natural language processing. Recent deep neural network language models such as BERT (Devlin et al., 2019), XLNet (Yang et al., 2019), and RoBERTa (Liu et al., 2019) are comprised of multiple attention heads-separate weight spaces each associated with the input sequence in a unique way. Language models consist of multiple attention matrices, all contributing to the final prediction. Visualising the attention weights from each of attention matrix is thus an important component in understanding and interpreting these models.
The attention mechanism which originated in the work on neural machine translation lends itself naturally to visualisation. (Bahdanau et al., 2014) used heat maps to display the attention weights between input and output text. This visualisation technique was first applied to the task of translation but found use in many other tasks such as visualising an input sentence and output summarization (Rush et al., 2015) and visualizing an input document and textual entailment hypothesis (Rocktäschel et al., 2015). In these heat map visualisations, a matrix or a vector is used to represent the learned alignments and color intensity illustrates attention weights. This provides a summary of the attention patterns describing how they map the input to the output. For classification tasks, a similar visualisation approach can be used to display the attention weights between the classified document and the predicted label (Yang et al., 2016;Tsaptsinos, 2017). Here, the visualisation of attention often displays the input document with the attention weights superimposed onto individual words. The superimposed attention weights are represented similarly to heat map visualisations using a color saturation to encode attention value.
An alternative visual encoding of attention weights is a bipartite graph visualisation. Here attention weights are represented by edge weights or thickness between two lists of words. This technique has been used to help interpret model output in neural machine translation , in natural language inference (Liu et al., 2018b), and for model debugging (Strobelt et al., 2018). A version of this visualisation which was designed specifically for multi-head self-attention (Vaswani et al., 2017) uses color hue to encode the attention head associated with each weight. The color is applied to the edges and is superimposed as a color strip over the node words. The intensity of the colors in the strips at each word position summarises the distribution of attention weight for that word across the heads. This multi-head self visualisation technique was recently extended (Vig, 2019) with two visualisations. The first, called "Model View", is a visualisation of the bipartite graphs for each layer and head in the system. The second visualization, "Neuron View", drills down to the computation of the attention score associated with each weighed edge in the bipartite graph. The element wise product, dot product, and softmax values are all visualised using coloured elements with saturation representing the magnitude of the value. This visualisation provides some insight into how each attention weight was computed while still providing the overview of attention weights.
The purpose of the proposed AttViz is to unveil the attention layer space to human explorers in an intuitive manner. The tool emphasizes self-attention, that is, the diagonal of the token-token attention matrix which possibly corresponds to relevance of individual tokens. By making use of alternative encoding techniques, the attention weights across the layers and heads can be explored dynamically to investigate the interactions between the model and the input data. The proposed AttViz differentiates from existing visualization tools as follows. The focus of the tool is, as stated, self-attention, implying visualization of (attention-annotated) input token sequences can be carried out directly. We developed a novel visualization technique, where self-attention values are on per-token basis visualized across the input sequence for each self-attention vector. Further, AttViz offers visualization of the distribution of the attention values across the token sequence along with relevant aggregations, such as the min/max and similar. Finally, the tool simultaneously shows both the prediction probabilities, making interpretation of the self-attention space even more transparent, and with it the information on potential alternative classifications.
3 AttViz: An online toolkit for visualization of self-attention We built AttViz, an online solution that can be coupled with existing language models from the PyTorchtransformers library 2 -one of the most widely used resources for language modeling. The idea behind AttViz is that it is lightweight, as it does not offer (online) neural model training, but facilitates the exploration of trained models. Along with AttViz, we provide a set of Python scripts that take as an input a trained neural language model and output a JSON file to be used by AttViz visualisation tool. A common pipeline for using AttViz is as follows. First, a transformer-based trained neural network model is used to obtain predictions on a desired set of instances (texts). The predictions are converted into the JSON format, suitable for AttViz, along with the attention space of the language model. The JSON file is loaded into AttViz (on the user's machine client side), where its visualization and exploration is possible. We next discuss the proposed visualization of the self-attention.

Visualization of self-attention
In this section, we discuss the proposed visualization schemes that emphasize different aspects of selfattention. The initial AttViz view offers sequence-level visualization, where each (byte-pair encoded) token is equipped with a self-attention value based on a given attention head (see Figure 1; central text space). Following the first row that represents the input text, consequent rows correspond to attention values that represent the importance of a given token with respect to a given attention head. As discussed in the empirical part of this paper (Section 5), the rationale for this display is that commonly, only a certain number of attention heads are activated (colored fields), thus visualization must entail both the whole attention space, as well as emphasize individual heads (and tokens).
The same document can also be viewed in the "aggregation" mode ( Figure 2), where the attention sequence is shown across the token space. The user can interactively explore how the self-attention varies for individual input tokens, by changing both the scale, as well as the type of the aggregation used, the visualization can be used to emphasize various aspects of the self-attention space.
The second developed visualization (Figure 2) is the overall distribution of attention values across the whole token space. Resembling a time series, for each consequent token, the attention values are plotted separately. This visualization offers an insight into self-attention peaks, i.e. parts of the attention space focused around certain tokens that potentially impact the performance and the decision making process of a given neural network. This view also emphasizes different aggregations of the attention vector space for a single token (e.g., mean, entropy, and maximum). The visualization, apart from the mean selfattention (per token), also offers the information on maximum and minimum attention values (red dots), as well as the remainder of the self-attention values (gray dots). The user can this way explore both the self-attention peaks, as well as the overall spread.

Aggregation of self-attention
We apply several aggregation schemes across the space of individual tokens. Consider a matrix A ∈ R h×t , where h is the number of attention vectors and t the number of tokens. We consider various aggregations across the second dimension of the attention matrix A (index j). In entropy based calculation, we denote with P ij the probability of observing A ij in the j-th column. The m j corresponds to the number of unique values in that column. The proposed schemes are summarized in Table 1. The   Table 1: Aggregation schemes used in AttViz.
Aggregate name Definition Mean(j) (mean) attention aggregates can also be visualized as part of the aggregate view (Figure 2), where, for example, the mean attention is plotted as a line along with the attention space for each token, depicting the dispersion around certain parts of the input text.

Comparison with state-of-the-art
In the following section we discuss in more detail the similarities and differences of AttViz with other state-of-the-art visualization approaches. Comparisons are summarized in  (Wolf et al., 2019) token-to-token attention The main novelties introduced as part of AttViz are the capability to aggregate the attention vectors with four different aggregation schemes, offering insights both into the average attention but also its dispersity around a given token. The neat-vision project is the closest to AttViz's functionality, with the following differences. It is not directly bound to PyTorch transformers library, requiring additional pre-processing on the user-side. Similarly, the fast switching between the sequence and aggregate view are more emphasized in AttViz, as they offer more general overview of the attention space. The class probabilities are to our knowledge available in both tools, offering simultaneous exploration of both input and output space at the same time.

Example usage: News visualization
In this section, we present a step-by-step use of the server along with potential insights the user can obtain. The examples are based on the BBC news data set 4 (Greene and Cunningham, 2006) that contains 2,225 news articles on five different topics (business, entertainment, politics, sport, tech). The documents Figure 1: Visualization of aggregations. The document was classified as a politics-related topic, it can be observed that aggregations emphasize tokens such as "development","uk" and "poorer". The user can also highlight desired head information -in this example the maximum attention (purple) is highlighted. from the dataset were split into short segments. The splits allow easier training (manageable sequence lengths), as well as easier inspection of the models. We split the dataset into 60% of the documents that were used to train a BERT-base (Devlin et al., 2019) model, 20% for validation and 20% for testing 5 .
The fine-tuning of the BERT model was conducted as discussed in the examples of the PyTorch-Transformers library (Wolf et al., 2019). The best-performing hyper parameter combination was using Figure 3: Visualization of all attention heads. The sixth heads's self attention is also used to highlight the text. The document was classified as a business-related, which can be linked to high self attention at the "trillion" and "uk" tokens. Note also that, compared to the first two examples (Figures 1 and 2), the network is less certain -the business and politics classes were predicted with similar probabilities (orange and red parts of the bar above visualized text).
3 epochs with the sequence length of 512 (other hyper parameters were left at their default values). We used Nvidia Tesla V100 GPU processor for fine-tuning. While more recent larger language models such as e.g., XLNet (Yang et al., 2019) could produce better accuracy, the idea and the use of AttViz visualizations is the same; hence, we selected the most commonly used model (BERT-base).
The main user interface of AttViz is displayed in Figures 1 and 2 and 3. In the first example (Figure 1), the user can observe the main view that consists of two parts. The leftmost part shows (by id) individual self-attention vectors, along with visualization, aggregation and file selection options. The file selection indexes all examples contained in the input (JSON) file. Attention vectors can be colored with custom colors, as shown in the central (token-value view). The user can observe that, for example, the violet attention head (no. 5) is active, and emphasizes tokens such as "servants" (from civil servants), which indicates a politics-related topic (as correctly classified). Here, the token (byte-pair encoded) space is shown along with self-attention values for each token. The attention vectors are shown below the token space and aligned for direct inspection (and correspondence). Further, the upmost visualization in the right part of the view shows probabilities (obtained via softmax normalization of the output layer weights) of the considered document belonging to a given class. This functionality was added to help human explorers investigate the correspondence between the actual classification and the classified text. Using "Details" section below the probability legend, the distributions across the class space can be further inspected.
In Figure 2, the user can observe the same text segment as an attention series spanning the input token space. Again, note that tokens, such as "trillion" and "uk" correspond to high values in a subset of the attention heads, indicating their potential importance for the obtained classification. However, we observed that only a few attention heads "activate" with respect to individual tokens, indicating that other attention heads are not focusing on the tokens themselves, but possibly on relations between them. This is possible and the attention matrices contain such information, yet the study of token relations is not the focus of this work (see (Vig, 2019) for such a visualization). In this work we focus on self-attention as such information can be directly mapped across token sequences, emphasizing tokens that are of relevance to the classification task at hand. Consequently, we see AttViz as being the most useful when exploring models used for classification of hatespeech or similar news texts, where individual tokens carry key information for classification.
In the example in Figure 3, we visualize a short segment related to uk homes and spending. Note that the text is shown after the preprocessing consisting of byte-pair encoding and lower-casing.
The segment was correctly classified as business-related. Tokens, such as "trillion", "uk" and "total" are all associated with high attention. The example shows how different attention heads detect different aspects of the sentence, even at the single token (self-attention) level. The user can observe that the next most probable category for this topic was politics (red color), which is indeed a more sensible classification than e.g., sports. The example shows how interpretation of the attention can be coupled with the model's output for increased interpretability.
A careful inspection of the remainder of the documents revealed that in the majority of cases, the first token is also emphasized. We believe the following reasons can induce this observed bias. First, as the BERT-base model was used for the classification task, the model was only fine-tuned on the news data set (for a few epochs), after being extensively pre-trained on vast amounts of text. The pre-training phase could introduce the bias, as the model is implicitly forced to learn to predict the next token, indicating that the first token in the classified segment will be of high "relevance". In the second interpretation, when the first token is a content work, it can already carry a lot of meaning for the whole sentence, thus it could be reasonably relevant for the task.

Critical overview of AttViz and Conclusions
As AttViz is an online toolkit for facilitated attention exploration, we discuss possible concerns regarding its usefulness. One of the main issues with online methods is privacy. Currently, AttViz does not employ any anonymization strategies, meaning that private processing of the input data is not guaranteed. We believe that this issue can be addressed as a part of further work or with a private installation of the tool. Further, AttViz leverages users' computing capabilities, meaning that too large data sets can cause memory overheads (e.g., several millions of examples). We believe that such situations are difficult to address with AttViz, however, instances can be filtered prior to being used in AttViz. This would enable seamless exploration of a subset of the data (e.g., only (in)correctly predicted instances, or certain time slot of instances). In terms of functionality, AttViz is focused on the exploration of self-attention. We realize that the self-attention is not necessarily the only important aspect of a neural network that needs to be inspected, but it is possibly the one, where visualisation techniques have been the least explored. Similarly to the work of (Liu et al., 2018a), we plan to further explore potentially interesting relations emerging from the attention matrices.
Finally, we believe AttViz could be further extended with a larger database of popular models and a back-end functionality, enabling it to, e.g., fine-tune models. Such endeavors are out of the scope of this paper-the current version of AttViz is lightweight, can be hosted by anyone (with minimal requirements overhead) and performs fast when considering exploration of self-attention.