{"id":5032,"date":"2021-09-22T06:29:26","date_gmt":"2021-09-22T06:29:26","guid":{"rendered":"https:\/\/www.aiproblog.com\/index.php\/2021\/09\/22\/the-attention-mechanism-from-scratch\/"},"modified":"2021-09-22T06:29:26","modified_gmt":"2021-09-22T06:29:26","slug":"the-attention-mechanism-from-scratch","status":"publish","type":"post","link":"https:\/\/www.aiproblog.com\/index.php\/2021\/09\/22\/the-attention-mechanism-from-scratch\/","title":{"rendered":"The Attention Mechanism from Scratch"},"content":{"rendered":"<p>Author: Stefania Cristina<\/p>\n<div>\n<p>The attention mechanism was introduced to improve the performance of the encoder-decoder model for machine translation. The idea behind the attention mechanism was to permit the decoder to utilize the most relevant parts of the input sequence in a flexible manner, by a weighted combination of all of the encoded input vectors, with the most relevant vectors being attributed the highest weights.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<p>In this tutorial, you will discover the attention mechanism and its implementation.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<p>After completing this tutorial, you will know:<\/p>\n<ul>\n<li>How the attention mechanism uses a weighted sum of all of the encoder hidden states to flexibly focus the attention of the decoder to the most relevant parts of the input sequence.<span class=\"Apple-converted-space\">\u00a0<\/span>\n<\/li>\n<li>How the attention mechanism can be generalized for tasks where the information may not necessarily be related in a sequential fashion.<\/li>\n<li>How to implement the general attention mechanism in Python with NumPy and SciPy.<span class=\"Apple-converted-space\">\u00a0<\/span>\n<\/li>\n<\/ul>\n<p>Let\u2019s get started.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<div id=\"attachment_12857\" style=\"width: 1034px\" class=\"wp-caption aligncenter\">\n<a href=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2021\/09\/attention_mechanism_cover-scaled.jpg\"><img decoding=\"async\" aria-describedby=\"caption-attachment-12857\" loading=\"lazy\" class=\"wp-image-12857 size-large\" src=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2021\/09\/attention_mechanism_cover-1024x683.jpg\" alt=\"\" width=\"1024\" height=\"683\" srcset=\"https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2021\/09\/attention_mechanism_cover-1024x683.jpg 1024w, https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2021\/09\/attention_mechanism_cover-300x200.jpg 300w, https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2021\/09\/attention_mechanism_cover-768x512.jpg 768w, https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2021\/09\/attention_mechanism_cover-1536x1024.jpg 1536w, https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2021\/09\/attention_mechanism_cover-2048x1365.jpg 2048w, https:\/\/machinelearningmastery.com\/wp-content\/uploads\/2021\/09\/attention_mechanism_cover-600x400.jpg 600w\" sizes=\"(max-width: 1024px) 100vw, 1024px\"><\/a><\/p>\n<p id=\"caption-attachment-12857\" class=\"wp-caption-text\">The Attention Mechanism from Scratch<br \/>Photo by <a href=\"https:\/\/unsplash.com\/photos\/RbbdzZBKRDY\">Nitish Meena<\/a>, some rights reserved.<\/p>\n<\/div>\n<h2><b>Tutorial Overview<\/b><\/h2>\n<p>This tutorial is divided into three parts; they are:<\/p>\n<ul>\n<li>The Attention Mechanism<\/li>\n<li>The General Attention Mechanism<\/li>\n<li>The General Attention Mechanism with NumPy and SciPy<\/li>\n<\/ul>\n<h2><b>The Attention Mechanism<\/b><\/h2>\n<p>The attention mechanism was introduced by <a href=\"https:\/\/arxiv.org\/abs\/1409.0473\">Bahdanau et al. (2014)<\/a>, to address the bottleneck problem that arises with the use of a fixed-length encoding vector, where the decoder would have limited access to the information provided by the input. This is thought to become especially problematic for long and\/or complex sequences, where the dimensionality of their representation would be forced to be the same as for shorter or simpler sequences.<\/p>\n<p><a href=\"https:\/\/machinelearningmastery.com\/how-does-attention-work-in-encoder-decoder-recurrent-neural-networks\/\">We had seen<\/a> that Bahdanau et al.\u2019s <i>attention mechanism<\/i> is divided into the step-by-step computations of the <i>alignment scores<\/i>, the <i>weights<\/i> and the <i>context vector<\/i>:<\/p>\n<ol>\n<li>\n<b>Alignment scores<\/b>: The alignment model takes the encoded hidden states, $mathbf{h}_i$, and the previous decoder output, $mathbf{s}_{t-1}$, to compute a score, $e_{t,i}$, that indicates how well the elements of the input sequence align with the current output at position, $t$. The alignment model is represented by a function, $a(.)$, which can be implemented by a feedforward neural network:<\/li>\n<\/ol>\n<p style=\"text-align: center\">$$e_{t,i} = a(mathbf{s}_{t-1}, mathbf{h}_i)$$<\/p>\n<ol start=\"2\">\n<li>\n<b>Weights<\/b>: The weights, $alpha_{t,i}$, are computed by applying a softmax operation to the previously computed alignment scores:<\/li>\n<\/ol>\n<p style=\"text-align: center\">$$alpha_{t,i} = text{softmax}(e_{t,i})$$<\/p>\n<ol start=\"3\">\n<li>\n<b>Context vector<\/b>: A unique context vector, $mathbf{c}_t$, is fed into the decoder at each time step. It is computed by a weighted sum of all, $T$, encoder hidden states:<\/li>\n<\/ol>\n<p style=\"text-align: center\">$$mathbf{c}_t = sum_{i=1}^T alpha_{t,i} mathbf{h}_i$$<\/p>\n<p style=\"text-align: left\">Bahdanau et al. had implemented an RNN for both the encoder and decoder.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<p>However, the attention mechanism can be re-formulated into a general form that can be applied to any sequence-to-sequence (abbreviated to seq2seq) task, where the information may not necessarily be related in a sequential fashion.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<blockquote>\n<p><i>In other words, the database doesn\u2019t have to consist of the hidden RNN states at different steps, but could contain any kind of information instead.<\/i><\/p>\n<p>\u2013 <a href=\"https:\/\/www.amazon.com\/Advanced-Deep-Learning-Python-next-generation\/dp\/178995617X\">Advanced Deep Learning with Python<\/a>, 2019.<\/p>\n<\/blockquote>\n<h2><b>The General Attention Mechanism<\/b><\/h2>\n<p>The general attention mechanism makes use of three main components, namely the <i>queries<\/i>, $mathbf{Q}$, the <i>keys<\/i>, $mathbf{K}$, and the <i>values<\/i>, $mathbf{V}$.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<p>If we had to compare these three components to the attention mechanism as proposed by Bahdanau et al., then the query would be analogous to the previous decoder output, $mathbf{s}_{t-1}$, while the values would be analogous to the encoded inputs, $mathbf{h}_i$. In the Bahdanau attention mechanism, the keys and values are the same vector.<\/p>\n<blockquote>\n<p><i>In this case,\u00a0we can think of the vector\u00a0$mathbf{s}_{t-1}$\u00a0as a\u00a0query\u00a0executed against a database of key-value pairs, where\u00a0the keys are vectors and\u00a0the hidden states\u00a0$mathbf{h}_i$\u00a0are the values.<\/i><\/p>\n<p>\u2013 <a href=\"https:\/\/www.amazon.com\/Advanced-Deep-Learning-Python-next-generation\/dp\/178995617X\">Advanced Deep Learning with Python<\/a>, 2019.<\/p>\n<\/blockquote>\n<p>The general attention mechanism then performs the following computations:<\/p>\n<ol>\n<li>Each query vector, $mathbf{q} = mathbf{s}_{t-1}$, is matched against a database of keys to compute a score value. This matching operation is computed as the dot product of the specific query under consideration with each key vector, $mathbf{k}_i$:<span class=\"Apple-converted-space\">\u00a0<\/span>\n<\/li>\n<\/ol>\n<p style=\"text-align: center\">$$e_{mathbf{q},mathbf{k}_i} = mathbf{q} cdot mathbf{k}_i$$<\/p>\n<ol start=\"2\">\n<li>The scores are passed through a softmax operation to generate the weights:<\/li>\n<\/ol>\n<p style=\"text-align: center\">$$alpha_{mathbf{q},mathbf{k}_i} = text{softmax}(e_{mathbf{q},mathbf{k}_i})$$<\/p>\n<ol start=\"3\">\n<li>The generalized attention is then computed by a weighted sum of the value vectors, $mathbf{v}_{mathbf{k}_i}$, where each value vector is paired with a corresponding key:<\/li>\n<\/ol>\n<p style=\"text-align: center\">$$text{attention}(mathbf{q}, mathbf{K}, mathbf{V}) = sum_i alpha_{mathbf{q},mathbf{k}_i} mathbf{v}_{mathbf{k}_i}$$<\/p>\n<p>Within the context of machine translation, each word in an input sentence would be attributed its own query, key and value vectors. These vectors are generated by multiplying the encoder\u2019s representation of the specific word under consideration, with three different weight matrices that would have been generated during training.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<p>In essence, when the generalized attention mechanism is presented with a sequence of words, it takes the query vector attributed to some specific word in the sequence and scores it against each key in the database. In doing so, it captures how the word under consideration relates to the others in the sequence. Then it scales the values according to the attention weights (computed from the scores), in order to retain focus on those words that are relevant to the query. In doing so, it produces an attention output for the word under consideration.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<h2><b>The General Attention Mechanism with NumPy and SciPy<\/b><\/h2>\n<p>In this section, we will explore how to implement the general attention mechanism using the NumPy and SciPy libraries in Python.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<p>For simplicity, we will initially calculate the attention for the first word in a sequence of four. We will then generalize the code to calculate an attention output for all four words in matrix form.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<p>Hence, let\u2019s start by first defining the word embeddings of the four different words for which we will be calculating the attention. In actual practice, these word embeddings would have been generated by an encoder, however for this particular example we shall be defining them manually.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\"># encoder representations of four different words\r\nword_1 = array([1, 0, 0])\r\nword_2 = array([0, 1, 0])\r\nword_3 = array([1, 1, 0])\r\nword_4 = array([0, 0, 1])<\/pre>\n<p>The next step generates the weight matrices, which we will eventually be multiplying to the word embeddings to generate the queries, keys and values. Here, we shall be generating these weight matrices randomly, however in actual practice these would have been learned during training.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# generating the weight matrices\r\nrandom.seed(42) # to allow us to reproduce the same attention values\r\nW_Q = random.randint(3, size=(3, 3))\r\nW_K = random.randint(3, size=(3, 3))\r\nW_V = random.randint(3, size=(3, 3))<\/pre>\n<p>Notice how the number of rows of each of these matrices is equal to the dimensionality of the word embeddings (which in this case is three) to allow us to perform the matrix multiplication.<\/p>\n<p>Subsequently, the query, key and value vectors for each word are generated by multiplying each word embedding by each of the weight matrices.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# generating the queries, keys and values\r\nquery_1 = word_1 @ W_Q\r\nkey_1 = word_1 @ W_K\r\nvalue_1 = word_1 @ W_V\r\n\r\nquery_2 = word_2 @ W_Q\r\nkey_2 = word_2 @ W_K\r\nvalue_2 = word_2 @ W_V\r\n\r\nquery_3 = word_3 @ W_Q\r\nkey_3 = word_3 @ W_K\r\nvalue_3 = word_3 @ W_V\r\n\r\nquery_4 = word_4 @ W_Q\r\nkey_4 = word_4 @ W_K\r\nvalue_4 = word_4 @ W_V<\/pre>\n<p>Considering only the first word for the time being, the next step scores its query vector against all of the key vectors using a dot product operation.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# scoring the first query vector against all key vectors\r\nscores = array([dot(query_1, key_1), dot(query_1, key_2), dot(query_1, key_3), dot(query_1, key_4)])<\/pre>\n<p>The score values are subsequently passed through a softmax operation to generate the weights. Before doing so, it is common practice to divide the score values by the square root of the dimensionality of the key vectors (in this case, three), to keep the gradients stable.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# computing the weights by a softmax operation\r\nweights = softmax(scores \/ key_1.shape[0] ** 0.5)<\/pre>\n<p>Finally, the attention output is calculated by a weighted sum of all four value vectors.<span class=\"Apple-converted-space\">\u00a0<\/span><\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">...\r\n# computing the attention by a weighted sum of the value vectors\r\nattention = (weights[0] * value_1) + (weights[1] * value_2) + (weights[2] * value_3) + (weights[3] * value_4)\r\n\r\nprint(attention)<\/pre>\n<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">[0.98522025 1.74174051 0.75652026]<\/pre>\n<p>For faster processing, the same calculations can be implemented in matrix form to generate an attention output for all four words in one go:<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">from numpy import array\r\nfrom numpy import random\r\nfrom numpy import dot\r\nfrom scipy.special import softmax\r\n\r\n# encoder representations of four different words\r\nword_1 = array([1, 0, 0])\r\nword_2 = array([0, 1, 0])\r\nword_3 = array([1, 1, 0])\r\nword_4 = array([0, 0, 1])\r\n\r\n# stacking the word embeddings into a single array\r\nwords = array([word_1, word_2, word_3, word_4])\r\n\r\n# generating the weight matrices\r\nrandom.seed(42)\r\nW_Q = random.randint(3, size=(3, 3))\r\nW_K = random.randint(3, size=(3, 3))\r\nW_V = random.randint(3, size=(3, 3))\r\n\r\n# generating the queries, keys and values\r\nQ = words @ W_Q\r\nK = words @ W_K\r\nV = words @ W_V\r\n\r\n# scoring the query vectors against all key vectors\r\nscores = Q @ K.transpose()\r\n\r\n# computing the weights by a softmax operation\r\nweights = softmax(scores \/ K.shape[1] ** 0.5, axis=1)\r\n\r\n# computing the attention by a weighted sum of the value vectors\r\nattention = weights @ V\r\n\r\nprint(attention)<\/pre>\n<\/p>\n<pre class=\"urvanov-syntax-highlighter-plain-tag\">[[0.98522025 1.74174051 0.75652026]\r\n [0.90965265 1.40965265 0.5       ]\r\n [0.99851226 1.75849334 0.75998108]\r\n [0.99560386 1.90407309 0.90846923]]<\/pre>\n<\/p>\n<h2><b>Further Reading<\/b><\/h2>\n<p>This section provides more resources on the topic if you are looking to go deeper.<\/p>\n<h3><b>Books<\/b><\/h3>\n<ul>\n<li>\n<a href=\"https:\/\/www.amazon.com\/Advanced-Deep-Learning-Python-next-generation\/dp\/178995617X\">Advanced Deep Learning with Python<\/a>, 2019.<\/li>\n<li>\n<a href=\"https:\/\/www.amazon.com\/Deep-Learning-Essentials-hands-fundamentals\/dp\/1785880365\">Deep Learning Essentials<\/a>, 2018.<\/li>\n<\/ul>\n<h3><b>Papers<\/b><\/h3>\n<ul>\n<li>\n<a href=\"https:\/\/arxiv.org\/abs\/1409.0473\">Neural Machine Translation by Jointly Learning to Align and Translate<\/a>, 2014.<\/li>\n<\/ul>\n<h2><b>Summary<\/b><\/h2>\n<p>In this tutorial, you discovered the attention mechanism and its implementation.<\/p>\n<p>Specifically, you learned:<\/p>\n<ul>\n<li>How the attention mechanism uses a weighted sum of all of the encoder hidden states to flexibly focus the attention of the decoder to the most relevant parts of the input sequence.<span class=\"Apple-converted-space\">\u00a0<\/span>\n<\/li>\n<li>How the attention mechanism can be generalized for tasks where the information may not necessarily be related in a sequential fashion.<\/li>\n<li>How to implement the general attention mechanism with NumPy and SciPy.<\/li>\n<\/ul>\n<p>Do you have any questions?<br \/>\nAsk your questions in the comments below and I will do my best to answer.<\/p>\n<p>The post <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/the-attention-mechanism-from-scratch\/\">The Attention Mechanism from Scratch<\/a> appeared first on <a rel=\"nofollow\" href=\"https:\/\/machinelearningmastery.com\/\">Machine Learning Mastery<\/a>.<\/p>\n<\/div>\n<p><a href=\"https:\/\/machinelearningmastery.com\/the-attention-mechanism-from-scratch\/\">Go to Source<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Author: Stefania Cristina The attention mechanism was introduced to improve the performance of the encoder-decoder model for machine translation. The idea behind the attention mechanism [&hellip;] <span class=\"read-more-link\"><a class=\"read-more\" href=\"https:\/\/www.aiproblog.com\/index.php\/2021\/09\/22\/the-attention-mechanism-from-scratch\/\">Read More<\/a><\/span><\/p>\n","protected":false},"author":1,"featured_media":5033,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_bbp_topic_count":0,"_bbp_reply_count":0,"_bbp_total_topic_count":0,"_bbp_total_reply_count":0,"_bbp_voice_count":0,"_bbp_anonymous_reply_count":0,"_bbp_topic_count_hidden":0,"_bbp_reply_count_hidden":0,"_bbp_forum_subforum_count":0,"footnotes":""},"categories":[24],"tags":[],"_links":{"self":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/5032"}],"collection":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/comments?post=5032"}],"version-history":[{"count":0,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/posts\/5032\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media\/5033"}],"wp:attachment":[{"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/media?parent=5032"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/categories?post=5032"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.aiproblog.com\/index.php\/wp-json\/wp\/v2\/tags?post=5032"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}