# AllenNLP: sequence to sequence attention plots

As follow-up to last weeks post about implemting a reversing sequence-to-sequence model in AllenNLP, this post is about visualizing the attention.

Same as last week this post was tested with Python 3.7 and AllenNLP 0.8.4.
And all code is in this repository: https://github.com/mfa/allennlp-reverse-seq2seq/

To get the informations needed to plot the attentions a few methods of the SimpleSeq2Seq class in simple_seq2seq.py have to be modified.

The lines changed compared to version 0.8.4 of AllenNLP:

```diff --git a/simple_seq2seq.py b/simple_seq2seq.py
index 849da8a..9c7e3da 100644
--- a/simple_seq2seq.py
+++ b/simple_seq2seq.py
@@ -323,6 +323,7 @@ class SimpleSeq2Seq(Model):

step_logits: List[torch.Tensor] = []
step_predictions: List[torch.Tensor] = []
+        attn: List[torch.Tensor] = []
for timestep in range(num_decoding_steps):
if self.training and torch.rand(1).item() < self._scheduled_sampling_ratio:
# Use gold tokens at test time and at a rate of 1 - _scheduled_sampling_ratio
@@ -338,6 +339,8 @@ class SimpleSeq2Seq(Model):

# shape: (batch_size, num_classes)
output_projections, state = self._prepare_output_projections(input_choices, state)
+            if not self.training:
+                attn.append(torch.squeeze(state["attention_weights"]))

# list of tensors, shape: (batch_size, 1, num_classes)
step_logits.append(output_projections.unsqueeze(1))
@@ -358,6 +361,9 @@ class SimpleSeq2Seq(Model):

output_dict = {"predictions": predictions}

+        if not self.training:
+            output_dict["attentions"] = torch.unsqueeze(torch.stack(attn), 0)
+
if target_tokens:
# shape: (batch_size, num_decoding_steps, num_classes)
logits = torch.cat(step_logits, 1)
@@ -412,7 +418,8 @@ class SimpleSeq2Seq(Model):

if self._attention:
# shape: (group_size, encoder_output_dim)
-            attended_input = self._prepare_attended_input(decoder_hidden, encoder_outputs, source_mask)
+            attended_input, input_weights = self._prepare_attended_input(decoder_hidden, encoder_outputs, source_mask)
+            state["attention_weights"] = input_weights

# shape: (group_size, decoder_output_dim + target_embedding_dim)
decoder_input = torch.cat((attended_input, embedded_input), -1)
@@ -451,7 +458,7 @@ class SimpleSeq2Seq(Model):
# shape: (batch_size, encoder_output_dim)
attended_input = util.weighted_sum(encoder_outputs, input_weights)

-        return attended_input
+        return attended_input, input_weights

@staticmethod
def _get_loss(logits: torch.LongTensor,
```

The same diff in the github repository: https://github.com/mfa/allennlp-reverse-seq2seq/commit/d9ca4c9c5f8f489b14f091a974b7e7a9cdbd7fef

Additionally the class name and registered name are changed to avoid duplicate naming.
Now we have to use the new model in the configuration and train with an additional parameter:

```allennlp train configurations/reverse_starting_point.json -s output --include-package library
```
For prediction we need a custom predictor that adds source and target sequence to plot them later.
To predict and than generate the plots run:

```allennlp predict output/model.tar.gz --use-dataset-reader examples.csv --predictor my_seq2seq --output-file output/examples.output --include-package library
python tools/plot_attention.py
```

One example plot looks like this:
{"ft_lang_label":"__label__en","ft_lang_prob":0.5681881,"math_prob":0.8624934,"size":3349,"snap":"2021-43-2021-49","text_gpt3_token_len":834,"char_repetition_ratio":0.119282514,"word_repetition_ratio":0.02247191,"special_character_ratio":0.25918186,"punctuation_ratio":0.21428572,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.96547294,"pos_list":[0,1,2],"im_url_duplicate_count":[null,4,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-10-17T05:29:48Z\",\"WARC-Record-ID\":\"<urn:uuid:929af6c1-19f7-4dee-84ab-4c9ae7b70a2c>\",\"Content-Length\":\"13942\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:1ebbcf1f-d04a-45e8-9506-a95d8fa601f7>\",\"WARC-Concurrent-To\":\"<urn:uuid:bd648be2-3c73-45b0-af28-87c4104b236c>\",\"WARC-IP-Address\":\"195.201.98.8\",\"WARC-Target-URI\":\"https://madflex.de/allennlp--sequence-to-sequence-attention-plots/\",\"WARC-Payload-Digest\":\"sha1:D6YIJ4GEOEQJPOZIZQFRO5WGPTBA73PG\",\"WARC-Block-Digest\":\"sha1:EMRJSL4DEN6DNZ6CGTQGNVYQBZ4BMRKI\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-43/CC-MAIN-2021-43_segments_1634323585121.30_warc_CC-MAIN-20211017052025-20211017082025-00337.warc.gz\"}"}