<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://aamster.github.io/feed.xml" rel="self" type="application/atom+xml"/><link href="https://aamster.github.io/" rel="alternate" type="text/html" hreflang="en"/><updated>2025-07-09T14:00:30+00:00</updated><id>https://aamster.github.io/feed.xml</id><entry><title type="html">Translation using deep neural networks - Transformer (part 2)</title><link href="https://aamster.github.io/blog/2025/sequence_to_sequence_models_2/" rel="alternate" type="text/html" title="Translation using deep neural networks - Transformer (part 2)"/><published>2025-07-09T00:00:00+00:00</published><updated>2025-07-09T00:00:00+00:00</updated><id>https://aamster.github.io/blog/2025/sequence_to_sequence_models_2</id><content type="html" xml:base="https://aamster.github.io/blog/2025/sequence_to_sequence_models_2/"><![CDATA[<h1 id="introduction">Introduction</h1> <p>In the last article we looked at how attention can be used with recurrent neural networks (RNNs) to generate a sequence from an input sequence. Specifically, we looked at the problem of translating an input sequence from one language into another. We saw that with RNNs without attention, the decoder in a translation model must use a single context vector to compress all the information in the source sequence; with attention, we can attend to different tokens at different decoder timesteps, which enables the model to “pay attention to” different things at different timesteps. This seems intuitively helpful, since if we’re translating a sequence, only certain parts of the sequence are relevant at certain decoding timesteps. Let’s revisit the attention weights example from part 1.</p> <figure id="figure-1" style="text-align: center;"> <div id="attention_weights_plot_container" style="width: 100%"></div> <script>fetch("/assets/plotly/2025-04-13-sequence_to_sequence_translation_2/rnn_attention_weights_0.json").then(t=>t.json()).then(t=>{Plotly.newPlot("attention_weights_plot_container",t.data,t.layout)})["catch"](t=>{console.error("Error loading Plotly data:",t)});</script> </figure> <p>This figure shows the attention weights from each of the predicted tokens on the left to the source tokens on the right. Each generated token on the left attends to each source token on the right, and the sum of weights from each generated token add up to 1. Hover over each line to see the weights between tokens more easily. Only weights &gt; 0.1 are being shown for ease of viewing.</p> <p>At the first timestep, we pay attention to the end of sequence token <code class="language-plaintext highlighter-rouge">&lt;/s&gt;</code>, which indicates that we need to start the translation, and we output <code class="language-plaintext highlighter-rouge">&lt;s&gt;</code>, the start of sequence token.</p> <p>At the second timestep we pay attention to “But” and look forward 1 timestep to “why” and output the French word for “but,” “Mais.”</p> <p>The transformer builds on the idea of attention and uses attention as feature extraction. It was first introduced in the paper <a class="citation" href="#10.5555/3295222.3295349">(Vaswani et al., 2017)</a>.</p> <p>In <a href="#weaknesses-of-rnn-architectures">Weaknesses of RNN architecture</a> I’ll motivate the need for the transformer architecture. In <a href="#transformer-architecture">Transformer architecture</a> I’ll go more in depth into its architecture. Finally, in <a href="#experiments-and-results">Experiments and results</a> I’ll show how the transformer performance compares to the RNN performance, and as a sub-research question, how the original encoder-decoder transformer architecture compares to GPT-style decoder-only architecture in <a href="#encoder-decoder-vs-decoder-only">Encoder-decoder vs decoder-only</a></p> <p>For this post, it helps if you have read <a href="https://aamster.github.io/blog/2024/sequence_to_sequence_models_1/">the previous post</a> or are already familiar with this topic.</p> <p>All code/trained weights, data for this post can be accessed <a href="https://github.com/aamster/seq2seq-translation?tab=readme-ov-file#translation-using-deep-neural-networks---transformer-part-2">here</a></p> <h1 id="weaknesses-of-rnn-architecture">Weaknesses of RNN architecture</h1> <h2 id="sequential-processing">sequential processing</h2> <p>Recall that in the RNN we extract features from the input sequence iteratively.</p> <p>To repeate the example from the previous post:</p> <p>Let’s tokenize the sentence as [“I”, “have”, “socks”, “.”]</p> <p>Let the embedding vector be \(x \in \mathbb{R}^2\)</p> <p>Let the hidden state be \(h \in \mathbb{R}^3\).</p> <div class="jupyter-notebook" style="position: relative; width: 100%; margin: 0 auto;"> <div class="jupyter-notebook-iframe-container"> <iframe src="/assets/jupyter/2024-10-03-sequence_to_sequence_translation/vanilla_rnn.ipynb.html" style="position: absolute; top: 0; left: 0; border-style: none;" width="100%" height="100%" onload="this.parentElement.style.paddingBottom = (this.contentWindow.document.documentElement.scrollHeight + 10) + 'px'"></iframe> </div> </div> <p>The RNN works by iteratively processing each token in the input sequence. We start with an initial “hidden state” defined by <code class="language-plaintext highlighter-rouge">h_t</code>. When we process each token, we use the current hidden state <code class="language-plaintext highlighter-rouge">h_t</code> and the current token <code class="language-plaintext highlighter-rouge">x_t</code> as input to update the hidden state. In this way we can keep track of what we have seen so that the model can encode the meaning of the entire sequence. The hidden state can be seen as an internal representation of the sequence, including token <code class="language-plaintext highlighter-rouge">x_t</code> and is collected in the variable <code class="language-plaintext highlighter-rouge">outs</code>. <code class="language-plaintext highlighter-rouge">outs</code> therefore can be seen as a \(\mathbb{R}^{T\times h}\) encoded representation of the sequence, and <code class="language-plaintext highlighter-rouge">h_t</code> as the final representation of the entire sequence.</p> <p>We had to process each token iteratively in order for an arbitrary token \(x_{t}\) to “know about” a previous token \(x_{t'}\). Iterative processing should be avoided if possible, since we would like to make use of the parallel processing that modern GPUs provide.</p> <p>The transformer does not use iterative processing to encode an input sequence but instead uses an attention mechanism so that in parallel, all tokens can “know about” all other previous tokens.</p> <h2 id="only-a-single-attention-vector">Only a single attention vector</h2> <p>In the RNN with attention, we are only calculating an alignment vector between \(q\) and \(K\) a single time, producing a single measure of similarity, or alignment, between the question \(q\) and the keys \(K\). What if we wanted to align the query with the keys in multiple different ways, for example, by looking for nouns, verbs, adjectives, proper nouns, etc. separately. Currently, using a single measure of similarity, these ideas of similarity are all combined into a single measure, which might make it harder for the model to learn complex patterns.</p> <p>The transformer uses multiple <em>heads</em> of attention to achieve this.</p> <h2 id="only-a-single-layer-of-attention">Only a single layer of attention</h2> <p>In the RNN with attention we stack multiple RNNs together to achieve depth but just calculate attention between the outputs. We’d like to instead add more layers to the attention calculation. We know that in deep learning, depth can allow us to learn more complex patterns.</p> <h1 id="transformer-architecture">Transformer architecture</h1> <p>The paper that first introduced the transformer architecture, <a class="citation" href="#10.5555/3295222.3295349">(Vaswani et al., 2017)</a> is called “Attention is all you need.” From that title we might guess that the transformer makes attention a core component of the architecture. Whereas with the RNN with attention we use attention to align the decoder hidden state with the encoder outputs, but still use sequential recurrent processing using \(h_t = f(h_t, x_t; W)\) to update the hidden state, with the transformer we remove the recurrent hidden state calculation and instead calculate attention as the main computational unit and feature extractor.</p> <p>The transformer has many other components, including attention that already existed at the time, and combines them into a novel architecture. Let’s look at the diagram of the architecture from the paper that introduced the transformer:</p> <figure id="figure-2" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/transformer_architecture.png" alt="transformer architecture" style="width: 60%"/> <figcaption>Figure 2: Transformer architecture. Figure from <a class="citation" href="#10.5555/3295222.3295349">(Vaswani et al., 2017)</a> </figcaption> </figure> <p>On the left of the diagram is the encoder, and on the right is the decoder. The encoder encodes the source sentence while the decoder generates the translated sentence using the encoded representation as input. The encoder and decoder are largely the same with a few differences.</p> <p>We’ll look at each component in the diagram and start with the encoder.</p> <h2 id="how-transformer-uses-attention">how transformer uses attention</h2> <p>In the encoder, the RNN uses a recurrent hidden state that takes as input the current token \(x_t\) and the previously seen tokens are encoded using the hidden state \(h_t\). This is a sequential operation since we iterate through each token in the sequence. How can this be replaced with a similar operation without iterating through each token?</p> <p>We’ve seen how attention can be computed between the RNN decoder hidden state vector and the encoder outputs; the decoder hidden state is treated as the query \(q\), and the encoder outputs are treated as the keys \(K\). The transformer adapts attention by generalizing it to an arbitrary number of queries and keys. In the transformer encoder, we calculate attention not just between a single vector and a set of keys, but between a set of query vectors and a set of keys. The set of query vectors \(Q\) is the entire source sequence, and the set of keys is the entire source sequence. The queries and the keys are the same! This is known as <em>self-attention</em>. Let’s look at self-attention in detail.</p> <p>First, though, we need to convert the tokens into numeric vectors as with the RNN, which is the which is the <span style=" border: 4px solid black; background-color: rgb(253, 220, 221); color: black; padding: 0.1em 0.5em; border-radius: 8px; display: inline-block; text-align: center; font-size: 14px; "> Input<br/> Embedding </span> box in the diagram, and is the same as described in the previous post.</p> <h3 id="self-attention">self-attention</h3> <h4 id="step-1-q-k-v-projection">Step 1: Q, K, V projection</h4> <p>Now, we can start to compute self-attention, which is the <span style=" border: 4px solid black; background-color: rgb(250, 219, 179); color: black; padding: 0.1em 0.5em; border-radius: 8px; display: inline-block; text-align: center; font-size: 14px; "> Multi-Head<br/> Attention </span> box in the diagram. First, we project the sequence embedding matrix 3 times using 3 different linear maps, \(Q_{proj} \in \mathbb{R}^{D \times D}\), \(K_{proj} \in \mathbb{R}^{D \times D}\), and \(V_{proj} \in \mathbb{R}^{D \times D}\). This results in three new tensors, \(Q\), \(K\), and \(V\), all size \(T \times D\). These are the queries, keys, and values respectively.</p> <p>Importantly, <em>notice that we reuse the same sequence to produce the queries, keys, and values.</em> We do not use different sequences as in the RNN with attention.</p> <figure id="figure2" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/projections.png" alt="projections" style="width: 75%"/> <figcaption>Figure 3: Query, keys, and values projections </figcaption> </figure> <h4 id="step-2-attention-weights">Step 2: attention weights</h4> <p>We then compute the attention weights, \(A\). These are calculated the same way as in RNN with attention, using the dot product between a query \(q\) and key \(k\). However, in the transformer there is not just one query (as was the case with the decoder hidden state in the RNN with attention) but \(T\) queries and \(T\) keys. In other words, we treat each token as both a query and key, so that we have \(T\) queries and \(T\) keys each of dimension \(D\). We then calculate similarity using dot-product (aka cosine similarity) between all queries and all keys in parallel using matrix multiplies. This results in a \(T \times T\) matrix including the similarity between every <em>query-key</em> combination.</p> <figure id="figure3" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/attention1.png" alt="attention 1" style="width: 50%"/> <figcaption>Figure 4: Query and key similarity </figcaption> </figure> <div class="note-box"> <strong>Note:</strong><br/> <p>Note the implications of storing a \(T \times T\) matrix. Here \(T\) is known as the <em>context length</em>. It is the maximum length the model can take as input and hold in memory. The model then requires \(O(T^2)\) memory to store attention weights. This can get expensive as \(T\) gets larger. If the context length is \(1024\) which is small for LLMs, then the \(T \times T\) matrix will store over \(1M\) numbers. Before with the RNN with attention, we never explicitly stored the \(T \times T\) matrix because we iterated through the tokens sequentially and maintained a hidden state. But we said that this was not scalable because it requires sequential iteration. With the transformer we’ve parallelized extracting information from the sequence and so have more efficient compute but at the cost of greater memory needs.</p> </div> <p>As before, we divide each product by \(\sqrt{D}\) as explained <a href="https://aamster.github.io/blog/2024/sequence_to_sequence_models_1/#attention">in the previous post</a>. Finally, we use the \({softmax}\) function for each query across all keys to make positive and normalize to a probability distribution. \({softmax}(A_{ij})\) is defined as:</p> \[\text{softmax}(A_{ij}) = \frac{\exp(A_{ij})}{\sum_{k=1}^{T} \exp(A_{ik})}, \quad i,j = 1,\dots, T.\] <p>This gives us a measure of similarity between each query and key, which is in the range \([0, 1]\) and sums to 1 across keys for a given query.</p> <p>Note that we use the terminology \(q_i\) “attends to” \(k_j\) to denote a strong similarity between \(q_i\) and \(k_j\).</p> <h4 id="step-3-weighting-features">Step 3: weighting features</h4> <p>The matrix \(V\) contains feature vectors of length \(d\) for each of the \(k\) keys. Row \(0\) contains a \(d\)-dimensional vector for key \(0\), row 1 a \(d\)-dimensional vector for key \(1\), etc.</p> <figure id="figure5" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/v.png" alt="V" style="width: 75%"/> <figcaption>Figure 5: $$V$$ </figcaption> </figure> <p>We’d like to weight each feature vector by the attention weights by multiplying the attention matrix \(A\) with the feature matrix \(V\).</p> <h4 id="example">example</h4> <p>Let’s look at a concrete example using the sequence “The dog barked” and for simplicity let’s tokenize as <code class="language-plaintext highlighter-rouge">["The", "dog", "barked"]</code>. Let \(D\) be 4.</p> <p>Let <span style=" display:inline-block; width:20px; height:20px; background:rgb(0 149 250) ; vertical-align:middle; "></span> denote a value for a <span style="color: rgb(0 149 250)">query</span> and <span style=" display:inline-block; width:20px; height:20px; background:rgb(255 89 75) ; vertical-align:middle; "></span> denote a value for a <span style="color: rgb(255 89 75)">key</span> and <span style="color: rgb(0 149 250)">\(Q\)</span>, <span style="color: rgb(255 89 75)">\(K\)</span> and <span style="color: rgb(255 89 75)">\(V\)</span> be:</p> <figure id="figure-6" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/qkv_example.png" alt="QKV example" style="width: 50%"/> <figcaption>Figure 6: QKV example </figcaption> </figure> <p>\(A\) is:</p> <figure id="figure-7" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/a_example.png" alt="A example" style="width: 50%"/> <figcaption>Figure 7: A example </figcaption> </figure> <p>This shows that the token <span style="color: rgb(0 149 250)">“The”</span> paid attention most strongly to <span style="color: rgb(255 89 75)">“barked”</span>, <span style="color: rgb(0 149 250)">“dog”</span> to <span style="color: rgb(255 89 75)">“barked”</span> and <span style="color: rgb(0 149 250)">“barked”</span> to <span style="color: rgb(255 89 75)">“dog”</span>.</p> <p>Next we compute \(AV\):</p> <figure id="figure-8" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/av_example.png" alt="AV example" style="width: 50%"/> <figcaption>Figure 8: AV example </figcaption> </figure> <p>If we look at the weighted feature vector for <em>barked</em>:</p> <figure id="figure-9" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/av_example_worked_out.png" alt="AV example worked out" style="width: 100%"/> <figcaption>Figure 9: AV example worked out </figcaption> </figure> <p>We see that because the attention \(a_{barked-dog}\) is the strongest, that the feature vector \(v_{dog}\) is given the most weight when calculating the weighted feature vector for <em>barked</em>.</p> <p>Also note that the weighted feature vector for <span style="color: rgb(0 149 250)">barked</span> now includes information from all other <span style="color: rgb(255 89 75)">keys</span> in the sequence.</p> <h3 id="multi-headed-attention">multi-headed attention</h3> <p>We said that one of the downsides to the RNN with attention was that the decoder hidden state could only ask one “question” of the encoded source sequence. This is because \(qK^T\) results in a \(T\)-dimensional vector \(a\) representing the attention weights. The hidden state only asks a single “question” which gets ranked as a probability distribution against the \(T\) keys in the encoder output.</p> <figure id="figure-10" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/rnn_attention.png" alt="RNN attention" style="width: 100%"/> <figcaption>Figure 10: RNN attention </figcaption> </figure> <p>The same is true of the attention mechanism in steps 1 through 3 above. Each token or (“query”) only asks a single question of every other token (“key”). What if we want each token to be able to ask multiple questions of the other tokens and rank alignment for each question separately. These “questions” are learned by the model, but presumably different questions would be “is this an adjective?” or “is this a proper noun?” We can see examples of what kinds of different questions the model has learned to ask in <a href="#attention-examples">attention examples</a>.</p> <p>How can we improve the attention mechanism so that each token asks multiple different questions instead of just a single question? Recall that we map each token to a \(T \times D\) tensor \(Q\), and separately map to a different \(T \times D\) tensor \(K\). To calculate attention, we take the product \(QK^T\) to produce a \(T \times T\) tensor of attention weights, normalized so that each query’s attention maps to a probability distribution for each key. Each query only asks a single question of each key.</p> <p>To improve this so that each query can ask multiple questions of each key, we need to compute multiple \(T \times T\) attention tensors for each question. The number of questions is called \(H\) and is a hyperparameter. Each \(h\) is called a “head” and this strategy is called “multi-head attention.”</p> <p>To construct multiple heads, we split \(Q\), \(K\), and \(V\), all of which are \(\mathbb{R}^{T \times D}\) respectively into \(\mathbb{R}^{T \times H \times D/H}\) tensors, which is equivalent in original size to a \(\mathbb{R}^{T \times D}\) tensor.</p> <figure id="figure-11" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/multi_headed_attention.png" alt="multi-headed attention" style="width: 70%"/> <figcaption>Figure 11: Multi-headed attention Q,K,V </figcaption> </figure> <p>Now we take each \(H\) \(Q\) and \(K\) tensors and compute \(A_h\) for each head. This results in \(H\) \(T \times T\) attention weight tensors, instead of the 1 we had previously. This increases the memory requirements by a factor of \(H\). This allows the model to learn \(H\) different measures of similarity between each token.</p> <figure id="figure-12" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/multi_headed_attention_weights.png" alt="multi-headed attention weights" style="width: 70%"/> <figcaption>Figure 12: Multi-headed attention weights </figcaption> </figure> <p>Finally, we weight each of the \(H\) value tensors \(V\) using the \(H\) attention weight tensors. This results in \(H\) \(T \times D/H\) tensors which get stacked together as a single \(T \times D\) tensor, the same dimensionality as in the single-headed scenario.</p> <figure id="figure-13" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/multi_headed_feature_vectors.png" alt="multi-headed feature vectors" style="width: 100%"/> <figcaption>Figure 13: Multi-headed weighted feature vectors </figcaption> </figure> <p>The stacked multi-headed attention output is on the right.</p> <p>For the cost of \(H\) attention weight tensors instead of 1, the model is able to learn \(H\) different queries, keys, values, and similarity measures.</p> <h4 id="code-example">code example</h4> <p>step 1.</p> <p>In code, using pytorch, if we have a <code class="language-plaintext highlighter-rouge">(T, D)</code> tensor for <code class="language-plaintext highlighter-rouge">Q</code>, <code class="language-plaintext highlighter-rouge">K</code>, and <code class="language-plaintext highlighter-rouge">V</code> respectively, we can split up into \(H\) different heads using a tensor view</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Q</span> <span class="o">=</span> <span class="n">Q</span><span class="p">.</span><span class="nf">view</span><span class="p">(</span><span class="n">T</span><span class="p">,</span> <span class="n">H</span><span class="p">,</span> <span class="n">D</span><span class="o">//</span><span class="n">H</span><span class="p">).</span><span class="nf">transpose</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">K</span> <span class="o">=</span> <span class="n">K</span><span class="p">.</span><span class="nf">view</span><span class="p">(</span><span class="n">T</span><span class="p">,</span> <span class="n">H</span><span class="p">,</span> <span class="n">D</span><span class="o">//</span><span class="n">H</span><span class="p">).</span><span class="nf">transpose</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">V</span> <span class="o">=</span> <span class="n">V</span><span class="p">.</span><span class="nf">view</span><span class="p">(</span><span class="n">T</span><span class="p">,</span> <span class="n">H</span><span class="p">,</span> <span class="n">D</span><span class="o">//</span><span class="n">H</span><span class="p">).</span><span class="nf">transpose</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
</code></pre></div></div> <p>This will produce a tensor of size <code class="language-plaintext highlighter-rouge">(T, H, D//H)</code>. We swap <code class="language-plaintext highlighter-rouge">T</code> and <code class="language-plaintext highlighter-rouge">H</code> so that <code class="language-plaintext highlighter-rouge">H</code> becomes the batch dimension, which will be needed in the next step, resulting in a <code class="language-plaintext highlighter-rouge">(H, T, D//H)</code> tensor.</p> <p>step 2.</p> <p>To calculate \(H\) \(T \times T\) attention tensors,</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">A</span> <span class="o">=</span> <span class="n">Q</span> <span class="o">@</span> <span class="n">K</span><span class="p">.</span><span class="nf">transpose</span><span class="p">(</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="o">*</span> <span class="p">(</span><span class="mf">1.0</span> <span class="o">/</span> <span class="n">math</span><span class="p">.</span><span class="nf">sqrt</span><span class="p">(</span><span class="n">K</span><span class="p">.</span><span class="nf">size</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)))</span>
</code></pre></div></div> <p>Note that in pytorch if we use <code class="language-plaintext highlighter-rouge">@</code> which is the overloaded symbol for <code class="language-plaintext highlighter-rouge">matmul</code>, that if we have a <code class="language-plaintext highlighter-rouge">(..., A, B)</code> dimensional tensor multiplied with <code class="language-plaintext highlighter-rouge">(..., B, A)</code> tensor, then the <code class="language-plaintext highlighter-rouge">...</code> dimensions are used as a batch dimension and the remaining dimensions are multiplied as in the typical 2d case. Here <code class="language-plaintext highlighter-rouge">H</code> is the batch dimension, but this would usually be part of a mini-batch in which case <code class="language-plaintext highlighter-rouge">B, H</code> would be the batch dimension. This gives us <code class="language-plaintext highlighter-rouge">H</code> <code class="language-plaintext highlighter-rouge">(T, T)</code> tensors, which are calculated in parallel.</p> <p>We map the attention weights for each query to a probability distribution using <code class="language-plaintext highlighter-rouge">softmax</code></p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">A</span> <span class="o">=</span> <span class="n">F</span><span class="p">.</span><span class="nf">softmax</span><span class="p">(</span><span class="n">att</span><span class="p">,</span> <span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
</code></pre></div></div> <p>step 3.</p> <p>Finally, we obtain the weighted feature vectors:</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">y</span> <span class="o">=</span> <span class="n">A</span> <span class="o">@</span> <span class="n">V</span>
</code></pre></div></div> <p>This uses the same batch matmul procedure as in the attention calculation. We are multiplying <code class="language-plaintext highlighter-rouge">(H, T, T)</code> tensor with <code class="language-plaintext highlighter-rouge">(H, T, D/H)</code> so this produces a <code class="language-plaintext highlighter-rouge">(H, T, D/H)</code> tensor.</p> <p>We stack the <code class="language-plaintext highlighter-rouge">H</code> weighted feature tensors together</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">y</span> <span class="o">=</span> <span class="n">y</span><span class="p">.</span><span class="nf">transpose</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">).</span><span class="nf">contiguous</span><span class="p">().</span><span class="nf">view</span><span class="p">(</span><span class="n">T</span><span class="p">,</span> <span class="n">D</span><span class="p">)</span>
</code></pre></div></div> <p>which produces the final <code class="language-plaintext highlighter-rouge">(T, D)</code> tensor.</p> <div class="note-box"> <strong>Note:</strong><br/> <p>There is an even more optimized code path to calculate all this using <code class="language-plaintext highlighter-rouge">torch.nn.functional.scaled_dot_product_attention</code> which uses optimized cuda kernels shown to be much faster and with less memory footprint than the above naive implementation</p> </div> <h3 id="decoder">decoder</h3> <p>So far we’ve been looking at the left-side of the transformer diagram, at the encoder. The decoder plays a similar role to the decoder in the encoder-decoder RNN—it decodes the learned representation from the encoder into a sequence. Like the RNN decoder, the transformer decoder will output a single token at each timestep \({1 \ldots T}\) iteratively. It is similar in many ways to the encoder. It will use self-attention to attend to the tokens it has output and will output a \(d\)-dimensional vector at each timestep. Unlike the encoder:</p> <ul> <li>We don’t want the decoder to see into the future during training. This is accomplished using <em>masked attention</em></li> <li>We want the decoder to also attend to the encoder outputs. This is known as <em>cross-attention</em></li> </ul> <h4 id="masked-attention">masked attention</h4> <p>Let’s take a look at the <span style=" border: 4px solid black; background-color: rgb(250, 219, 179); color: black; padding: 0.1em 0.5em; border-radius: 8px; display: inline-block; text-align: center; font-size: 14px; "> Masked<br/> Multi-Head<br/> Attention </span> box in the <a href="#transformer-architecture">Transformer architecture</a> diagram. In the RNN decoder, we don’t peek into the future by its nature, since we process each token sequentially. This is the so-called “autoregressive” modeling. We need to be careful that the transformer decoder doesn’t see into the future during training, since the self-attention mechanism is able to look at all tokens, including future tokens. In other words, in the target sequence <code class="language-plaintext highlighter-rouge">[I, have, a, cat]</code>, we do not want <code class="language-plaintext highlighter-rouge">I</code> to “know about” <code class="language-plaintext highlighter-rouge">have a cat</code>. This is because we do not know what the correct output is when this is used on novel input sequences, and letting the model see into the future would make it incapable of generating novel correct sequences. How are we going to accomplish this?</p> <p>The self-attention mechanism allows every query \(q_{1 \ldots T}\) to attend to every key \(k_{1 \ldots T}\). But we only want query \(q_t\) to attend to keys \(k_{1 \ldots t-1}\).</p> <p>To accomplish this, we can zero out attention weights for keys \(k_{t \ldots T}\). That way when we compute the softmax over each key, these keys won’t contribute.</p> <p>The trick, in code, is to set the attention output \(AV\) to \(-\inf\) using an upper triangular matrix for all \(k_{t_k&gt;=t_q}\) where \(t_k\) is the key timestep and \(t_q\) is the query timestep. The attention masking is commonly referred to as <em>causal mask</em>.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">causal_mask</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="nf">triu</span><span class="p">(</span><span class="n">torch</span><span class="p">.</span><span class="nf">ones</span><span class="p">(</span><span class="n">t_q</span><span class="p">,</span> <span class="n">t_k</span><span class="p">))</span>
<span class="n">causal_mask</span> <span class="o">=</span> <span class="n">causal_mask</span><span class="p">.</span><span class="nf">masked_fill</span><span class="p">(</span><span class="n">causal_mask</span><span class="p">.</span><span class="nf">bool</span><span class="p">(),</span> <span class="o">-</span><span class="nf">float</span><span class="p">(</span><span class="sh">'</span><span class="s">inf</span><span class="sh">'</span><span class="p">))</span>
<span class="n">att</span> <span class="o">=</span> <span class="p">(</span><span class="n">q</span> <span class="o">@</span> <span class="n">k</span><span class="p">.</span><span class="nf">transpose</span><span class="p">(</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">))</span> <span class="o">*</span> <span class="p">(</span><span class="mf">1.0</span> <span class="o">/</span> <span class="n">math</span><span class="p">.</span><span class="nf">sqrt</span><span class="p">(</span><span class="n">k</span><span class="p">.</span><span class="nf">size</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)))</span>
<span class="n">att</span> <span class="o">+=</span> <span class="n">causal_mask</span>
<span class="n">att</span> <span class="o">=</span> <span class="n">F</span><span class="p">.</span><span class="nf">softmax</span><span class="p">(</span><span class="n">att</span><span class="p">,</span> <span class="n">dim</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
</code></pre></div></div> <p>Example:</p> <figure id="figure-14" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/masked_self_attention.png" alt="masked self-attention" style="width: 60%"/> <figcaption>Figure 14: Masked self-attention </figcaption> </figure> <p>In step <span style=" display: inline-flex; justify-content: center; align-items: center; width: 1.4em; height: 1.4em; border-radius: 50%; background: black; color: white; font: 0.9em/1 Helvetica, sans-serif; "> 1 </span> we initialize \(A\) to hypothetical values where queries are in <span style="color: rgb(10, 146, 240);">blue</span> and keys in <span style="color: rgb(254, 89, 75);">red</span>. In step <span style=" display: inline-flex; justify-content: center; align-items: center; width: 1.4em; height: 1.4em; border-radius: 50%; background: black; color: white; font: 0.9em/1 Helvetica, sans-serif; "> 2 </span> we initialize our upper triangular matrix \(\text{mask}\) to have the value \(-\inf\) in the nonzero slots, and is the same size as \(A\). In step <span style=" display: inline-flex; justify-content: center; align-items: center; width: 1.4em; height: 1.4em; border-radius: 50%; background: black; color: white; font: 0.9em/1 Helvetica, sans-serif; "> 3 </span> we add \(\text{mask}\) to \(A\). In step <span style=" display: inline-flex; justify-content: center; align-items: center; width: 1.4em; height: 1.4em; border-radius: 50%; background: black; color: white; font: 0.9em/1 Helvetica, sans-serif; "> 4 </span> we take the \(\text{softmax}\) across columns for each row. Note the effect of the mask. For the first token <em>I</em> all other timesteps are zeroed out. For the second token, <em>have</em> it is able to attend to itself and the previous token <em>I</em>. For the third token <em>a</em>, it is able to attend to itself and <em>I</em>, <em>have</em>, but not to the next token <em>cat</em>, etc.</p> <h4 id="cross-attention">cross attention</h4> <p>Using masked self-attention, the decoder can pay attention to the tokens in the target sequence. However, we also need the decoder to pay attention to the encoder’s representation of the source sequence. To do this, we’ll use the concept of <em>cross-attention</em> which is the <span style=" border: 4px solid black; background-color: rgb(250, 219, 179); color: black; padding: 0.1em 0.5em; border-radius: 8px; display: inline-block; text-align: center; font-size: 14px; "> Multi-Head<br/> Attention </span> box in the decoder (right half) of the <a href="#transformer-architecture">Transformer architecture</a> diagram.</p> <p>Using self-attention, a sequence can pay attention to itself. However, we can also use attention so that a sequence \(A\) can pay attention to another sequence \(B\). We’ll use that so that the decoder can pay attention to the encoder’s representation.</p> <p>Let the source sequence be <code class="language-plaintext highlighter-rouge">[J'ai, un, chat]</code> and the target sequence be <code class="language-plaintext highlighter-rouge">[I, have, a, cat]</code>.</p> <figure id="figure-15" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/cross_attention.png" alt="cross attention" style="width: 90%"/> <figcaption>Figure 15: Cross attention example </figcaption> </figure> <p>In this example, <span style=" display: inline-flex; justify-content: center; align-items: center; width: 1.4em; height: 1.4em; border-radius: 50%; background: black; color: white; font: 0.9em/1 Helvetica, sans-serif; "> 1 </span> let \(AV_{target}\) be \(AV\) for the target sequence and <span style=" display: inline-flex; justify-content: center; align-items: center; width: 1.4em; height: 1.4em; border-radius: 50%; background: black; color: white; font: 0.9em/1 Helvetica, sans-serif; "> 2 </span> let \(Y_{source}\) be the output from the encoder for the source sequence. Again, let <span style=" display:inline-block; width:20px; height:20px; background:rgb(0 149 250) ; vertical-align:middle; "></span> denote a value for a <span style="color: rgb(0 149 250)">query</span> and <span style=" display:inline-block; width:20px; height:20px; background:rgb(255 89 75) ; vertical-align:middle; "></span> denote a value for a <span style="color: rgb(255 89 75)">key</span>. Then in <span style=" display: inline-flex; justify-content: center; align-items: center; width: 1.4em; height: 1.4em; border-radius: 50%; background: black; color: white; font: 0.9em/1 Helvetica, sans-serif; "> 3 </span> we compute attention weights between the queries from the target to the keys in the source. This is a hypothetical example, but \(att_{target,source}\) is saying that “I” attends most strongly to “Jai,” “have” to “un,” etc.</p> <p>This shows how the target sequence can attend to the source sequence, crucial for translation in which we need to know how the target translation aligns with the source sequence.</p> <h2 id="other-components-of-the-transformer">Other components of the transformer</h2> <p>There are a few other components to the transformer. We’ll cover <span style=" border: 4px solid black; background-color: rgb(183, 228, 244); color: black; padding: 0.1em 0.5em; border-radius: 8px; display: inline-block; text-align: center; font-size: 14px; "> Feed Forward </span>, positional encoding, <span style=" border: 4px solid black; background-color: rgb(239, 243, 188); color: black; padding: 0.1em 0.5em; border-radius: 8px; display: inline-block; text-align: center; font-size: 14px; "> Add &amp; Norm </span>, <span style=" border: 4px solid black; background-color: rgb(214, 218, 236); color: black; padding: 0.1em 0.5em; border-radius: 8px; display: inline-block; text-align: center; font-size: 14px; "> Linear </span>, and <span style=" border: 4px solid black; background-color: rgb(195, 228, 202); color: black; padding: 0.1em 0.5em; border-radius: 8px; display: inline-block; text-align: center; font-size: 14px; "> Softmax </span> next.</p> <h3 id="feed-forward-network">Feed forward network</h3> <p>Recall that the output of the attention mechanism is \(AV \in \mathbb{R}^{T \times D}\). At this point there is no nonlinearity, and so the model is limited in its representational capacity. We add a position-wise feed forward network with a single hidden layer, where \(x\) the attention output.</p> \[\begin{aligned} \mathrm{FFN}(x) &amp;= W_2\bigl(\sigma\bigl(W_1\,x + b_1\bigr)\bigr) + b_2, \\[6pt] W_1 &amp;\in \mathbb{R}^{H\times D}, \quad W_2 \in \mathbb{R}^{D\times H}, \\[6pt] \sigma(\cdot) &amp;: \quad (\text{activation function, e.g., ReLU or GELU}) \end{aligned}\] <p>This whole sequence \(AV\) followed by \(\mathrm{FFN}\) is repeated \(N_x\) times, where the sequence is considered a “block” and the output of \({block}_l\) becomes the input of \({block}_{l+1}\), in other words the model starts attending to its own feature representations.</p> <h3 id="positional-encoding">positional encoding</h3> <p>The attention mechanism treats each token independently. In other words, <em>it does not care or no about order</em>. This is known as a “bag of words” model because it’s as if the words were put in a bag and mixed up. This is a problem because the sentences “this is a bad bagel” and “is this a bad bagel” would be identical. Let’s take a look at an example.</p> <div class="jupyter-notebook" style="position: relative; width: 100%; margin: 0 auto;"> <div class="jupyter-notebook-iframe-container"> <iframe src="/assets/jupyter/2025-04-13-sequence_to_sequence_models_2/positional_encoding.ipynb.html" style="position: absolute; top: 0; left: 0; border-style: none;" width="100%" height="100%" onload="this.parentElement.style.paddingBottom = (this.contentWindow.document.documentElement.scrollHeight + 10) + 'px'"></iframe> </div> </div> <p>As we can see, when we did not use positional encoding the attention output <code class="language-plaintext highlighter-rouge">y_perm</code> is permuted in the same way as the input <code class="language-plaintext highlighter-rouge">x_perm</code>. Therefore, both orderings would be treated the same by the model.</p> <p>However, when we add a positional encoding by adding <code class="language-plaintext highlighter-rouge">positional_embedding</code> to <code class="language-plaintext highlighter-rouge">x</code>, then order matters since when we shuffle <code class="language-plaintext highlighter-rouge">x</code>, now the <code class="language-plaintext highlighter-rouge">positional_embedding</code> indicates the order and <code class="language-plaintext highlighter-rouge">y_with_pos</code> and <code class="language-plaintext highlighter-rouge">y_shuffle_with_pos</code> are different.</p> <p>The <code class="language-plaintext highlighter-rouge">positional_embedding</code> is just a learned embedding lookup for each token position. One concern is that the positional embedding must be learned and might not be well-trained for token positions that fall outside the normal range (e.g., unusually long sequences). <a class="citation" href="#10.5555/3295222.3295349">(Vaswani et al., 2017)</a> use a non-learned sinusoidal function to add positional information instead, but they didn’t notice any performance difference between the sinusoidal function vs. the positional embedding. Future models such as GPT-2 use positional embedding.</p> <p>Next, we’ll cover <span style=" border: 4px solid black; background-color: rgb(239, 243, 188); color: black; padding: 0.1em 0.5em; border-radius: 8px; display: inline-block; text-align: center; font-size: 14px; "> Add &amp; Norm </span>, which is two steps: layer normalization and residual connections.</p> <h3 id="layer-norm">layer norm</h3> <p>For certain types of models, including CNNs, batch normalization <a class="citation" href="#Ioffe_Szegedy_2015">(Ioffe &amp; Szegedy, 2015)</a> is typically used to stabilize the network, and this has been shown to decrease the number of iterations it takes a deep model to converge. Discussion about normalization techniques is outside the scope of this article, but I wanted to motivate why a different normalization technique is used for transformers than was previously used.</p> <p>If we were to apply batch normalization in one dimension for sequential text data where the shape is <code class="language-plaintext highlighter-rouge">(B, T, D)</code>, the normalization is applied for each feature over each <code class="language-plaintext highlighter-rouge">(B, T)</code>, yielding a <code class="language-plaintext highlighter-rouge">D</code>-dimension \(\mu\) and \(\sigma^2\) vector, containing the statistics for each feature over batch and time, as well as <code class="language-plaintext highlighter-rouge">D</code>-dimensional \(\gamma\) and \(\beta\) to scale and shift the distribution. Normalization is applied over the batch and time dimension:</p> \[\mu_d \;=\; \frac{1}{B\,T} \sum_{b=1}^{B}\sum_{t=1}^{T} x_{b,t,d} \qquad \sigma_d^2 \;=\; \frac{1}{B\,T} \sum_{b=1}^{B}\sum_{t=1}^{T} \bigl(x_{b,t,d}-\mu_d\bigr)^{2} \qquad \hat x_{b,t,d} \;=\; \frac{x_{b,t,d}-\mu_d}{\sqrt{\sigma_d^2}} \qquad y_{b,t,d} \;=\; \gamma_d\,\hat x_{b,t,d} + \beta_d\] <figure id="figure-16" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/batch_norm_1d.png" alt="embedding" style="width: 90%"/> <figcaption>Figure 16: BatchNorm1d </figcaption> </figure> <p>This is a problem for sequential text data for several reasons.</p> <ol> <li>Each token’s features represent different things, and it’s not natural to normalize over the features of different tokens.</li> <li>This cannot be used when sequences are of different lengths, since in that case the sequences are padded to the longest sequence in the mini-batch, and we don’t want to include padding features when computing statistics. We would have to mask this out somehow.</li> <li>At inference time when we decode the sequence sequentially, we’d be using running statistics that were calculated based on an entire sequence.</li> </ol> <p>For sequential text data, instead, we’d like to normalize each timestep individually, without the features from other timesteps being included. This is what <a class="citation" href="#Ba_Kiros_Hinton_2016">(Ba et al., 2016)</a> does. Instead of normalizing along the batch and time dimension as in BatchNorm1d, layer norm normalizes along each feature axis \(D\) for each timestep, resulting in a <code class="language-plaintext highlighter-rouge">D</code>-dimension \(\mu\) and \(\sigma^2\) vector, containing the statistics for each feature as well as <code class="language-plaintext highlighter-rouge">D</code>-dimensional \(\gamma\) and \(\beta\) to scale and shift the distribution, <em>for each timestep</em>. Every timestep in the batch is normalized individually:</p> \[\mu_{b,t} \;=\; \frac{1}{D} \sum_{d=1}^{D} x_{b, t,d} \qquad \sigma_{b,t}^2 \;=\; \frac{1}{D} \sum_{d=1}^{D} \bigl(x_{b, t,d}-\mu_{b,t}\bigr)^{2} \qquad \hat x_{b,t,d} \;=\; \frac{x_{b,t,d}-\mu_{b,t}}{\sqrt{\sigma_{b,t}^2 + \varepsilon}} \qquad y_{b,t,d} \;=\; \gamma_d\,\hat x_{b,t,d} + \beta_d\] <figure id="figure-17" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/layer_norm.png" alt="embedding" style="width: 90%"/> <figcaption>Figure 17: Layer Norm </figcaption> </figure> <p>Now we can normalize over each token individually, and so:</p> <ol> <li>Layer norm normalizes over each timestep individually, instead of including information from other timesteps.</li> <li>We can handle sequences of arbitrary lengths since we normalize each timestep individually.</li> <li>We don’t need to track running statistics, since each timestep is normalized on the fly.</li> </ol> <p>We can also see that experimentally, layer norm gives faster convergence for sequential text data, where in this case layer norm is used in a multimodal model to model images and captions:</p> <figure id="figure-18" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/layer_norm_faster_convergence.png" alt="embedding" style="width: 50%"/> <figcaption>Figure 18: Layer Norm faster convergence. Figure from <a class="citation" href="#Ba_Kiros_Hinton_2016">(Ba et al., 2016)</a>. </figcaption> </figure> <h3 id="residual-connections">residual connections</h3> <p>Residual connections (aka skip connections) allow information to flow through the network. <a class="citation" href="#He_resnet">(He et al., 2016)</a> observed that increasing the size of the network leads to worse training performance, which did not make sense, since deeper networks should be able to fit strictly more complex functions than shallower networks. He et al. observed this was because the signal was getting “lost.” Let’s look at a basic example.</p> <p>Consider \(y_1 = f_1(x)\) where \(f_1\), which is a blackbox function, and \(y_2 = f_2(y_1)\) which takes as input \(y_1\).</p> <p>We want to compute \(\frac{\partial y_2}{\partial x}\), i.e., how does an inner input affect the output, which is \(\frac{\partial y_2}{\partial x} = \frac{\partial f_2}{\partial y_1}\frac{\partial y_1}{\partial x}\) due to the chain rule.</p> <p>If the upstream gradient \(\frac{\partial f_2}{\partial y_1}\) is \(&lt;&lt; 1\) or 0, then \(\frac{\partial y_2}{\partial x}\) will be diluted or 0.</p> <p>Residual connections are beautifully simple but powerful. If instead of computing \(y_2 = f_2(y_1)\), we compute \(y_2 = y_1 + f_2(y_1)\), then</p> \[\begin{align*} \frac{\partial y_2}{\partial x} &amp;= (1 + \frac{\partial f_2}{\partial y_1})\frac{\partial y_1}{\partial x} \\ &amp;= \frac{\partial y_1}{\partial x} + \frac{\partial f_2}{\partial y_1}\frac{\partial y_1}{\partial x} \end{align*}\] <p>Notice that just by adding the input \(y_1\), we have made sure that the inner gradient is propagated without being diluted/zeroed out by the upstream gradient.</p> <p>Why are they called “residual” connections? Because now if the downstream layer \(f_2\) contributes meaningfully to the signal, then the term \(\frac{\partial f_2}{\partial y_1}\frac{\partial y_1}{\partial x}\) gets added to the gradient \(\frac{\partial y_1}{\partial x}\); otherwise we still propagate the inner term \(\frac{\partial y_1}{\partial x}\) which tells us how the input affected an earlier layer in the network.</p> <p>In the transformer we use residual connections in the following way:</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="n">self</span><span class="p">.</span><span class="nf">multi_head_attention</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">layer_norm</span><span class="p">[</span><span class="mi">0</span><span class="p">](</span><span class="n">x</span><span class="p">)</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="n">self</span><span class="p">.</span><span class="nf">mlp</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">layer_norm</span><span class="p">[</span><span class="mi">1</span><span class="p">](</span><span class="n">x</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">x</span>
</code></pre></div></div> <p>The input <code class="language-plaintext highlighter-rouge">x</code> is added to the output in order to propagate the gradient of the input. Notice that the gradient must flow through the layer norm. <a class="citation" href="#10.5555/3524938.3525913">(Xiong et al., 2020)</a> studied if it is better to allow the gradient of the input to flow without it being modified by the layer norm. The original transformer “between residual block” layer norm is referred to as “post-layer normalization,” while the approach by Xiong et al. is “pre-layer normalization.”</p> <p>In code the pre-layer normalization looks like</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="n">self</span><span class="p">.</span><span class="nf">multi_head_attention</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">layer_norm</span><span class="p">[</span><span class="mi">0</span><span class="p">](</span><span class="n">x</span><span class="p">))</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="n">self</span><span class="p">.</span><span class="nf">mlp</span><span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">layer_norm</span><span class="p">[</span><span class="mi">1</span><span class="p">](</span><span class="n">x</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">x</span>
</code></pre></div></div> <p><a class="citation" href="#10.5555/3524938.3525913">(Xiong et al., 2020)</a> found that placing the layer norm within the residual blocks allows for a faster convergence than if the layer norm is placed between the residual blocks. This is because when the layer norm is placed between the residual blocks, then the training requires a learning rate warmup to achieve good results. Without the warmup, training converges more quickly, and <a class="citation" href="#10.5555/3524938.3525913">(Xiong et al., 2020)</a> shows that learning rate warmup is not needed if we place the layer norm inside the residual blocks. The former approach is called <em>post-layer normalization</em> transformer while the latter is <em>pre-layer normalization</em> transformer.</p> <p>They have a nice picture showing this:</p> <figure id="figure-19" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/pre_vs_post_ln_residual_connections.png" alt="pre vs post ln" style="width: 50%"/> <figcaption>Figure 19: Pre vs post layer norm. Figure from <a class="citation" href="#10.5555/3524938.3525913">(Xiong et al., 2020)</a>. </figcaption> </figure> <p>Notice that compared to post-layer norm, here the gradient of <code class="language-plaintext highlighter-rouge">x</code> flows through without the gradient being modified by the layer norm. This is what yields faster convergence without learning rate warmup.</p> <p><a class="citation" href="#10.5555/3524938.3525913">(Xiong et al., 2020)</a> showed this experimentally, where we can see clearly that the pre-layer norm without warmup converges faster than the post-layer norm with warmup:</p> <figure id="figure-20" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/pre_vs_post_ln.png" alt="pre vs post ln" style="width: 90%"/> <figcaption>Figure 20: Pre vs post layer norm. Figure from <a class="citation" href="#10.5555/3524938.3525913">(Xiong et al., 2020)</a>. </figcaption> </figure> <p>Because of this, transformer architectures such as GPT adopted pre-layer norm (although with warmup, go figure)</p> <h3 id="putting-it-all-together">Putting it all together</h3> <p>We want the decoder to predict <em>the next token</em> \(y_{t+1}\) at each timestep \(t\). To do this, we shift each token 1 unit to the right and fill the token at \(t=0\) with a start of sequence token. The target sequence <code class="language-plaintext highlighter-rouge">[I, have, a, cat]</code> becomes <code class="language-plaintext highlighter-rouge">[&lt;sos&gt;, I, have, a, cat]</code> so that \(y_0\) is <code class="language-plaintext highlighter-rouge">&lt;sos&gt;</code>, \(y_1\) is <code class="language-plaintext highlighter-rouge">I</code>, etc.</p> <p>We feed the source sequence through the encoder, which produces an encoded representation, and the shifted target sequence through the decoder, which also makes use of the encoded representation of the source sequence using cross-attention. The output of this is a \(T \times D\) tensor. But we are not quite done. We need to learn to predict the target sequence from the source sequence. The \(T \times D\) tensor output by the decoder needs to be mapped to \(T \times C\) where \(C\) is the number of tokens in the vocabulary, and for that we’ll use a \(D \times C\) fully connected layer at the end, which is indicated by the <span style=" border: 4px solid black; background-color: rgb(214, 218, 236); color: black; padding: 0.1em 0.5em; border-radius: 8px; display: inline-block; text-align: center; font-size: 14px; "> Linear </span> box in the <a href="#transformer-architecture">Transformer architecture</a> diagram. Recall that the token embedding lookup maps \(C\) tokens to \(D\)-dimensional vectors. Because the final fully connected layer can be thought of as the opposite, mapping \(D\) to \(C\) instead of \(C\) to \(D\), we can reuse the weights from the embedding lookup. This saves a lot of extra parameters since \(D\) and \(C\) can be quite large. The logits from the fully connected layer are run through the <span style=" border: 4px solid black; background-color: rgb(195, 228, 202); color: black; padding: 0.1em 0.5em; border-radius: 8px; display: inline-block; text-align: center; font-size: 14px; "> Softmax </span> function to produce a probability distribution over tokens. We then backpropagate using cross-entropy over the \(C\) categories as the loss function.</p> <p>During inference, we will iteratively decode a single token at a time since we do not have a target sequence. After every iteration, we’ll add the decoded token to the decoded sequence to generate the translated sequence, and we’ll stop once we’ve predicted the end-of-sequence token or hit a maximum number of iterations.</p> <h1 id="experiments-and-results">Experiments and results</h1> <p>I implemented a transformer using the approach described in Vaswani et al., to reproduce results, and trained on the WMT ‘14 train set and tested on the WMT ‘14 test set. I was interested in reproducing results in the paper but also wanted to see how the runtime and performance of the model compares to the RNN. Why is the transformer considered a breakthrough? Transformers allow better parallelization than RNNs since we do not need to iterate through each token to process a sequence as in an RNN, but can instead process the entire sequence in parallel using tensor multiplication. So this ought to be more efficient, but how much more efficient? This efficiency, I think, is what enables transformers to perform much better than RNNs at scale since we can train on much larger datasets and models more quickly, and I think this is what allowed researchers to test the hypothesis of whether LLMs would “wake up” when the model size + data size increased. Without transformers, I don’t think we would have reached this paradigm shift.</p> <p>My primary interest was in reproducing the results reported in Vaswani et al.</p> <p>My secondary interest was in seeing how the transformer performance in terms of accuracy as well as runtime and scalability compares to the RNN performance.</p> <p>Lastly, the transformer architecture uses an encoder-decoder architecture; however, GPT and other LLMs use a decoder-only architecture. They use a decoder-only architecture since they train in a different self-supervised regime where they take a large amount of text and just try to predict the next token. This is different from the translation problem in which we want to take a sequence and predict an entire sequence correctly. But I was motivated to try using a decoder-only model for the problem of translation since a decoder-only model is simpler than an encoder-decoder. It also seems easy to frame the translation as predicting the next token rather than encoding the source sequence and then producing the translation.</p> <h2 id="dataset">Dataset</h2> <p>See <a href="https://aamster.github.io/blog/2024/sequence_to_sequence_models_1/#dataset">the previous post</a></p> <h2 id="model">Model</h2> <p>The model hyperparameters are the same as Transformer base in Vaswani et al.</p> \[\begin{array}{|c|c|c|c|c|c|} \hline d_{\text{model}} &amp; h &amp; P_{drop} &amp; d_{ff} &amp; N &amp; \epsilon_{ls} \\ \hline 512 &amp; 8 &amp; 0.1 &amp; 2048 &amp; 6 &amp; 0.1 \\ \hline \end{array}\] <p>where</p> <ul> <li>\(d_{model}\) is the hidden dim in every layer of the model</li> <li>\(h\) is the number of attention heads, and so the hidden dim in every head is \(512/8=64\)</li> <li>\(P_{drop}\) is the dropout</li> <li>\(d_{ff}\) is the feedforward hidden dim</li> <li>\(N\) is the number of blocks</li> <li>\(\epsilon_{ls}\) is the label smoothing strength</li> </ul> <p>A difference between my model and the transformer base model is that I used a separate vocabulary and embedding lookup for both the encoder and decoder, since that was the approach I followed for the RNN model. I used a vocab size of \(30,000\) for both the source and target languages, compared to a vocab size of \(32,000\) total vocabulary size used by Vaswani et al.</p> <p>The model had \(74M\) parameters compared to \(65M\) in transformer base, with the difference stemming from the \(60,000\) embedding vectors compared to \(32,000\).</p> <h2 id="training">Training</h2> <ul> <li>Byte-pair encoding was used for tokenization. See <a href="https://aamster.github.io/blog/2024/sequence_to_sequence_models_1/#tokenization">the previous post</a> for details.</li> <li>Data was split randomly into train/val using 99.9% of the data for train (4000 val examples)</li> <li>I used 3 nvidia V100 GPUs for 24 hours with a batch size of 128 (228,000 iterations).</li> <li>Cross-entropy loss was used, and the model’s weights were updated if the cross-entropy loss decreased.</li> <li>Training was done using float16 mixed precision using automatic mixed precision provided by pytorch (<code class="language-plaintext highlighter-rouge">torch.amp</code>)</li> <li>\(\text{AdamW}\) optimizer using cosine annealing with warmup learning rate scheduler was used. Warmup number of steps is \(2000\), min learning rate is \(6e^-5\), and the max learning rate is \(6e^-4\)</li> </ul> <h2 id="results-and-discussion">Results and discussion</h2> <table id="tbl-bleu"> <caption> The reproduced model achieves equivalent test-set performance as Transformer base. FLOPs calculation is using $$C = 6ND$$ per Kaplan et al. 2020. </caption> <thead> <tr> <th>Model</th> <th>Non-embedding Parameters</th> <th>FLOPs</th> <th>BLEU</th></tr> </thead> <tbody> <tr> <td>Transformer Base</td> <td>65M</td> <td>$$1.95 \times 10^{18}$$</td> <td>38.1</td></tr> <tr> <td>This model</td> <td>60M</td> <td>$$1.57 \times 10^{18}$$</td> <td>38.6</td> </tr> </tbody> </table> <p>The test set performance shows that we were able to achieve the same performance.</p> <p>From the plot of train/validation BLEU score, we can see that the model did not converge and could have continued training with increased performance.</p> <figure id="figure-21" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/encoder_decoder_perf.png" alt="masked self-attention" style="width: 90%"/> <figcaption>Figure 21: Transformer performance </figcaption> </figure> <h3 id="attention-examples">Attention examples</h3> <p>Let’s look at the encoder self-attention, and decoder-cross attention calculated by the model. I’m skipping decoder self-attention as I don’t speak French, and it is most likely similar in nature to the encoder self-attention. I’ve chosen the same running example from the test set “But why such optimism for some and pessimism for others?” → “Les raisons d’un tel optimisme, chez les uns, et pessimisme, chez les autres ?”.</p> <h4 id="encoder-self-attention">Encoder self-attention</h4> <p>I’ve broken down the self-attention by layer which can be toggled by the slider at the bottom, and each subplot is a single head of attention. The query tokens are on the left and key tokens on the right. The line weight indicates the attention weight ranging from \([0, 1]\).</p> <figure id="figure-22" style="text-align: center;"> <div id="encoder_self_attention_weights_plot_container" style="width: 100%"></div> <script>fetch("/assets/plotly/2025-04-13-sequence_to_sequence_translation_2/multi_head_encoder_self_attention_weights_0.json").then(t=>t.json()).then(t=>{Plotly.newPlot("encoder_self_attention_weights_plot_container",t.data,t.layout)})["catch"](t=>{console.error("Error loading Plotly data:",t)});</script> </figure> <p>Here’s what I notice, focusing on a couple layers for brevity:</p> <ul> <li>Layer 1 <ul> <li>In layer 1 the attention seems pretty diffuse where each token in general seems to be attending to every other token</li> </ul> </li> <li>Layer 2 <ul> <li>In layer 2 we start to see more specialized heads. In head 2 token \(j\) is attending to the previous token \(j-1\), and in head 4 token \(j\) attends to the next token \(j+1\).</li> <li>Interestingly, many of the tokens are attending to the end of sequence token <code class="language-plaintext highlighter-rouge">&lt;/s&gt;</code>.</li> </ul> </li> <li>Layer 6 <ul> <li>Head 7 <em>?</em> attends to <em>why</em></li> <li>Head 8 token \(j\) attends to itself</li> <li>Head 6 some tokens attend to another instance of itself elsewhere in the sequence, e.g., the first <em>for</em> attends to the 2nd <em>for</em>, or if no other instance is in the sequence, then it attends to itself</li> </ul> </li> </ul> <p>As we can see, the heads are performing different functions in terms of learning the structure of the sequence.</p> <h4 id="decoder-cross-attention">Decoder cross-attention</h4> <p>The following example is generated by collecting attention weights from the decoder during inference generation of the sequence.</p> <figure id="figure-23" style="text-align: center;"> <div id="decoder_cross_attention_weights_plot_container" style="width: 100%"></div> <script>fetch("/assets/plotly/2025-04-13-sequence_to_sequence_translation_2/multi_head_decoder_cross_attention_weights_0.json").then(t=>t.json()).then(t=>{Plotly.newPlot("decoder_cross_attention_weights_plot_container",t.data,t.layout)})["catch"](t=>{console.error("Error loading Plotly data:",t)});</script> </figure> <p>A few observations:</p> <ul> <li>Throughout all layers a significant amount of attention is given to the end of sequence token <code class="language-plaintext highlighter-rouge">&lt;/s&gt;</code>, particularly in early layers 1-3</li> <li>Some heads, e.g., head 7 in layer 3 align output tokens with the corresponding input token (Mais -&gt; But, porquois -&gt; why, etc). This makes sense and what I would expect the model to do for translation, since the output needs to be aligned with the input.</li> <li>Other heads, e.g., head 1 in layer 5 align output tokens with the corresponding input token that follows it (in the phrase “Mais porquois” (But why), “Mais” (but) attends to why,” etc.)</li> </ul> <p>Many of these observations on attention behaviors are not unique to this data/model but are found in other research and LLMs, such as in <a class="citation" href="#Clark_Khandelwal_Levy_Manning_2019">(Clark et al., 2019)</a> in which they also find that a significant amount of attention weight is placed on <em>[SEP]</em>, the token used to indicate a sequence boundary (similar to <code class="language-plaintext highlighter-rouge">&lt;/s&gt;</code> that I used). They argue that this is a “no-op” or a sort of fallback behavior. They also find that many heads do simple and similar things such as just attending to the previous or the next token.</p> <p>Contrary to what the paper observes, heads in the same layer don’t always perform the same function, e.g., head 2 and 4 in layer 2 of the encoder self-attention clearly perform previous token and next token alignment respectively.</p> <h3 id="transformer-vs-rnn-architecture">Transformer vs RNN architecture</h3> <p>One of the motivating reasons for studying the transformer was to try to understand the benefits it has over the RNN. We know that researchers and AI companies have adopted the transformer architecture for LLMs, and so we’d like to try to understand why LLMs weren’t built with a different architecture, such as the RNN.</p> <p>Here is a summary table comparing RNN with Transformer efficiency and performance.</p> <table> <thead> <tr> <th>Model</th> <th style="text-align: right">Parameter count<sup id="fnref:1"><a href="#fn:1" class="footnote" rel="footnote" role="doc-noteref">1</a></sup></th> <th style="text-align: right">Num. tokens processed<sup id="fnref:2"><a href="#fn:2" class="footnote" rel="footnote" role="doc-noteref">2</a></sup></th> <th style="text-align: right">Num. GPU hours<sup id="fnref:3"><a href="#fn:3" class="footnote" rel="footnote" role="doc-noteref">3</a></sup></th> <th style="text-align: right">GPU</th> <th style="text-align: right">FLOPs<sup id="fnref:4"><a href="#fn:4" class="footnote" rel="footnote" role="doc-noteref">4</a></sup></th> <th style="text-align: right">FLOP/s</th> <th>BLEU<sup id="fnref:5"><a href="#fn:5" class="footnote" rel="footnote" role="doc-noteref">5</a></sup></th> </tr> </thead> <tbody> <tr> <td>RNN</td> <td style="text-align: right">158M</td> <td style="text-align: right">6.1 B</td> <td style="text-align: right">159</td> <td style="text-align: right">nvidia V100</td> <td style="text-align: right">\(5.78 \times 10^{18}\)</td> <td style="text-align: right">\(1 \times 10^{13}\)</td> <td>.30</td> </tr> <tr> <td>Transformer</td> <td style="text-align: right">60M</td> <td style="text-align: right">4.37 B</td> <td style="text-align: right">30</td> <td style="text-align: right">nvidia V100</td> <td style="text-align: right">\(1.57 \times 10^{18}\)</td> <td style="text-align: right">\(1.45 \times 10^{13}\)</td> <td><strong>.38</strong></td> </tr> </tbody> </table> <h4 id="runtime-efficiency">runtime efficiency</h4> <p>First, which model ran faster? The RNN must process each token sequentially, while the transformer can process all tokens in parallel using matrix multiplications, and so we would expect the transformer to make better use of the hardware. Deep learning model’s runtime complexity is typically measured in terms of FLOPs (floating point operations), rather than using big-O notation as is typical for algorithms. Neural networks essentially do many adds and multiplies. A single add and a single multiply would count as 2 FLOPs. A matrix multiply \(AB\) where \(A\) is \([M, N]\) and \(B\) is \([N, P]\) would require \(2*M*N*P\) FLOPs. If \(A\) is \([49, 1]\) and \(B\) is \([1, 10000]\) then there are \(980,000\) FLOPs. Models that require more FLOPs are computationally more expensive.</p> <p>How are FLOPs calculated? In <a class="citation" href="#10.5555/3295222.3295349">(Vaswani et al., 2017)</a> they calculate FLOPs</p> <blockquote> <p>by multiplying the training time, the number of GPUs used, and an estimate of the sustained single-precision floating-point capacity of each GPU</p> </blockquote> <p>This relies on the floating point capacity of the GPU and assumes 100% or near 100% saturation of the GPU and is GPU-dependent. If the model doesn’t 100% saturate the GPU, then this calculation will be an overestimate.</p> <p>Later work <a class="citation" href="#Kaplan_McCandlish_Henighan_Brown_Chess_Child_Gray_Radford_Wu_Amodei_2020">(Kaplan et al., 2020)</a> derived that for most neural network models the number of FLOPs can be calculated as \(C=6ND\) where N is the number of parameters in the model and D is the number of inputs (see <a href="https://jax-ml.github.io/scaling-book/transformers/">this blog post</a> for an explanation). Using this method to estimate the number of FLOPs, the transformer performed \(1.57 \times 10^{18}\) of FLOPs while the RNN performed \(5.78 \times 10^{18}\) FLOPs. The transformer trained for 30 GPU hours and performed \(1.45 \times 10^{13}\) FLOP/s while the RNN trained for 159 GPU hours and performed \(1 \times 10^{13}\) FLOP/s, so <strong>the transformer was able to run 1.45x faster than the RNN</strong>.</p> <p>This is also supported by looking at GPU utilization logs. Since the transformer keeps the GPU busier by processing tokens in parallel, it is able to run more operations / second.</p> <figure id="figure-24" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/gpu_util.png" alt="gpu util" style="width: 60%"/> <figcaption>Figure 24: RNN vs. Transformer GPU utilization. The transformer keeps the GPU busier and more saturated. </figcaption> </figure> <h4 id="translation-quality">Translation quality</h4> <p>Recall that the RNN achieved <strong>30</strong> WMT’14 test set BLEU, while the transformer achieved <strong>38</strong> BLEU and so the transformer had better translation quality. It also did this with less data and with fewer weights. The RNN was trained on 6.1B tokens and contained 158M params, while the transformer only trained on 4.7B tokens and contained 60M params.</p> <p>So the transformer achieved significantly better translation quality using fewer parameters and 25% less data, and was 1.45x more efficient in terms of theoretical FLOP/s.</p> <h3 id="encoder-decoder-vs-decoder-only">Encoder-decoder vs decoder-only</h3> <p>The transformer architecture used by LLMs is largely the same as in the original transformer but with a few differences. The differences include:</p> <ul> <li>GELU activation function <a class="citation" href="#Hendrycks_Gimpel_2016">(Hendrycks &amp; Gimpel, 2016)</a> instead of ReLU</li> <li>layer norm within the residual block (pre-LN)</li> <li>additional layer norm before the final linear layer</li> <li>Decoder-only (no encoder)</li> </ul> <p>The first three are fairly simple architectural details that yield an improvement. The last difference, decoder-only vs. encoder-decoder, requires some explanation. In the original transformer paper, the transformer includes both an encoder and a decoder. The encoder encodes the source text while the decoder produces the output. This makes sense since there is a finite input (the input text) that must be understood to produce the output. However, LLM pretraining works by taking in a context of text and predicting the next token. This is what the decoder does in our encoder-decoder model. It takes as context the currently predicted sequence and predicts the next token. What if instead of just taking the target text or predicted text as context, it also prepended the source text? Then we can treat the entire source + target/predicted text as a single sequence and learn to predict the next token.</p> <figure id="figure-25" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/decoder.png" alt="decoder" style="width: 20%"/> <figcaption>Figure 25: Decoder (right half) of transformer encoder-decoder diagram </figcaption> </figure> <p>I largely followed <a class="citation" href="#Wang_Tu_Tan_Wang_Sun_Liu_2021">(Wang et al., 2021)</a> which had the same idea.</p> <figure id="figure-26" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/lm4mt.png" alt="lm4mt" style="width: 100%"/> <figcaption>Figure 26: Decoder-only model. Diagram from <a class="citation" href="#Wang_Tu_Tan_Wang_Sun_Liu_2021">(Wang et al., 2021)</a>. During training, the source and target texts are concatenated into a long sequence and the next token is predicted. During inference the source text is given as input, and the predicted text is concatenated to it. </figcaption> </figure> <p>As an example, if the following are the source and target texts, respectively, they would get concatenated into a single long input:</p> <p><strong>concatenated input:</strong> <em><code class="language-plaintext highlighter-rouge">&lt;source&gt;</code> Macedonian entrepreneurs and their descendants eventually employed their numerical strength within the food service industry as a catapult into a variety of larger and more sophisticated ventures. <code class="language-plaintext highlighter-rouge">&lt;target&gt;</code> Finalement, des entrepreneurs macédoniens et leurs descendants utiliseront la force du nombre dans l’industrie du service alimentaire comme un tremplin vers différentes entreprises plus perfectionnées et plus importantes.</em></p> <p>You’ll notice that the source and target texts are separated by a special language tag token, which <a class="citation" href="#Wang_Tu_Tan_Wang_Sun_Liu_2021">(Wang et al., 2021)</a> found to be beneficial.</p> <p>One concern is that the goal, remember, is to translate text. We want our measure of success to be how well the output aligns with the expected output. However, if we were to model the concatenated text next token prediction using cross-entropy loss, then we would also be tuning the model to predict the next token <em>in the source text as well as the target text</em>. We don’t care how well the model can predict the next token for the source text, but we do for the target text.</p> <p>For this reason <a class="citation" href="#Wang_Tu_Tan_Wang_Sun_Liu_2021">(Wang et al., 2021)</a> separated the loss into a multi-task loss with two parts. Recall that in the encoder-decoder, the loss is only measured on the target sequence as the cross-entropy loss</p> \[\mathcal{L}_{CE} = -\sum_{1}^{T}\text{log}P\bigl(y_t \mid \mathbf{x}, \mathbf{y}_{&lt;t}\bigr)\] <p>. However, in the decoder-only setting, the source and target are concatenated. <a class="citation" href="#Wang_Tu_Tan_Wang_Sun_Liu_2021">(Wang et al., 2021)</a> break up the loss into 2 parts: \(\mathcal{L}^{AE}\), the autoencoder loss which is defined as</p> \[\mathcal{L}^{AE} = -\sum_{1}^{S}\text{log}P\bigl(x_s \mid \mathbf{x}_{&lt;s}\bigr)\] <p>and the machine translation loss \(\mathcal{L}^{MT}\) which is defined as</p> \[\mathcal{L}^{MT} = -\sum_{1}^{T}\text{log}P\bigl(y_t \mid \mathbf{x}, \mathbf{y}_{&lt;t}\bigr)\] <p>where \(S\) is the number of tokens in the source sequence, \(T\) is the number of tokens in the target sequence, \(\mathbf{x}\) is the source sequence, and \(\mathbf{y}\) is the target sequence.</p> <p>The total loss \(\mathcal{L}\) is therefore</p> \[\mathcal{L} = \mathcal{L}^{AE} + \mathcal{L}^{MT}\] <p>This loss differs from the transformer loss \(\mathcal{L}_{CE}\) in that we’re computing loss on the source sequence as well as the target sequence.</p> <p>Since we’ve separated the loss into two parts, 1 for the source sequence and another for the target sequence, we can control each separately. Since the goal is translation, we might want to focus more on the \(\mathcal{L}^{MT}\) component at later stages in training. This is what <a class="citation" href="#Wang_Tu_Tan_Wang_Sun_Liu_2021">(Wang et al., 2021)</a> did, they added a term \(\lambda_d\) as a decay factor, which decays piecewise linearly using hyperparameters \(\alpha\) and \(\mathcal{B}\). The loss with the decay factor is then</p> \[\mathcal{L}_{decoder} = \lambda_d\mathcal{L}^{AE} + \mathcal{L}^{MT}\] <h4 id="experiments">Experiments</h4> <p>I compared the model using the transformer loss \(\mathcal{L}_{MT}\) with the model using the weighted multi-task loss \(\mathcal{L}_{decoder}\), and compared both of these with the encoder-decoder transformer. For an equal comparison, since the decoder doesn’t include an encoder, we make up for the lost parameters. <a class="citation" href="#Wang_Tu_Tan_Wang_Sun_Liu_2021">(Wang et al., 2021)</a> did this by increasing the depth of the network. I increased \(N\), the number of layers from 6 to 19. Note that, due to a bug, I originally miscalculated the number of params in the encoder-decoder as 74M instead of 60M, and so made the decoder-only model have 74M params instead of 60M. BLEU is reported on the WMT’14 test set.</p> <table id="tbl-decoder-only-vs-encoder-decoder"> <caption> Decoder-only vs encoder-decoder transformer BLEU scores. The decoder-only model using $$\mathcal{L}_{decoder}$$ outperforms the other models. </caption> <thead> <tr> <th>Model</th> <th>Num non-embed params</th> <th>Num layers</th> <th>Num epochs</th> <th>FLOPs</th> <th>BLEU</th> </tr> </thead> <tbody> <tr> <td>Encoder-decoder</td> <td>60M</td> <td>6</td> <td>2.16</td> <td>$$1.57 \times 10^{18}$$</td> <td>38.6</td> </tr> <tr> <td>Decoder-only with $$\mathcal{L}_{MT}$$</td> <td>76.28M</td> <td>19</td> <td>1.41</td> <td>$$2 \times 10^{18}$$</td> <td>37.3</td> </tr> <tr> <td>Decoder-only with $$\mathcal{L}_{decoder}$$</td> <td>76.28M</td> <td>19</td> <td>1.41</td> <td>$$2 \times 10^{18}$$</td> <td><b>38.7</b></td> </tr> </tbody> </table> <p>Decoder FLOP calculation: \(C = 6 \times 76.28M \times 3.1 \text{B tokens} \times 1.41\)</p> <p>The decoder-only using \(\mathcal{L}_{decoder}\) had the best performance, but performed ~400M more FLOPs than the encoder-decoder due to the parameter difference count. This shows that a decoder-only model, with a few minor adjustments can be used to get good performance on translation tasks. We didn’t test it, but also presumably just using \(\mathcal{L}_{CE}\) on the entire source + target sequence would do ok, since ChatGPT can translate very well with enough data:</p> <figure id="figure-27" style="text-align: center;"> <img src="/assets/img/2025-04-13-sequence_to_sequence_translation/chatgpt_translate.png" alt="chatgpt translate" style="width: 100%"/> <figcaption>Figure 27: Example chatgpt translation </figcaption> </figure> <p>which when translated back to English via Google Translate yields:</p> <blockquote> <p>The decoder-only model using the \mathcal{L}_{decoder} loss achieved the best performance. Note that we didn’t train it as long as the encoder-decoder, so we can expect better results if we had continued training for longer.</p> </blockquote> <h3 id="attention-weights">Attention weights</h3> <p>Finally, let’s look at some attention weights from the decoder-only model. The source text is given to the model as inference input, and the predicted tokens are iteratively added to the sequence. We collect the attention weights after completing the predicted sequence. Note that language tags <code class="language-plaintext highlighter-rouge">&lt;en&gt;</code> and <code class="language-plaintext highlighter-rouge">&lt;fr&gt;</code> are prepended to the english and French sequences respectively. Only showing weights &gt; 0.1 to reduce the number of lines drawn.</p> <figure id="figure-28" style="text-align: center;"> <div id="decoder_only_attn_weights_container" style="width: 100%"></div> <script>fetch("/assets/plotly/2025-04-13-sequence_to_sequence_translation_2/multi_head_decoder_attention_weights_0.json").then(t=>t.json()).then(t=>{Plotly.newPlot("decoder_only_attn_weights_container",t.data,t.layout)})["catch"](t=>{console.error("Error loading Plotly data:",t)});</script> </figure> <p>We can see some interesting patterns. Here are ones that stand out as the most obvious.</p> <p><strong>Layer 1, head 2</strong>: Some tokens just pay attention to itself while others either pay attention to the same token output previously, e.g. “for” and “for” or the target token is aligned with the source token, e.g. “et” and “and”</p> <p><strong>Layer 5, head 5</strong>: Previous token attention</p> <p><strong>Layer 6, head 1</strong>: Tokens that go together are aligned, e.g. “si-mis-m” attend to “pes” or “tel” attend to “un” in “un tel” meaning “such”</p> <p><strong>Layer 9, head 3</strong>: Many tokens attend to <code class="language-plaintext highlighter-rouge">&lt;en&gt;</code> tag, which seems like a “default” or no-op that we’ve seen previously. This trend is repeated throughout many layers/heads, e.g., layer 18 head 5 attends to both <code class="language-plaintext highlighter-rouge">&lt;en&gt;</code> and <code class="language-plaintext highlighter-rouge">&lt;fr&gt;</code> respectively.</p> <p>Overall, we see a mixture of the English sequence attending to its tokens, the French sequence attending to its tokens, and the French sequence attending to the English tokens. A significant number of layers/heads don’t contain useful signal and just attend to <code class="language-plaintext highlighter-rouge">&lt;en&gt;</code> and <code class="language-plaintext highlighter-rouge">&lt;fr&gt;</code>.</p> <h1 id="conclusion">Conclusion</h1> <p>We’ve looked at the transformer architecture and how it differs from the RNN architecture that preceded it. The transformer has better performance on the translation task but beyond translation, is the SOTA model for multi-modal understanding and generation. It makes better use the hardware for parallelism and so is faster and more scalable than the RNN architecture. We also looked at how the original encoder-decoder transformer architecture compares to decoder-only LLM architecture and showed that the decoder-only model can achieve similar performance as the encoder-decoder on the original translation task as well. This shows that the original transformer could be formulated as a modern decoder-only transformer without loss in performance.</p> <div class="footnotes" role="doc-endnotes"> <ol> <li id="fn:1"> <p>Excluding embedding layers <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;</a></p> </li> <li id="fn:2"> <p>The number of tokens processed is calculated as average tokens per iteration × number of iterations. <a href="#fnref:2" class="reversefootnote" role="doc-backlink">&#8617;</a></p> </li> <li id="fn:3"> <p>Only including train time, not inference/validation <a href="#fnref:3" class="reversefootnote" role="doc-backlink">&#8617;</a></p> </li> <li id="fn:4"> <p>FLOP calculation is \(C=6ND\) per Kaplan et al. 2020 (see <a href="https://jax-ml.github.io/scaling-book/transformers/">this blog post</a>). <a href="#fnref:4" class="reversefootnote" role="doc-backlink">&#8617;</a></p> </li> <li id="fn:5"> <p>WMT’14 test set BLEU <a href="#fnref:5" class="reversefootnote" role="doc-backlink">&#8617;</a></p> </li> </ol> </div>]]></content><author><name></name></author><category term="deep learning"/><category term="transformer"/><category term="machine translation"/><category term="sequences"/><summary type="html"><![CDATA[Introduction]]></summary></entry><entry><title type="html">Translation using deep neural networks - RNN (part 1)</title><link href="https://aamster.github.io/blog/2024/sequence_to_sequence_models_1/" rel="alternate" type="text/html" title="Translation using deep neural networks - RNN (part 1)"/><published>2024-10-03T00:00:00+00:00</published><updated>2024-10-03T00:00:00+00:00</updated><id>https://aamster.github.io/blog/2024/sequence_to_sequence_models_1</id><content type="html" xml:base="https://aamster.github.io/blog/2024/sequence_to_sequence_models_1/"><![CDATA[<p>In this article, I’ll introduce language modeling using deep learning and will focus on the problem of translation.</p> <p>I’ll cover how language was modeled using deep learning prior to transformers, which was by using recurrent neural networks (RNNs).</p> <p>I’ll compare <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a> which introduces the idea of <em>attention</em> in RNNs, with a paper published around the same time <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> which does not use attention. I’ll explain in detail what attention is and why it was introduced, as well as try to reproduce the results from these papers. The results from these papers are actually contradictory; <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> reported better performance than <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a>, however the latter is well known and influential for introducing attention. This is surprising to me, and shows that researchers found the idea of attention to be useful regardless of the performance reported in these papers.</p> <p>In the section <a href="#sequence-to-sequence-models">Sequence to sequence models</a>, I’ll give background on how to model problems where we take a sequence as input and output a sequence, with special attention (no pun intended) to the problem of translation. In <a href="#experiments-and-results">Experiments and results</a> I’ll reproduce <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> and <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a>. And in <a href="#implementation-details">Implementation details</a> I’ll cover technical details about how the models were implemented.</p> <p>All code for this article is available <a href="https://github.com/aamster/seq2seq-translation">here</a>.</p> <p>In the next article I’ll cover how language is modeled today using transformers.</p> <h2 id="introduction">Introduction</h2> <h3 id="avoiding-nlp">Avoiding NLP</h3> <p>In school, I always skipped over the natural language processing (NLP) topic for several reasons</p> <p>NLP used to be boring to me and language-specific where linguistics domain knowledge was needed. It involved steps such as</p> <ul> <li>tokenization (which is still needed but there wasn’t as good support for it before and it is annoying to implement),</li> <li>parts of speech tagging</li> <li>entities extraction</li> <li>…, etc</li> </ul> <p>The second reason why I avoided this topic is that I didn’t see much practical value in learning NLP. When would I ever need to build a chatbot or translation model?</p> <p>These reasons lead to me cringing everytime I saw “NLP” mentioned</p> <h3 id="language-modeling-today">Language modeling today</h3> <p>Turn to 2024 and language modeling is arguably the hottest topic in AI, so much so in fact that when some people say “AI” they are actually referring to language modeling.</p> <p>The models used for language modeling are also general purpose models that can handle any problem in which the data can be broken up into a finite sequence of tokens such as image understanding/generation, audio, biology (genomics), etc, and so language is just one use case of these models.</p> <h3 id="what-is-a-language-model">What is a language model?</h3> <p>Simply put a language model is a model that has learned to predict the next <strong>token</strong> given the previous <strong>tokens</strong>. The token is usually a word/subword/single character, but can be any discrete chunk of data that is part of a fixed vocabulary.</p> <h3 id="what-is-a-large-language-model">What is a large language model?</h3> <p>A large language model or LLM is a language model that has been trained on a ton of text and has many parameters (billions or trillions). Parameters are akin to the weights in biological neurons which determine whether they fire or not.</p> <h3 id="why-is-language-modeling-now-relevant-and-interesting">Why is language modeling now relevant and interesting?</h3> <p>Language models are part of a trend in AI of generative models. Generative models produce data, whereas historically machine learning models used to only predict a single variable, such as whether a review was good or the price of a house.</p> <p>Other types of generative models would cover the tasks of image generation, video generation, audio generation, and other kinds of generation. But this article will focus on language modeling.</p> <p>It is an understatement to say that generative models are a hot topic right now (mostly language models). It seems overnight companies are racing to build bigger and better models and other companies are racing to incorporate these models into their product offering. Schools are discussing whether to allow the use of LLMs or how to even prevent them from being used.</p> <p>We’ve seen that GPT-3.5+ models are incredibly powerful. They have seemingly limitless knowledge about seemingly all topics and can create and combine things in novel ways. When GPT-3.5 came out, most people discovered that it can write haikus, <a href="https://www.reddit.com/r/ChatGPT/comments/101huf7/prompt_please_write_a_breaking_news_article_about/">breaking news articles about falling leaves</a>, and get it to say other amusing and funny things.</p> <p>But language models are more than just haiku-generating machines. I frequently use GPT to figure out confusing things in code or an API I’m unfamiliar with, or to do tedius software engineering related things. I also find myself bouncing ideas off of GPT to get unstuck.</p> <p>There is also tremendous potential in teaching and education. While reading a book or watching a video, you can ask GPT to explain something to better understand it; this makes learning more interactive and effective.</p> <p>In research, many people are doing and have been doing amazing research. There is not even close to being enough time for anyone to keep up. Large language models can help surface and summarize research and help people navigate the idea landscape.</p> <p>Much of life can be tedious or confusing; large language models can hopefully serve as the “all knowing” guide and enhance our creativity and insight without us needing to sacrifice our autonomy or intelligence.</p> <h3 id="sequence-to-sequence-translation">Sequence to sequence translation</h3> <p>Translation has historically been a challenging task to automate and was used as a springboard for different AI research.</p> <p>I chose translation as the task to focus on for learning language modeling as 2 seminal papers in language modeling, which I’ll get to, also used translation as the task.</p> <p>The task of translation, as you may have guessed, involves translating an arbitrary document (word, sentence, paragraph, whatever) from 1 language into another.</p> <h3 id="why-is-translation-using-neural-networks-difficult">Why is translation using neural networks difficult</h3> <p>Translation using neural network models is challenging for several reasons.</p> <h4 id="language-involves-sequences-of-arbitrary-length">Language involves sequences of arbitrary length</h4> <p>According to <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a></p> <blockquote> <p>Despite their flexibility and power, DNNs [Deep Neural Nets] can only be applied to problems whose inputs and targets can be sensibly encoded with vectors of fixed dimensionality. It is a significant limitation, since many important problems are best expressed with sequences whose lengths are not known a-priori.</p> </blockquote> <p>Today, this issue seems like a non-issue. But back in 2014 this was seen as a novel problem to solve.</p> <p>Traditional machine learning operates on fixed length vectors, such as variables representing imporant features of a house (e.g. # of bedrooms, square footage, location, etc), the length of which is known in advance.</p> <p>Language is different in that sentences can be of arbitrary length. How to encode the sentences “I ate a cheese sandwhich” as well as “It is morning.” such that the model receives a fixed length input?</p> <h4 id="long-inputs">Long inputs</h4> <p>The paragraph</p> <blockquote> <p>It was cold outside so I wanted something warm to drink. I was out of tea so I thought to go to the store to buy some. My favorite kind of tea is matcha tea because of its health benefits. It was on sale so I bought some matcha tea. Drinking the tea really warms me up and gives me energy!</p> </blockquote> <p>contains a lot of information. How do we encode all this information so that we can know how to translate it?</p> <p>In fact, early models would do better at shorter sentences than longer ones because of this issue. The model was able to encode the meaning only for very short inputs but tended to not properly capture longer inputs.</p> <p><a class="citation" href="#cho-etal-2014-properties">(Cho et al., 2014)</a> analysis of early DNN translation models states:</p> <blockquote> <p>Our analysis shows that the performance of the neural machine translation model degrades quickly as the length of a source sentence increases.</p> </blockquote> <figure id="ChoBleuVsSentLen" style="text-align: center;"> <img src="/assets/img/2024-06-22-sequence_to_sequence_translation/rnn_enc_decreasing_perf_sent_len.png" alt="bleu vs sentence len"/> <figcaption>Figure 1: Figure from <a class="citation" href="#cho-etal-2014-properties">(Cho et al., 2014)</a>. Exponential dropoff in BLEU score (measure of translation quality) of deep neural network model as input/target length increases. </figcaption> </figure> <p>However, <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> states</p> <blockquote> <p>We were surprised to discover that the LSTM did well on long sentences</p> </blockquote> <figure id="figure-2" style="text-align: center;"> <img src="/assets/img/2024-06-22-sequence_to_sequence_translation/sutskever_sent_len.png" alt="Sutskever bleu vs sentence len"/> <figcaption>Figure 2: Figure from <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a>. LSTM (recurrent neural network model) performed well even on the longest inputs.</figcaption> </figure> <p>And then again in the seminal paper <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a>, which I’ll discuss in more detail later shows the same problem, that the model struggles with longer sentences:</p> <figure id="figure3" style="text-align: center;"> <img src="/assets/img/2024-06-22-sequence_to_sequence_translation/bhadanau_perf.png" alt="Bhadanau perf"/> <figcaption>Figure 3: Figure from <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a>. LSTM models without attention show exponential dropoff in BLEU score (translation quality) while the model with attention is stable across input lengths. </figcaption> </figure> <p>Notice how the performance (BLEU score, I’ll discuss in more detail in the section <a href="#measuring-performance-of-translation-tasks-bleu-score">Measuring performance of translation tasks: BLEU score</a>) degrades rapidly as the sentence length increases in the RNNenc-50 and RNNenc-30 models.</p> <p>So there is a discrepancy among these papers when discussing the problem of sentence length. Sutskever et al, 2014 say that the model performs well on long inputs, but Cho et al, 2014 and Bahdanau et al, 2014 say that the models are defficient when the input size increases. All these papers use the same dataset, WMT ‘14 for training and evaluation.</p> <p>The problem of sentence length would lead to the idea of attention in Bahdanau et al, 2014, which forms the basis for the transformer architecture.</p> <h4 id="vocabularies-are-large">Vocabularies are large</h4> <p>In language models, we have to turn the text into a series of <strong>tokens</strong>. Tokens are the smallest unit of input when using deep neural network models to model language.</p> <p>The vocabulary is then the set of possible tokens. We could just use single characters as the set of tokens, which would require a small vocabulary. However using single characters poses other difficulties as it would increase the input/output size if every character was modeled separately. We would like something flexible enough to handle individual characters as the smallest token, up to entire phrases. See <a class="citation" href="#Radford_Wu_Child_Luan_Amodei_Sutskever_2019">(Radford et al., 2019)</a> for this discussion.</p> <p>Vocabularies are large. According to the website <a href="https://www.opensourceshakespeare.org/statistics/">open source Shakespeare</a> there are 28,829 unique words in all of Shakespeare’s works, and apparently 40% of those words are used only once. That is a lot of words, but relatively modern LLMs (e.g. GPT2) use a token size of ~50,000 <a class="citation" href="#Radford_Wu_Child_Luan_Amodei_Sutskever_2019">(Radford et al., 2019)</a>, since these models need to understand more than just the vocabulary of Shakespeare.</p> <p>Large vocabulary sizes pose some challenges. The first is that once the data is tokenized, we typically will construct a vector of real numbers, as this is easier to model than simply providing an index. This vector is called an embedding vector and the set of embedding vectors for all tokens in the vocabulary the embedding matrix. A large vocabulary size means a large embedding matrix.</p> <p>Another challenge with a large vocabulary size is that when we predict each token at the decoding step, we typically use a linear transformation, which requires hidden \(\times\) number of tokens weights, which increases compute. For example if the hidden size in the decoder is \(1000\) and the number of tokens is \(30000\) then we would require \(1000 \times 30000 = 3e7\) weights (multiplications/additons) in this layer alone.</p> <p>Large vocabulary sizes also mean that we need a very large dataset in order to capture enough examples for every token in the vocabulary in order to train each token sufficiently. For example rarer tokens might be undertrained.</p> <h4 id="translation-is-difficult">Translation is difficult</h4> <p>The Hebrew sentence יש לי גרביים means “I have socks”.</p> <p>The literal translation is “There is to me socks”. This means that a language model cannot just learn a mapping between words. If the model needed to translate the english sentence “I have socks” to Hebrew, it cannot just look up the Hebrew word for “I”, which would be “אני”. It needs to know that the 2 words “I” followed by “have” get translated to the Hebrew “יש לי”. On the other hand if the sentence were “I am a man”, then “I” should get translated to “אני”.</p> <p>Another example would be translating the phrase “black cat” into spanish in which case it is “gato negro”. In other words when the model sees “black” it should output “gato” or “cat” and when it sees “cat” it should output “negro” or “black”.</p> <p>This is just scratching the surface as to why translation is difficult.</p> <h2 id="sequence-to-sequence-models">Sequence to sequence models</h2> <p>Translation involves taking in a sequence of text and producing a sequence of text. For example:</p> <p>Input:</p> <p>יש לי גרביים</p> <p>Output:</p> <p>I have socks.</p> <p>The way that we (humans) process language is by starting from the beginning and reading until the end.</p> <p>I—have—socks—.</p> <p>We mentally break up the sentence into chunks and process it sequentially in parts. We also need to understand the meaning of the sentence as a whole.</p> <p>When translating this sentence into a different language, after we mentally process the input, we then start producing the output one chunk at a time.</p> <p>יש—לי—גרביים</p> <p>So this involves 3 main steps:</p> <ol> <li>tokenize the input into a sequence of tokens</li> <li>process and condense/understand the input so that we can translate it</li> <li>use the condensed form from (2) to produce a translation token by token</li> </ol> <p>We would like a machine learning model that can do steps (2) and (3) above.</p> <p>The encoder-decoder architecture as proposed by<a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> does just this.</p> <p>The encoder processes and compresses the input into a meaningful representation, a fixed length vector. The decoder then takes this meaningful representation and then generates the output 1 token at a time.</p> <p>In <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> both the encoder and decoder are RNNs, (or more specifically a variant called LSTM). Let’s take a look at how an RNN works.</p> <h3 id="rnns">RNNs</h3> <p>The basic form of an RNN is the following, in pseudo-code:</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">VanillaRNN</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="n">self</span><span class="p">):</span>
        <span class="n">h_t</span> <span class="o">=</span> <span class="n">self</span><span class="p">.</span><span class="n">inital_state</span>
        <span class="n">outs</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="k">for</span> <span class="n">x_t</span> <span class="ow">in</span> <span class="n">seq</span><span class="p">:</span>
            <span class="n">h_t</span> <span class="o">=</span> <span class="nf">f</span><span class="p">(</span><span class="n">h_t</span><span class="p">,</span> <span class="n">x_t</span><span class="p">)</span>
            <span class="n">outs</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">h_t</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">outs</span><span class="p">,</span> <span class="n">h_t</span>

</code></pre></div></div> <p>In words, we initialize a “hidden state” or \(h_t\) of the RNN to the current state. We loop over every token in the input. For each token we calculate a function called \(f\) which takes as input the current token \(x_t\) as well as the current state \(h_t\). We append the current hidden state for timestep \(t\) to the list of outputs <code class="language-plaintext highlighter-rouge">outs</code>.</p> <p>In math, \(f\) takes a specific form.</p> \[h_t = f(h_t, x_t; W) = tanh(W_{hh}h_t + W_{xh}x_t + b_h)\] <p>The <strong>hidden state</strong>, \(h_t\) is what stores the compressed/meaningful representation of the sequence. Let’s look at how the hidden state is calculated.</p> <p>There are 2 weight matrices involved:</p> \[W_{hh}\in \mathbb{R}^{h \times h}\] \[W_{xh}\in \mathbb{R}^{x \times h}\] <p>as you can see \(W_{hh}\) is multiplied with \(h_t\), \(W_{xh}\) is multiplied with \(x_t\) and the 2 resulting vectors are added along with a bias.</p> <p>The resulting vector is then passed through the a function \(tanh\) which is just a function that maps \((-\infty, +\infty) \to (-1, 1)\). It looks like this:</p> <figure id="figure-4" style="text-align: center;"> <img src="/assets/img/2024-06-22-sequence_to_sequence_translation/Hyperbolic_Tangent.svg"/> <figcaption>Figure 4: tanh </figcaption> </figure> <p>that means that the hidden state is a vector \(h_t \in \mathbb{R}^h\) where each element is between \((-1, 1\))</p> <h4 id="example">example</h4> <p>Let’s look at a simple example using the sentence “I have socks.” as input, and pass it through the vanilla RNN.</p> <p>Let’s tokenize the sentence as [“I”, “have”, “socks”, “.”]</p> <p>Let the embedding vector be \(x \in \mathbb{R}^2\)</p> <p>Let the hidden state be \(h \in \mathbb{R}^3\).</p> <div class="jupyter-notebook" style="position: relative; width: 100%; margin: 0 auto;"> <div class="jupyter-notebook-iframe-container"> <iframe src="/assets/jupyter/2024-10-03-sequence_to_sequence_translation/vanilla_rnn.ipynb.html" style="position: absolute; top: 0; left: 0; border-style: none;" width="100%" height="100%" onload="this.parentElement.style.paddingBottom = (this.contentWindow.document.documentElement.scrollHeight + 10) + 'px'"></iframe> </div> </div> <p><strong>What has happened here?</strong></p> <p>First we split up the sequence “I have socks.” into tokens “I”, “have”, “socks”, “.”</p> <p>Then we mapped each token to a unique number using the variable <code class="language-plaintext highlighter-rouge">vocab</code> to map between token and number.</p> <p>For each token id we looked up an embedding vector. The embedding vector is a fixed length numeric vector and is a way to map each token to a vector of numbers, since the neural network can only take numeric values as input. It starts out randomly initialized and is learned during training.</p> <p>Mapping the sequence of tokens into a sequence of vectors gives us:</p> <figure id="figure-5" style="text-align: center;"> <img src="/assets/img/2024-06-22-sequence_to_sequence_translation/embedding.png" style="width: 50%"/> <figcaption>Figure 5: Mapping tokens to numeric vectors (embeddings) </figcaption> </figure> <p>We initialized the hidden state \(h_0 = \begin{bmatrix} 0 &amp; 0 &amp; 0 \end{bmatrix}\)</p> <p>then we iterated over each token, and updated the hidden state for each token.</p> <p>In detail:</p> <ol> <li>extract embedding vector for token “I”, \(x_1\), and update hidden state \(h_1\)</li> </ol> \[x_1 = \begin{bmatrix}-0.8330 &amp; -0.4121\end{bmatrix}\] \[h_1 = tanh(W_{hh}h_0 + W_{xh}x_1 + b_{hh} + b_{xh})\] \[h_1 = \begin{bmatrix}-0.3126 &amp; 0.5246 &amp; 0.6447\end{bmatrix}\] <ol> <li>extract embedding vector for token “have”, \(x_2\), and update hidden state \(h_2\)</li> </ol> \[x_2 = \begin{bmatrix}-1.1774 &amp; 0.7259\end{bmatrix}\] \[h_2 = tanh(W_{hh}h_1 + W_{xh}x_2 + b_{hh} + b_{xh})\] \[h_2 = \begin{bmatrix}0.0277 &amp; 0.3934 &amp; 0.8409\end{bmatrix}\] <ol> <li>extract embedding vector for token “socks”, \(x_3\), and update hidden state \(h_3\)</li> </ol> \[x_3 = \begin{bmatrix}0.5375 &amp; 0.0382\end{bmatrix}\] \[h_3 = tanh(W_{hh}h_2 + W_{xh}x_3 + b_{hh} + b_{xh})\] \[h_3 = \begin{bmatrix}-0.8055 &amp; -0.0275 &amp; 0.0972\end{bmatrix}\] <ol> <li>extract embedding vector for token “.”, \(x_4\), and update hidden state \(h_4\)</li> </ol> \[x_4 = \begin{bmatrix}-0.6446 &amp; -1.0341\end{bmatrix}\] \[h_4 = tanh(W_{hh}h_3 + W_{xh}x_4 + b_{hh} + b_{xh})\] \[h_4 = \begin{bmatrix}-0.2049 &amp; 0.3322 &amp; 0.3161\end{bmatrix}\] <p>After all this math, we get a final hidden state \(h_4\) and an output \(o\) which includes \(h_t\) for each timestep \(t\)</p> \[h_4 = \begin{bmatrix}-0.2049 &amp; 0.3322 &amp; 0.3161\end{bmatrix}\] \[o = \begin{bmatrix}-0.3126 &amp; 0.5246 &amp; 0.6447\\0.0277 &amp; 0.3934 &amp; 0.8409\\-0.8055 &amp; -0.0275 &amp; 0.0972\\-0.2049 &amp; 0.3322 &amp; 0.3161\end{bmatrix}\] <p>What do these numbers represent? The final hidden state \(h_4\) represents the RNN’s compressed/useful representation of the input sequence <em>I have socks.</em>. The outputs \(o_t\) represent the compressed/useful representation after processing token \(t\) and having processed the previous \(t-1\) tokens.</p> <p>The hidden state is reset to \(0\) each time it processes a new sequence.</p> <h4 id="why-recurrent-neural-network">Why “recurrent” neural network</h4> <p>Why are RNNs called “recurrent” neural networks?</p> <p>The name “recurrent” in “recurrent neural network” comes from the fact that the hidden state \(h_{t-1}\) is recursively used to calculate the new hidden state \(h_t\)</p> <p>If we unpack a single update of \(\textcolor{blue}{h_t}\), we get:</p> \[\textcolor{blue}{h_t = tanh(W_{hh}\textcolor{lime}{h_{t-1}} + W_{xh}x_t + b_{hh} + b_{xh})}\] <p>if we unpack \(\textcolor{lime}{h_{t-1}}\) we get:</p> \[\textcolor{lime}{h_{t-1} = tanh(W_{hh}\textcolor{orange}{h_{t-2}} + W_{xh}x_{t-1} + b_{hh} + b_{xh})}\] <p>Plugging this into the previous equation, we get:</p> \[\textcolor{blue}{h_t = tanh(W_{hh}(}\textcolor{lime}{tanh(W_{hh}\textcolor{orange}{h_{t-2}} + W_{xh}x_{t-1} + b_{hh} + b_{xh})}\textcolor{blue}{) + W_{xh}x_t + b_{hh} + b_{xh})}\] <p>If we unpack this for one more timestep, \(\textcolor{orange}{h_{t-2}}\) would be \(\textcolor{orange}{h_{t-2} = tanh(W_{hh}h_{t-3} + W_{xh}x_{t-2} + b_{hh} + b_{xh})}\)</p> <p>Plugging in \(\textcolor{orange}{h_{t-2}}\) we get:</p> \[\textcolor{blue}{h_t = tanh(W_{hh}(}\textcolor{lime}{tanh(W_{hh}(}\textcolor{orange}{tanh(W_{hh}h_{t-3} + W_{xh}x_{t-2} + b_{hh} + b_{xh})}\textcolor{lime}{) + W_{xh}x_{t-1} + b_{hh} + b_{xh})}\textcolor{blue}{) + W_{xh}x_t + b_{hh} + b_{xh})}\] <p>The full recursive equation would be:</p> \[h_t = tanh(W_{hh}(tanh(W_{hh}(...tanh(W_{hh}h_0 + W_{xh}x_1 + b_{hh} + b_{xh})...) + W_{xh}x_{t-1} + b_{hh} + b_{xh})) + W_{xh}x_t + b_{hh} + b_{xh})\] <ul> <li>The calculation of the hidden state \(\textcolor{blue}{h_t}\) involves the previous \(t-1\) hidden states \(\textcolor{lime}{h_{t-1}}, \textcolor{orange}{h_{t-2}}, ... h_{0}\)</li> <li>The hidden state calculation \(\textcolor{blue}{h_t}\) involves each of the previous \(t-1\) tokens in the sequence \(\textcolor{lime}{x_{t-1}}, \textcolor{orange}{x_{t-2}}, ... x_{0}\). This enables the model to “see” the entire sequence.</li> <li>The weights and biases \(W_{hh}\), \(W_{xh}\), \(b_{hh}\), \(b_{xh}\) are used repeatedly when processing the sequence for each hidden state \(h_t\)</li> <li>There are a lot of matrix-matrix multiplications (\(\textcolor{blue}{W_{hh}} * \textcolor{lime}{W_{hh}} * \textcolor{orange}{W_{hh}}\)). This can lead to very large numbers (exploding gradients) or very small numbers (vanishing gradients)</li> </ul> <p class="box-note"><strong>Note:</strong> This is showing the forward pass of a simple RNN using a single training example. The model would actually be trained on many examples, and the model parameters \(W_{hh}\), \(W_{xh}\), \(b_{hh}\), \(b_{xh}\) would be trained using backpropagation.</p> <h4 id="more-complicated-architectures">More complicated architectures</h4> <p>There are various issues with this simple “vanilla RNN” architecture that people have worked on addressing over the years, and there are other improvements to increase complexity and expressiveness.</p> <p>Mentioned above is the issue that because there are many matrix-matrix multiplications, the simple RNN has the issue of vanishing and exploding gradients which prevent the network from learning well. People have worked on addressing this issue by introducing <a href="https://pytorch.org/docs/stable/generated/torch.nn.LSTM.html">LSTM</a> and <a href="https://pytorch.org/docs/stable/generated/torch.nn.GRU.html">GRU</a> and these variants are used in practice instead of the simple RNN. These fix the issue of vanishing gradients; exploding gradients are usually handled by thresholding the gradients if the norm is larger than a certain value.</p> <p>To increase the model expressiveness, you can stack multiple RNNs together where the output from 1 is given as the input to the next. Set <code class="language-plaintext highlighter-rouge">num_layers</code> argument <code class="language-plaintext highlighter-rouge">&gt;1</code> in pytorch to do this.</p> <p>It might also be useful to process a sequence in the forwards direction and in the backwards direction. To do this, you can use 2 RNNs: 1 that processes the sequence forwards and the other backwards. Set <code class="language-plaintext highlighter-rouge">bidirectional=True</code> in pytorch to do this.</p> <h3 id="encoder-decoder-architecture">Encoder-decoder architecture</h3> <p>So far we’ve discussed how an RNN can be used to process the source sequence. What about translation? To do translation, we have to add an additional step.</p> <p>The proposed architecture is the so-called encoder-decoder architecture. The idea is that an RNN processes the input sequence, as we’ve shown above. Then another RNN, the “decoder”, takes the hidden state of the “encoder” RNN as input and tries to predict the correct translated token at each timestep. From <a class="citation" href="#DBLP:conf/emnlp/ChoMGBBSB14">(Cho et al., 2014)</a>:</p> <blockquote> <p>The proposed neural network architecture, which we will refer to as an RNN Encoder–Decoder, consists of two recurrent neural networks (RNN) that act as an encoder and a decoder pair. The encoder maps a variable-length source sequence to a fixed-length vector, and the decoder maps the vector representation back to a variable-length target sequence. The two networks are trained jointly to maximize the conditional probability of the target sequence given a source sequence.</p> </blockquote> <p>Here is a picture of what that would look like for the sequence “I have socks.” -&gt; יש לי גרביים</p> <figure id="figure6" style="text-align: center;"> <img src="/assets/img/2024-06-22-sequence_to_sequence_translation/encoder_decoder.png"/> <figcaption>Figure 6: Encoding/decoding "I have socks." -&gt; יש לי גרביים </figcaption> </figure> <p>You’ll notice a few things from this picture of the encoder-decoder architecture for translation.</p> <ul> <li>The encoder and decoder look similar. They are both separate RNNs that are connected to each other and trained together. Each have separate hidden states.</li> <li>The inputs to each timestep \(t\) in the decoder are the <span style="color:rgb(245,66,213)">context vector</span> as well as the <span style="color:rgb(0,103,20)">previous token</span>.</li> <li>The <span style="color:rgb(245,66,213)">context vector</span> is the last hidden state \(h_t\) in the encoder (the encoder’s representation after processing the entire input sequence). The same <span style="color:rgb(245,66,213)">context vector</span> is used for each timestep \(t\) in the decoder</li> <li>At each step in the decoder we predict the correct token \(\hat{y_{t}}\) and compare it with the <span style="color:rgb(0,103,20)">correct token</span> at that timestep</li> </ul> <p class="box-note"><strong>Note:</strong> \(\hat{y_{t}}\) is calculated using the <a href="https://en.wikipedia.org/wiki/Softmax_function">softmax</a> function over every possible token in the target vocabulary. For example, if there are 10,000 possible tokens in the target language vocabulary, then \(\hat{y_{t}}\) will be of size 10,000. We then calculate \(argmax\) over this vector to choose the most confident token at that timestep.</p> <p class="box-note"><strong>Note:</strong> both the encoder and decoder networks are trained end-to-end using backpropagation using the <a href="https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html">cross-entropy</a> loss function</p> <p class="box-note"><strong>Note:</strong> At inference time we use the previously predicted token \(\hat{y}_{t-1}\) rather than the truly <span style="color:rgb(0,103,20)">correct token</span> at each timestep \(t\)</p> <h3 id="attention">attention</h3> <p>You might have noticed that the entire input sequence is compressed into what is called the <strong>context vector</strong>. The decoder must rely on all of the meaning of the input sequence being encoded into the context vector in order to produce the translation.</p> <p>In the example sentence</p> <blockquote> <p>I have socks.</p> </blockquote> <p>it might be possible to properly represent this in a fixed length vector.</p> <p>But what if the sentence was</p> <blockquote> <p>I have socks that are thick and made of wool because it is cold outside; it is comfortable to wear around the house while I look outside at the white snow gently falling to the ground.</p> </blockquote> <p>It might be difficult to encode all of the meaning into a fixed length vector representation of numbers so that the decoder can produce a correct translation. It is sort of like the game of “telephone”; the meaning and nuances would be lost in translation.</p> <p>This is the same pattern that <a class="citation" href="#cho-etal-2014-properties">(Cho et al., 2014)</a> observed, see <a href="#ChoBleuVsSentLen">Figure 1</a></p> <p>The bleu score on the vertical axis is a measure of translation quality, which I’ll discuss later in the article. Notice how as sentence length increases there is an exponential dropoff in translation quality.</p> <p><a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a> addressed this in their now famous paper “NEURAL MACHINE TRANSLATION BY JOINTLY LEARNING TO ALIGN AND TRANSLATE”.</p> <p>This paper is cited as the paper that introduced attention in neural networks. Attention is the backbone of the transformer architecture which is the architecture used to train LLMs, so it’s sort of a big deal.</p> <p>In <a href="#figure3">Figure 3</a>, they compared an encoder-decoder model without attention, as we’ve discussed above, with a model using attention.</p> <p>RNNenc-* is the same model we looked at before. We can see a similar dropoff in translation quality as the sentence length increases.</p> <p>Compare this to RNNsearch-* which is a model with attention. Both RNNsearch models have better performance, and interestingly, the RNNsearch-50 model shows no sign of decrease in performance as the sentence length increases.</p> <h4 id="what-is-attention">what is attention?</h4> <p>Attention, as the name implies is giving the model the ability to pay attention to certain parts of the input.</p> <p>While <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a> was the paper to popularize the idea of attention, it was refined and simplified in <a class="citation" href="#10.5555/3295222.3295349">(Vaswani et al., 2017)</a>, and the latter is what is typically used. I’ll go over both versions of attention.</p> <h4 id="bahdanau-additive-attention">Bahdanau (additive) attention</h4> <p>Let \(s_{i-1}\) be the previous hidden state in the decoder</p> <p>Let \(h_j\) be the hidden state in the last layer of the encoder RNN at each timestep \(j\)</p> <p>Bahdanau attention adds 3 new parameters:</p> \[W_a \in \mathbb{R}^{n \times n}\] \[U_a \in \mathbb{R}^{n \times 2n}\] \[v_a \in \mathbb{R}^{n}\] <p>where \(n\) is the hidden state dimensionality in both the encoder and decoder (must be the same) and \(U_a\) is n x <em>2n</em> because the encoder was bidirectional in the paper.</p> <p>Then the attention weights \(a\) can be calculated by taking as input the decoder previous hidden state \(s_{i-1}\) and the hidden state in the last layer of the encoder RNN at each timestep \(j\) as:</p> \[a(s_{i-1}, h_j) = {v_a}^Ttanh(W_as_{i-1} + U_ah_j)\] <h5 id="how-does-this-give-the-model-the-ability-to-pay-attention-to-certain-parts-of-the-input">How does this give the model the ability to pay attention to certain parts of the input?</h5> <p>We are taking the current decoder hidden state \(s_{i-1}\) when processing token at timestep \(i\) and adding it to the hidden state in the encoder at each timestep \(j\) \(h_j\). That is why this form of attention is referred to as “additive” attention.</p> <p>The result of \(a(s_{i-1}, h_j)\) will be \(\in \mathbb{R}^{t}\) where \(t\) is the number of tokens in the input sequence.</p> <p>It will look like:</p> <figure id="figure-7" style="text-align: center;"> <img src="/assets/img/2024-06-22-sequence_to_sequence_translation/attention_weights.png" style="width: 50%"/> <figcaption>Figure 7: attention weights </figcaption> </figure> <p>We then map the numbers to a probability distribution using the <em>softmax</em> function. The attention weights will then look like:</p> <figure id="figure-8" style="text-align: center;"> <img src="/assets/img/2024-06-22-sequence_to_sequence_translation/attention_weights_softmax.png" style="width: 50%"/> <figcaption>Figure 8: attention weights passed through the softmax function </figcaption> </figure> <p>This has the interpretation of “which tokens in the input are most important for outputting the current token in the decoder?”</p> <p>Note that we use a probability distribution rather than a hard cutoff when determining which tokens are important. Some tokens may be less important than others, but have some importance.</p> <h4 id="scaled-dot-product-attention">Scaled dot-product attention</h4> <p>When people today refer to “attention” they are generally referring to the scaled dot-product attention rather than the previously discussed additive attention. There are several reasons for this.</p> <p>You may have noticed that the additive attention is not that straightforward. Why are we adding the decoder hidden state with the encoder hidden state at each timestep?</p> <p><a class="citation" href="#10.5555/3295222.3295349">(Vaswani et al., 2017)</a> in their influential paper “Attention is all you need” reformulate attention to be the following, which is the basis of the transformer architecture.</p> \[attention(Q, K, V) = softmax(\frac{QK^T}{\sqrt{d_k}})V\] <p>This is similar to the previously discussed additive attention but with a few key differences.</p> <p>The query \(Q\) is the current vector we are asking the question “what should we be paying attention to?”. The keys \(K\) are the set of vectors, or matrix, which are the options to pay attention to. The values \(V\) is the set of vectors, or matrix, that each key maps to.</p> <p>In the case of translation using the RNN encoder-decoder model, the query \(Q\) is the current decoder hidden state of dimension \(d_q\). The keys are the encoder outputs which get mapped to the dimension \(d_{t \times {d_q}}\) and the values are also the encoder outputs mapped to the dimension \(d_{t \times {d_v}}\)</p> <p>The idea is that we want to find which <em>keys</em> \(K\) in the input the current <em>query</em> \(Q\) should attend to. This is computed as the dot product between \(Q\) and \(K\). The dot product has the theoretical interpretation as the similarity between 2 vectors.</p> <p>We are multiplying the query \(Q\) of dimension \(q\) with \(K^T\) of dimension \({q \times t}\). The resulting vector is of dimension \(t\).</p> <p>This is then divided by \(\sqrt{d_k}\), and hence the name “scaled” in “scaled dot-product” since we are scaling the dot-product by \(\sqrt{d_k}\). The reason for this is given as</p> <blockquote> <p>We suspect that for large values of \(d_k\), the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients. To counteract this effect, we scale the dot products by \(\sqrt{d_k}\).</p> </blockquote> <p>We then take the <em>softmax</em>, resulting in a probability for each timestep \(t\).</p> <p>Finally, we multiply this by the matrix \(V\). The resulting vector is of size \(d_v\) and each element is a weighted sum of importances calculated from the attention weights in the previous step.</p> <h4 id="how-is-attention-different-from-the-previous-encoder-decoder-approach">How is attention different from the previous encoder-decoder approach?</h4> <p>In <a href="#figure6">Figure 6</a> we showed an encoder-decoder architecture in which a <strong>context vector</strong> is passed to each decoding step. We noted that this context vector is computed from the output of the encoder and is the same at every decoding step. We noted that this has the potential problem that the entire input must be encoded into a single meaningful representation.</p> <p><strong>Attention</strong> tries to fix this problem by figuring out what the most relevant bits of the input are for each decoding step. In the example long input that we made up above</p> <blockquote> <p>I have socks that are thick and made of wool because it is cold outside; it is comfortable to wear around the house while I look outside at the white snow gently falling to the ground.</p> </blockquote> <p>when we are translating at the end the word “snow”, maybe “socks that are thick and made of wool” is less relevant than “white” and “gently falling”.</p> <p>In this way the attention mechanism allows us to pay attention to only the relevant parts of the input for each decoding step, and so we don’t have to construct a single meaning of the entire input.</p> <h3 id="measuring-performance-of-translation-tasks-bleu-score">Measuring performance of translation tasks: BLEU score</h3> <p>How do we measure the correctness of a machine-translated output?</p> <p>We could hire native speakers and/or professional translators to look at and rate the translation qualities. But looking at and judging the quality would take a very long time and be very costly. It also wouldn’t be reproducible if multiple different algorithms should be compared against a benchmark dataset.</p> <p>Let’s take a stab at a naive translation quality algorithm.</p> <p>Let’s say the correct translation is</p> <blockquote> <p>In my dresser I have socks.</p> </blockquote> <p>but our model outputs</p> <blockquote> <p>I have socks.</p> </blockquote> <p>We can see that the model’s output is partially correct. So maybe if we were to score the correctness of the translation we’d like it be be considered partially correct but not completely correct, and not completely incorrect.</p> <p>If we were to just match up each word with the correct word</p> <p>In -&gt; I</p> <p>my -&gt; have</p> <p>dresser -&gt; socks</p> <p>We would give this a score of 0, since no word matches up. In fact it is exceedingly rare for 2 translations to match a given translation exactly.</p> <p>BLEU score is the standard metric used to evaluate translation models. It was proposed in <a class="citation" href="#10.3115/1073083.1073135">(Papineni et al., 2002)</a>. The goal of the BLEU score is to be automated and to correlate with how well a human would judge the translation quality of a given translation to be.</p> <p>See this interesting figure in the paper in which the authors found the bleu score to correlate with how bilingual humans rated the quality of a translation:</p> <figure id="figure-9" style="text-align: center;"> <img src="/assets/img/2024-06-22-sequence_to_sequence_translation/bleu_human_correlation.png"/> <figcaption>Figure 9: Figure from <a class="citation" href="#10.3115/1073083.1073135">(Papineni et al., 2002)</a>. BLEU score correlates with bilingual judgement of translation quality. </figcaption> </figure> <p>At a high level, the bleu score computes an average of precisions for \(n\)-grams up to a certain \(n\).</p> <p>Let’s take a look at an example</p> <h4 id="example-1">example</h4> <div class="jupyter-notebook" style="position: relative; width: 100%; margin: 0 auto;"> <div class="jupyter-notebook-iframe-container"> <iframe src="/assets/jupyter/2024-10-03-sequence_to_sequence_translation/bleu_score.ipynb.html" style="position: absolute; top: 0; left: 0; border-style: none;" width="100%" height="100%" onload="this.parentElement.style.paddingBottom = (this.contentWindow.document.documentElement.scrollHeight + 10) + 'px'"></iframe> </div> </div> <p>The bleu score for the prediction <code class="language-plaintext highlighter-rouge">I have socks.</code> when the reference translation is <code class="language-plaintext highlighter-rouge">In my dresser I have socks.</code> is \(0.47\). The bleu score ranges between \([0, 1]\) and so a bleu score of \(0.47\) is decent but not perfect.</p> <p>Let’s break down the calculation further. We calculate <code class="language-plaintext highlighter-rouge">precision</code> scores for \(n\)-grams up to \(n\), in this case 4. <em>Precision</em> is defined as \(\frac{TP}{TP + FP}\), in other words the number of \(n\)-grams that we predict in our translation that are correct.</p> <p>\(1\)-grams</p> <ul> <li>Prediction unigrams: {I, have, socks, .}</li> <li>Reference unigrams: {In, my, dresser, I, have, socks, .}</li> <li>Total unigrams in prediction: 4</li> <li>Unigram precision: \(p_1\) = \(\frac{4}{4} = 1.0\)</li> </ul> <p>\(2\)-grams</p> <ul> <li>Prediction bigrams: {I have, have socks, socks .}</li> <li>Reference bigrams: {In my, my dresser, dresser I, I have, have socks, socks .}</li> <li>Total bigrams in prediction: 3</li> <li>Bigram precision: \(p_2\) = \(\frac{3}{3} = 1.0\)</li> </ul> <p>\(3\)-grams</p> <ul> <li>Prediction trigrams: {I have socks, have socks .}</li> <li>Reference trigrams: {In my dresser, my dresser I, dresser I have, I have socks, have socks .}</li> <li>Total trigrams in prediction: 2</li> <li>Trigram precision: \(p_3\) = \(\frac{2}{2} = 1.0\)</li> </ul> <p>\(4\)-grams</p> <ul> <li>Prediction 4-grams: {I have socks .}</li> <li>Reference 4-grams: {In my dresser I, my dresser I have, dresser I have socks, I have socks .}</li> <li>Total 4-grams in prediction: 1</li> <li>4-gram precision: \(p_4\) = \(\frac{1}{1} = 1.0\)</li> </ul> <p>So in this case all the \(n\)-gram precisions up to \(4\) are \(1.0\). But the translation is not perfect, so how do we penalize it?</p> <p>A brevity penalty is calculated. The way it is calculated is outside of the scope of this article. See the <a class="citation" href="#10.3115/1073083.1073135">(Papineni et al., 2002)</a> for the equation. In this case the brevity penalty is \(0.47\). The brevity penalty is multiplied with the \(n\)-gram precisions to get a final bleu score of \(0.47\).</p> <h4 id="bleu-score-problems">Bleu score problems</h4> <p>However, the bleu score is not a perfect metric.</p> <ul> <li> <p>Implicit in the bleu score calculation is that the text has been tokenized. For example, <code class="language-plaintext highlighter-rouge">I have socks.</code> is tokenized as <code class="language-plaintext highlighter-rouge">[I, have, socks.]</code>. This is not the only way to tokenize, as we’ll see later. This could lead to differences in bleu score calculation across papers.</p> </li> <li> <p>It does not take into consideration semantics. Let’s say the reference translation is <code class="language-plaintext highlighter-rouge">I have a hamburger in my bag</code>. Candidate translation 1 is <code class="language-plaintext highlighter-rouge">I have a sandwhich in my bag</code>, and candidate translation 2 is <code class="language-plaintext highlighter-rouge">I have a dolphin in my bag.</code> They would both have the same bleu score, while we can see that candidate 2 is nonsense while candidate 1 is close.</p> </li> <li> <p>It was designed for English translations. Translations in other languages may not have the same “similar n-gram matches correlates with human-judgement of translation quality” property.</p> </li> <li> <p>If one of the n-gram matches is 0, the bleu score is undefined since \(log(0)\) is undefined. It is usually set to 0 in this case. For example, the translation <code class="language-plaintext highlighter-rouge">I have socks.</code> with reference <code class="language-plaintext highlighter-rouge">I have socks in my dresser.</code> would have a bleu score of 0 since the \(4\)-gram has precision of 0. This is not a good property since it is clearly a close translation. This can be fixed by adding 1 to all n-gram precisions, but it’s not clear whether papers use this approach.</p> </li> </ul> <p>See <a href="https://huggingface.co/spaces/evaluate-metric/bleu">this page</a> for more discussion of limitations.</p> <p>Regardless, bleu score is the standard for evaluating machine translations in an automated way.</p> <h2 id="experiments-and-results">Experiments and results</h2> <p>Now I’ll actually implement both the RNN encoder-decoder model from <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> and the RNN encoder-decoder model with attention from <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a>, evaluate it on the English to French translation task of the <a class="citation" href="#bojar-etal-2014-findings">(Bojar et al., 2014)</a> (WMT’14) dataset, and compare results to the papers.</p> <h3 id="dataset">Dataset</h3> <p>In <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> and <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a>, they use the <a class="citation" href="#bojar-etal-2014-findings">(Bojar et al., 2014)</a> (Workshop on Machine Translation a.k.a WMT’14) English-French parallel corpora dataset which contains the following:</p> <ul> <li>Europarl <ul> <li>Professional translations of European parliment</li> </ul> </li> <li>News Commentary <ul> <li>Translations of news articles</li> </ul> </li> <li>UN <ul> <li>Translations from the UN meetings</li> </ul> </li> <li>Crawled corpora <ul> <li>Presumably random text on the web translated into different languages</li> </ul> </li> </ul> <p>The breakdown on the number of reported tokens per each dataset is:</p> <table> <thead> <tr> <th style="text-align: left">Dataset</th> <th style="text-align: left">Num. words</th> </tr> </thead> <tbody> <tr> <td style="text-align: left">Europarl</td> <td style="text-align: left">61M</td> </tr> <tr> <td style="text-align: left">News Commentary</td> <td style="text-align: left">5.5M</td> </tr> <tr> <td style="text-align: left">UN</td> <td style="text-align: left">421M</td> </tr> <tr> <td style="text-align: left">Crawled corpora</td> <td style="text-align: left">362.5M</td> </tr> </tbody> </table> <p>They use a technique (Cho et al, 2014) to filter down to a total of <strong>348M</strong> words for training. I did not follow this selection technique.</p> <p>They use a test set of <em>3003</em> sentences for testing.</p> <p>Here’s an example from the <strong>Europarl dataset</strong>:</p> <p>French:</p> <blockquote> <p>Même si cet idéal est encore loin d’être atteint, je voudrais exprimer la satisfaction de l’Union européenne de voir l’élection du Belarus au Conseil des droits de l’homme empêchée avec succès au mois de mai.</p> </blockquote> <p>English:</p> <blockquote> <p>Although this ideal is still far from having been achieved, I should like to express the satisfaction of the European Union that the election of Belarus to the Human Rights Council was successfully thwarted in May.</p> </blockquote> <p>and from the <strong>News Commentary dataset</strong>:</p> <p>French:</p> <blockquote> <p>Si l’on s’inquiète de cette possibilité, l’or pourrait en effet être la couverture la plus fiable.</p> </blockquote> <p>English:</p> <blockquote> <p>And if you are really worried about that, gold might indeed be the most reliable hedge.</p> </blockquote> <h3 id="model">Model</h3> <p>I used an encoder-decoder model using a GRU in both the encoder and decoder. The encoder is bidirectional. The hidden state size in the forward and backward directions of the encoder is \(1000\) and in the decoder is \(1000\). The embedding dimensionality in both the encoder and decoder is \(1000\). Both the encoder and decoder have \(4\) layers. For attention, I used the scaled dot-product attention with \(d_v\) equal to \(1000\). The source vocab size and target vocab size were set to \(30,000\). The models with attention and without attention contains ~\(189M\) trainable params.</p> <p>For comparison, <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> used LSTM instead of GRU. The vocab sizes were much larger at \(160,000\) for the source and \(80,000\) for the target. Their model contain \(384M\) params. To the best of my knowledge the attention model implemented is approximately equal to <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a>, but they leave out some implementation details, so I cannot say for sure.</p> <h3 id="training-details">Training details</h3> <ul> <li>I used 3 nvidia V100 GPUs to train both the model with attention and model without attention.</li> <li>Both models were trained for up to 3 epochs, or 72 hours, whichever came first. The model with attention completed ~3 epochs in 72 hours, while the model without attention completed 3 epochs.</li> <li>\(AdamW\) optimizer using cosine annealing with warmup learning rate scheduler was used. Warmup number of steps is \(2000\), min learning rate is \(6e^{-5}\) and max learning rate is \(6e^{-4}\)</li> <li>Cross entropy loss was used between the output sequence of tokens with highest probabilty and the target.</li> </ul> <h3 id="results">Results</h3> <p>Results are reported on the WMT’14 test set which contained 3003 english-french pairs.</p> <table> <thead> <tr> <th style="text-align: left">Model</th> <th style="text-align: left">Average BLEU score</th> </tr> </thead> <tbody> <tr> <td style="text-align: left"><a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> (Single reversed LSTM, beam size 12)</td> <td style="text-align: left">0.306</td> </tr> <tr> <td style="text-align: left">With attention</td> <td style="text-align: left">0.297</td> </tr> <tr> <td style="text-align: left"><a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a> (RNNsearch-50*, All words)</td> <td style="text-align: left">0.285</td> </tr> <tr> <td style="text-align: left">Without attention</td> <td style="text-align: left">0.261</td> </tr> </tbody> </table> <p>The model with attention achieved an overall higher average BLEU score than the model without attention. The model with attention achieved a better performance than <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a> (RNNsearch-50*, All words), while the model without attention achieved worse performance than <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> (Single reversed LSTM, beam size 12).</p> <p>Note that the model with attention, <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a> (RNNsearch-50*, All words), has a worse reported BLEU score than <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> (Single reversed LSTM, beam size 12).</p> <p>One of the key questions we wanted to answer was whether the model without attention suffers when the input lengths increase. The following figure compares BLEU score for the model with attention vs without as the input length increases.</p> <figure id="figure-10" style="text-align: center;"> <div id="attention_vs_no_attention_sent_len_plot_container" style="width: 100%"></div> <script>fetch("/assets/plotly/2024-10-03-sequence_to_sequence_translation/attention_vs_no_attention_sent_len.json").then(t=>t.json()).then(t=>{Plotly.newPlot("attention_vs_no_attention_sent_len_plot_container",t.data,t.layout)})["catch"](t=>{console.error("Error loading Plotly data:",t)});</script> <figcaption>Figure 10: Number of input tokens vs BLEU score for the model using attention and the model without attention on the WMT'14 test set. Both models showed increase in BLEU score as the number of input tokens increased. The scatter points are the actual BLEU score for each example, while the lines are lines of best fit to the data. Note that this figure agrees with <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> but disagrees with <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a> since the latter reports a decrease in performance in non-attention model with an increase in number of tokens, whereas we don't see this trend. </figcaption> </figure> <p>We are not able to reproduce a decrease in performance as the number of input tokens increases as <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a> and others showed. <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> showed that their model without attention is robust to an increase in sentence length even without attention, which is the same trend we were able to reproduce.</p> <h3 id="random-examples">Random examples</h3> <p>Let’s look at a few randomly chosen translations from the test set.</p> <h4 id="example-1">example 1</h4> <table> <thead> <tr> <th style="text-align: left">Input</th> <th style="text-align: left">With attention Prediction</th> <th style="text-align: left">Without attention Prediction</th> <th style="text-align: left">Target</th> </tr> </thead> <tbody> <tr> <td style="text-align: left">California planners are looking to the system as they devise strategies to meet the goals laid out in the state’s ambitious global warming laws.</td> <td style="text-align: left">Les planificateurs de la Californie se tournent vers le système lorsqu’ils élaborent des stratégies pour atteindre les objectifs énoncés dans les lois ambitieuses de l’État sur le réchauffement planétaire.</td> <td style="text-align: left">Les planificateurs californiens se tournent vers le système pour mettre au point des stratégies visant à atteindre les objectifs énoncés dans la législation ambitieuse du réchauffement de la planète.</td> <td style="text-align: left">Les planificateurs de Californie s’intéressent au système puisqu’ils élaborent des stratégies pour atteindre les objectifs fixés dans les lois ambitieuses de l’État sur le réchauffement climatique.</td> </tr> </tbody> </table> <p>While I don’t speak French, plugging in both predictions into Google Translate produces:</p> <p><strong>With attention</strong></p> <blockquote> <p>California planners are turning to the system as they develop strategies to meet the goals set out in the state’s ambitious global warming laws.</p> </blockquote> <p><strong>Without attention</strong></p> <blockquote> <p>California planners are looking to the system to develop strategies to meet goals set out in ambitious global warming legislation.</p> </blockquote> <p>Both are close, but the translation with attention is better as it produces <ins>the goals</ins> rather than <ins>goals</ins> and also the translation without attention misses the important phrase <ins>the state’s</ins>. Also the word <em>legislation</em> is awkward and <em>laws</em> is better.</p> <h4 id="example-2">example 2</h4> <table> <thead> <tr> <th style="text-align: left">Input</th> <th style="text-align: left">With attention Prediction</th> <th style="text-align: left">Without attention Prediction</th> <th style="text-align: left">Target</th> </tr> </thead> <tbody> <tr> <td style="text-align: left">“Despite losing in its attempt to acquire the patents-in-suit at auction, Google has infringed and continues to infringe,” the lawsuit said.</td> <td style="text-align: left">“Malgré la perte dans sa tentative d’acquérir les brevets en cours d’enchère, Google a enfreint et continue de violer”, a déclaré la poursuite.</td> <td style="text-align: left">“En dépit de sa perte dans l’acquisition des brevets en cours aux enchères, Google a enfreint et continue de violer”, a-t-il poursuivi.</td> <td style="text-align: left">« Bien qu’ayant échoué dans sa tentative d’acquérir les brevets en cause au cours des enchères, Google a violé et continue à violer lesdits brevets », ont indiqué les conclusions du procès.</td> </tr> </tbody> </table> <p><strong>With attention</strong></p> <blockquote> <p>“Despite losing its bid to acquire the patents in the auction, Google has infringed and continues to infringe,” the suit said.</p> </blockquote> <p><strong>Without attention</strong></p> <blockquote> <p>“Despite its loss in the pending patent auction, Google has infringed and continues to infringe,” he continued.</p> </blockquote> <p>We see a similar pattern as before. The model with attention pretty much gets it right, while the model without attention adds the word <ins>pending</ins> to <em>patent auction</em> which is incorrect, and ends with <ins>he continued</ins> which is incorrect and should be <em>the lawsuit said</em>.</p> <h4 id="example-3">example 3</h4> <table> <thead> <tr> <th style="text-align: left">Input</th> <th style="text-align: left">With attention Prediction</th> <th style="text-align: left">Without attention Prediction</th> <th style="text-align: left">Target</th> </tr> </thead> <tbody> <tr> <td style="text-align: left">He also said that a woman and child had been killed in fighting the previous evening and had been buried.</td> <td style="text-align: left">Il a également déclaré qu’une femme et un enfant avaient été tués dans les combats de la soirée précédente et avaient été enterrés.</td> <td style="text-align: left">Il a également déclaré qu’une femme et un enfant avaient été tués au cours de la nuit précédente et avaient été enterrés.</td> <td style="text-align: left">Selon lui, une femme et son enfant ont été tués par les combats de la veille et ont été enterrées.</td> </tr> </tbody> </table> <p><strong>With attention</strong></p> <blockquote> <p>He also said that a woman and a child had been killed in the fighting the previous evening and had been buried.</p> </blockquote> <p><strong>Without attention</strong></p> <blockquote> <p>He also said that a woman and a child had been killed during the previous night and had been buried.</p> </blockquote> <p>The model with attention gets it right while the model without attention misses the important phrase <ins>in the fighting</ins> and adds the slightly awkward <ins>during</ins>.</p> <h3 id="looking-at-attention-weights">Looking at attention weights</h3> <p>Attention, as described above, give the decoder the ability to give different weights to different tokens in the input. We can inspect these weights to understand better which input tokens each decoding timestep is “paying attention to”.</p> <figure id="figure-11" style="text-align: center;"> <div id="attention_weights_plot_container" style="width: 100%"></div> <script>fetch("/assets/plotly/2024-10-03-sequence_to_sequence_translation/attention_weights.json").then(t=>t.json()).then(t=>{Plotly.newPlot("attention_weights_plot_container",t.data,t.layout)})["catch"](t=>{console.error("Error loading Plotly data:",t)});</script> <figcaption>Figure 11: Attention weights for 4 randomly chosen examples in the WMT'14 test set with input lengths between 10 and 20 tokens. The model output tokens are on the horizontal axis and the input tokens on the vertical. The value of each cell indicates how strongly a given decoding timestep "paid attention to" a given input token. </figcaption> </figure> <p>Above is a figure showing 4 randomly chosen examples from the WMT’14 test set which have input lengths between 10 and 20 tokens. We can see that the attention weights are mostly linear. For example in the top left subplot we can see that at timestep \(1\), the model most strongly pays attention to the english token <em>_But</em> to produce the french token <em>_Mais</em>, and at timestep \(2\) the model most strongly pays attention to <em>_why</em> to produce the french token <em>_porquois</em>.</p> <p>However there are deviations from this. For example in the bottom left subplot we can see that the english phrase <em>phone calls</em> gets translated to the french <em>appels téléphoniques</em>, which literally translates to <em>calls phone</em>, and we can see that when outputting <em>appels</em>, the input token <em>calls</em> is most strongly paid attention to, while when outputting <em>téléphoniques</em>, <em>phone</em> is most strongly paid attention to.</p> <p>Sometimes, we can see that a given token in the input is paid attention to by multiple timesteps in the decoder. For example, in the bottom right subplot we can see that the input <em>returned</em> is paid attention to by the phrase <em>les gens sont revenus</em> or in english <em>the people returned</em>. So in addition to paying attention to <em>revenus</em> when outputting the literal translation <em>returned</em>, the model is paying attention to <em>returned</em> when outputting the entire phrase <em>les gens sont revenus</em>. This shows that the surrounding phrase is helpful here.</p> <p>We can see another case where the model outputs multiple tokens which maps to a single input token. In the top left subplot the output tokens, <em>_l</em>, <em>‘</em>, <em>_autorité</em> all pay attention to the input token <em>_authority</em>, and which is a good property since <em>authority</em> gets split up into the 3 french tokens <em>l, ‘, _autorité</em>.</p> <h3 id="failure-mode-examples">Failure mode examples</h3> <p>It’s useful to look at examples where the model performs poorly.</p> <table> <thead> <tr> <th style="text-align: left">Input</th> <th style="text-align: left">With attention Prediction</th> <th style="text-align: left">Without attention Prediction</th> <th style="text-align: left">Target</th> </tr> </thead> <tbody> <tr> <td style="text-align: left">I should say that I am rather sociable and have a job with responsibilities. I laugh and sing, I go out, I’m a grandmother, I have lots of friends, but my heart and my soul belong to him. I never talk about him except with my son, and I never go to the cemetery.</td> <td style="text-align: left">Je dois dire que je suis plutôt sociable et j’ai un travail avec des responsabilités.</td> <td style="text-align: left">Je dois dire que je suis assez sociable et qu’il est un homme qui a des devoirs, je rentre et j’essaie de chanter, je suis une grand-mère, j’ai beaucoup d’amis, mais mon cœur et moi-même l’âme, je n’en parle qu’à mon fils, mais</td> <td style="text-align: left">Je tiens à préciser que je suis sociable avec un métier à responsabilité, je ris et je chante, je sors, je suis grand-mère, j’ai plein d’amis, mais mon cœur et mon âme lui appartiennent et je ne parle jamais de lui sauf avec mon fils, et je ne vais jamais au cimetière.</td> </tr> </tbody> </table> <p>Interesting, it looks like the model is having trouble because there are multiple sentences separated with “.”, which is not common in the dataset. Each sentence is supposed to be split. The model has trouble with this and stops at the first period.</p> <p>This is a failure mode that would definitely need to be worked on, possibly by splitting on period and translating each sentence separately.</p> <h2 id="implementation-details">Implementation details</h2> <p>I’ll now go through the nitty-gritty of some of the implementaton details.</p> <h3 id="tokenization"><a name="tokenization"></a>Tokenization</h3> <p>In <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a>, tokenization was treated as an after-thought. They say</p> <blockquote> <p>After a usual tokenization, …</p> </blockquote> <p>However I soon realized that tokenization is an important topic and can influence the model in many ways. Curious what SOTA LLMs use, I found that it is more common to use an algorithm called Byte-pair encoding algorithm, for example as discussed in <a class="citation" href="#Radford_Wu_Child_Luan_Amodei_Sutskever_2019">(Radford et al., 2019)</a>.</p> <h4 id="byte-pair-encoding-algorithm">Byte-pair encoding algorithm</h4> <p>As mentioned previously, tokenization is the way by which we feed the inputs to the model. Unfortunately, there is no way currently to feed the inputs directly to the model. The inputs must be chunked into discrete <strong>tokens</strong>.</p> <p>Traditionally, inputs might be tokenized by breaking up into words or characters.</p> <p>For example in the sentence</p> <blockquote> <p>I have socks.</p> </blockquote> <p>it might be tokenized as <code class="language-plaintext highlighter-rouge">['I', ' ', 'have', ' ', 'socks', '.']</code></p> <p>but it could also be tokenized as <code class="language-plaintext highlighter-rouge">['I', ' ', 'h', 'a', 'v', 'e', ' ', 's', 'o', 'c', 'k', 's', '.']</code></p> <p>The “vocabulary” is then the set of possible tokens. One problem is that not every word encountered might be represented in the vocabulary. Traditionally, rare words or given the token “UNKOWN” so as to limit the vocabulary, and to handle tokens not seen in the training set. However this is not great; we’d like the model to be able to handle anything without defaulting to an UNKNOWN token.</p> <p>Splitting on words is not great as that introduces a bias. In deep learning we like the model to learn the raw signal without human intervention and splitting on words is somewhat of a human intervention. Splitting on characters is better, but introduces other problems as discussed in <a class="citation" href="#Radford_Wu_Child_Luan_Amodei_Sutskever_2019">(Radford et al., 2019)</a>.</p> <p>One idea is to feed the model UTF-8 bytes directly. However, for each character, 1-4 bytes are used in UTF-8. We would have a vocabulary of size 256 (\(2^8\) possible tokens can be modeled with a single byte). In this case the input size would explode in some cases since for each character we are using 1-4 tokens. For english tokens just a single byte is used but for characters in other languages and special tokens such as math, up to 4 bytes are used. This is a problem computationally, and so we would like the inputs to be somewhere on the spectrum of “word-level tokenization”, “character-level tokenization”, and “UTF-8 byte level representation”.</p> <p><a class="citation" href="#Radford_Wu_Child_Luan_Amodei_Sutskever_2019">(Radford et al., 2019)</a> (GPT-2 paper) adopted the BPE (byte-pair encoding) algorithm, which allows for a middle ground between these representations, and solves the issue of being able to model any possible character.</p> <p>The BPE algorithm in short converts a “training set”, which is possibly a sample of text used to train for the problem we’re working on, or a completely different set of text, to UTF-8 bytes. As mentioned, this is a vocabulary of size 256. We want to expand the vocabulary.</p> <p>Then, the most common pairs of bytes are merged. These merges get added to the vocabulary.</p> <p>This continues until the vocabulary gets to a certain size, which is a hyperparameter.</p> <p>Note that this solves the problems mentioned above. We are using a byte-level representation, but for common sequences of bytes, such as common words, we are representing those as a single token. For characters not in the training set, those are left as individual bytes, which can be achieved by using <code class="language-plaintext highlighter-rouge">byte_fallback=True</code> in the <code class="language-plaintext highlighter-rouge">sentencepiece</code> algorithm.</p> <p class="box-note"><strong>Side note:</strong> The BPE algorithm was originally developed as a <a href="https://web.archive.org/web/20160326130908/http://www.csse.monash.edu.au/cluster/RJK/Compress/problem.html">compression algorithm</a> in 1994.</p> <h4 id="implementation-of-bpe">Implementation of BPE</h4> <p>OpenAI has released their <a href="https://github.com/openai/tiktoken">BPE algorithm</a> but it can only be used for inference.</p> <p>The <a href="https://github.com/google/sentencepiece">sentencepiece algorithm</a> is similar to the above implementation, and was used for Meta’s LLama 2. It has a very efficient training implementation, so this is what I used.</p> <p>See the excellent overview of BPE and sentencepiece by Andrej Karpathy</p> <iframe width="560" height="315" src="https://www.youtube.com/embed/zduSFxRajkE?si=M2xaub0-iBADHwnY" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen=""></iframe> <h3 id="using-multiple-gpus">Using multiple GPUs</h3> <p>To train on multiple GPUs, the <code class="language-plaintext highlighter-rouge">torch.nn.parallel.DistributedDataParallel</code> package in pytorch was used. Since it was the first time using it, I’ll explain briefly how it works.</p> <p>At a high level, the model is duplicated across the GPUs, each running in a separate process. When the backward pass is completed, the gradients are synced with a master process. The updated gradients then sync with the other processes.</p> <p>To use <code class="language-plaintext highlighter-rouge">DistributedDataParallel</code>, we just need to wrap the pytorch model in <code class="language-plaintext highlighter-rouge">DistributedDataParallel</code>:</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">model</span> <span class="o">=</span> <span class="nc">DistributedDataParallel</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">device_ids</span><span class="o">=</span><span class="p">[...])</span>
</code></pre></div></div> <p>To make use of DDP, we can use the <code class="language-plaintext highlighter-rouge">torchrun</code> command line utility in pytorch. It assists in launching multiple processes and setting environment variables.</p> <p>Important envionrment variables are <code class="language-plaintext highlighter-rouge">RANK</code> and <code class="language-plaintext highlighter-rouge">LOCAL_RANK</code>. <code class="language-plaintext highlighter-rouge">RANK</code> is the global identifier for the process, and <code class="language-plaintext highlighter-rouge">LOCAL_RANK</code> is the local identifier for a process. <code class="language-plaintext highlighter-rouge">torchrun</code> can launch processes across machines, in which case these will be different, but on the same machine they will be the same. <code class="language-plaintext highlighter-rouge">device_ids</code> should be the <code class="language-plaintext highlighter-rouge">LOCAL_RANK</code>.</p> <p class="box-note"><strong>Note:</strong> Only log and check validation performance from the master process (the one where <code class="language-plaintext highlighter-rouge">RANK == 0</code>)!</p> <h3 id="padding">Padding</h3> <p>During development of the model I experienced a strange issue that took all day to debug. I’ll first describe why padding is needed, the issue I encountered, and then the solution.</p> <p>When training we construct minibatches to parallelize the computation. We must pass a single tensor to the model, and so all sequences must be made to be the same length. This means that if the sequences are different lengths, then we need to add a special token to any sequence which is shorter than the longest sequence.</p> <p>Let’s say we had this minibatch:</p> <figure id="figure-12" style="text-align: center;"> <img src="/assets/img/2024-06-22-sequence_to_sequence_translation/padding.png" style="width: 80%"/> <figcaption>Figure 12: Example minibatch with padding </figcaption> </figure> <p>The 3 padding tokens in the 1st sequence are required because the 1st sequence is shorter than the 2nd sequence.</p> <h4 id="the-issue">the issue</h4> <p>What I encountered is that when I passed the 1st sequence as is with the 3 padding tokens through the encoder-decoder, the output translation was one thing. But when I removed the padding tokens, and just passed the sequence by itself without padding tokens, I got a totally different translation.</p> <p>This to me was a bad sign. The model should not be sensitive to the padding tokens; they should be ignored. Their only purpose should be to make the sequences in the minibatch the same length and shouldn’t have any meaning.</p> <h4 id="the-solution">the solution</h4> <p>Padding affects the model in a few ways.</p> <p>The 1st way is when we encode the input sequences in the minibatch, the RNN must iterate through each token in the sequence, including the pad tokens. We would like for the encoder to learn that the pad tokens are irrelevent, which is what I thought would happen with enough data. But clearly this was not the case. How can we force the encoder to ignore the pad tokens?</p> <p>It turns out in pytorch there is function to force RNNs to ignore the pad tokens.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">packed_embedded</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="n">nn</span><span class="p">.</span><span class="n">utils</span><span class="p">.</span><span class="n">rnn</span><span class="p">.</span><span class="nf">pack_padded_sequence</span><span class="p">(</span>
    <span class="nb">input</span><span class="o">=</span><span class="nb">input</span><span class="p">,</span>
    <span class="n">lengths</span><span class="o">=</span><span class="n">input_lengths</span><span class="p">,</span>
    <span class="n">batch_first</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
    <span class="n">enforce_sorted</span><span class="o">=</span><span class="bp">False</span>
<span class="p">)</span>
</code></pre></div></div> <p>Given the tensor with the pad tokens, and the lengths of each sequence in the tensor, <code class="language-plaintext highlighter-rouge">torch.nn.utils.rnn.pack_padded_sequence</code> will construct a <code class="language-plaintext highlighter-rouge">PackedSequence</code> object which any RNN module in pytorch knows how to take as input. The RNN will know to ignore the pad tokens.</p> <p>The 2nd way is the loss function. In the cross-entropy loss we are comparing the predicted token with the actual token for a minibatch of predicted and actual sequences, e.g.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">loss</span> <span class="o">=</span> <span class="nf">criterion</span><span class="p">(</span>
    <span class="n">decoder_outputs</span><span class="p">.</span><span class="nf">reshape</span><span class="p">(</span><span class="n">batch_size</span> <span class="o">*</span> <span class="n">T</span><span class="p">,</span> <span class="n">C</span><span class="p">),</span>
    <span class="n">target_tensor</span><span class="p">.</span><span class="nf">view</span><span class="p">(</span><span class="n">batch_size</span> <span class="o">*</span> <span class="n">T</span><span class="p">)</span>
<span class="p">)</span>
</code></pre></div></div> <p>What happens if the sequences are padded with a bunch of pad tokens? If we evaluate the loss where a significant number of <code class="language-plaintext highlighter-rouge">decoder_outputs</code> are pad tokens and <code class="language-plaintext highlighter-rouge">target_tensor</code> are pad tokens, then the loss will be biased towards the pad tokens. We want the loss to reflect the actual tokens, and not the pad tokens. It turns out that <code class="language-plaintext highlighter-rouge">CrossEntropyLoss</code> supports <code class="language-plaintext highlighter-rouge">ignore_index</code> which will ignore a specific index in the loss calculation; in this case it should be set to the <code class="language-plaintext highlighter-rouge">&lt;pad&gt;</code> token.</p> <p>The 3rd way is the attention mechanism when calculating the attention weights. We don’t want the model to pay attention to the pad token.</p> <p>If we look again at the equation for attention:</p> \[attention(Q, K, V) = softmax(\frac{QK^T}{\sqrt{d_k}})V\] <p>We want \(V\) to be 0 where the padding tokens are. To do that we just need to set the scores \(QK^T\) to \(-{inf}\) where the padding tokens are.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">scores</span> <span class="o">=</span> <span class="n">torch</span><span class="p">.</span><span class="nf">bmm</span><span class="p">(</span><span class="n">query</span><span class="p">,</span> <span class="n">keys</span><span class="p">.</span><span class="nf">transpose</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span> <span class="o">/</span> <span class="n">math</span><span class="p">.</span><span class="nf">sqrt</span><span class="p">(</span><span class="n">Dq</span><span class="p">)</span>
<span class="n">scores</span> <span class="o">=</span> <span class="n">scores</span><span class="p">.</span><span class="nf">masked_fill</span><span class="p">(</span><span class="n">mask</span><span class="p">.</span><span class="nf">unsqueeze</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="nf">float</span><span class="p">(</span><span class="sh">'</span><span class="s">-inf</span><span class="sh">'</span><span class="p">))</span>
</code></pre></div></div> <p>where \(mask\) is \(1\) where the pad tokens are.</p> <h5 id="does-it-work">does it work?</h5> <p>Hopefully all this effort to ignore the pad token works and the model is insensitive to the number of pad tokens, which wasn’t the case when I didn’t ignore the pad token in the RNN encoder and in the attention layer.</p> <p>In the following example we randomly sample a test example, check the output with no padding and compare it with the output with a randomly chosen number of pad tokens appended.</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>input: Moore told reporters that the initial autopsy indicated Johnson died as a result of "positional asphyxia."
output with no pad tokens appended to input == output with 42 pad tokens appended to input True
===========
input: "The alarms went off one after the other as it took reinforcements to deal with the building, because the buildings here are close together," explained France Loiselle, spokesperson for the Quebec fire service.
output with no pad tokens appended to input == output with 13 pad tokens appended to input True
===========
input: Rehousing Due to Rats Causes Strife in La Seyne
output with no pad tokens appended to input == output with 29 pad tokens appended to input True
===========
input: I see her eyes resting on me.
output with no pad tokens appended to input == output with 26 pad tokens appended to input True
===========
input: Moreover, Kiev needs liquid assets to pay for its gas imports from Russia, which accuses it of not having paid a bill of 882 million dollars.
output with no pad tokens appended to input == output with 3 pad tokens appended to input True
===========
</code></pre></div></div> <p>Great, the model seems to be ignoring the pad tokens!</p> <h3 id="sequence-generation">Sequence generation</h3> <p>When we’re producing the output sequences it turns out that there are multiple ways to go about it and some are better than others.</p> <h4 id="greedy-search">greedy search</h4> <p>The simplest is called “greedy search” and involves just selecting the token with the highest predicted probability of being the correct token at each timestep.</p> <p>I thought this would be sufficient, as the model is being optimized to learn which is the correct token at each timestep \(t\) given the previous \(t-1\) tokens.</p> <p>However, it turns out that this can produce suboptimal, awkwardly phrased, or strange outputs. It can select a bad token at timestep \(t\) and then this creates a bad sequence going forward.</p> <h4 id="beam-search">beam search</h4> <p>A solution to this is to use “beam search”. <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> and <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a> both use beam search to produce the output sequences.</p> <p>At each timestep \(t\), beam search will choose the \(B\) most likely next tokens, as well as store the following things:</p> <ul> <li>the decoder hidden state at timestep \(t\)</li> <li>the generated sequence at timestep \(t\)</li> <li>The <em>log-likelihood</em> of the sequence</li> </ul> <p>We start by choosing \(B\) most likely tokens to start the sequence. Then for each of these sequences, we select the \(B\) most likely next tokens, producing \(B^2\) possible sequences. From this list of possible sequences, we choose the \(B\) most promising by comparing the <em>log-likelihood</em> of each sequence and choosing the \(B\) sequences with the highest <em>log-likelihood</em>. We complete the search once all \(B\) beams terminate with an <code class="language-plaintext highlighter-rouge">end of sentence</code> token or when we’ve done a certain number of iterations of search, whichever comes first.</p> <h3 id="impact-of-beam-search">Impact of beam search</h3> <p>The above results shown <a href="#figure10">figure 10</a> are using beam search using a beam width of 10.</p> <p>We can see from the figure below that beam search in general improves performance compared to greedy, but also produces a translation of equivalent quality to greedy more generally and sometimes worse. Beam search also takes significantly longer to run.</p> <figure id="figure-13" style="text-align: center;"> <div id="beam_search_plot_container" style="width: 100%"></div> <script>fetch("/assets/plotly/2024-10-03-sequence_to_sequence_translation/beam_search.json").then(e=>e.json()).then(e=>{Plotly.newPlot("beam_search_plot_container",e.data,e.layout)})["catch"](e=>{console.error("Error loading Plotly data:",e)});</script> <figcaption>Figure 13: Impact of beam search on BLEU score. The histogram shows slight overall improvement in BLEU score when beam search is used. </figcaption> </figure> <h5 id="beam-search-example">beam search example</h5> <p>As an example, let’s consider the following input:</p> <blockquote> <p>The theatre director immediately began an evacuation procedure and called the fire brigade to check out a suspicious smell.</p> </blockquote> <p>This has the ground truth french translation:</p> <blockquote> <p>Immédiatement, le directeur de l’établissement a fait procéder à l’évacuation de la salle et a prévenu les pompiers pour une odeur suspecte.</p> </blockquote> <p>The greedy search prediction is:</p> <blockquote> <p>Le directeur du théâtre a immédiatement entrepris une procédure d’évacuation et a appelé la brigade de pompiers pour vérifier une odeur suspecte.</p> </blockquote> <p>Let’s see what beam search produces.</p> <p>For this example I am using a <em>beam-size</em> \(B\) of \(2\).</p> <p>Beam search starts off predicting the 1st token:</p> <p><strong>iteration 1</strong></p> <table> <thead> <tr> <th style="text-align: left">Sequence</th> <th style="text-align: left"><em>log-likelihood</em></th> </tr> </thead> <tbody> <tr> <td style="text-align: left"> </td> <td style="text-align: left">0.0</td> </tr> <tr> <td style="text-align: left">’</td> <td style="text-align: left">-19.966</td> </tr> </tbody> </table> <p>It starts off predicting start of sentence and an apostrophe token.</p> <p>Then, for each of these beams, it predicts \(B\) next tokens:</p> <p><strong>iteration 2</strong></p> <table> <thead> <tr> <th style="text-align: left">Sequence</th> <th style="text-align: left"><em>log-likelihood</em></th> </tr> </thead> <tbody> <tr> <td style="text-align: left">Le</td> <td style="text-align: left"><strong>-0.387</strong></td> </tr> <tr> <td style="text-align: left">La</td> <td style="text-align: left"><strong>-3.325</strong></td> </tr> <tr> <td style="text-align: left">’ Le</td> <td style="text-align: left">-20.716</td> </tr> <tr> <td style="text-align: left">’ La</td> <td style="text-align: left">-22.956</td> </tr> </tbody> </table> <p>For each of the previous 2 beams, we search for the next token. <em>Le</em> is the most likely, while <em>La</em> is second most likely. We select these 2 beams and continue expanding both.</p> <p><strong>iteration 3</strong></p> <table> <thead> <tr> <th style="text-align: left">Sequence</th> <th style="text-align: left"><em>log-likelihood</em></th> </tr> </thead> <tbody> <tr> <td style="text-align: left">Le directeur</td> <td style="text-align: left"><strong>-0.560</strong></td> </tr> <tr> <td style="text-align: left">Le chef</td> <td style="text-align: left">-4.279</td> </tr> <tr> <td style="text-align: left">La directrice</td> <td style="text-align: left"><strong>-3.885</strong></td> </tr> <tr> <td style="text-align: left">La direction</td> <td style="text-align: left">-5.589</td> </tr> </tbody> </table> <p>Let’s see what happens next.</p> <p><strong>iteration 4</strong></p> <table> <thead> <tr> <th style="text-align: left">Sequence</th> <th style="text-align: left"><em>log-likelihood</em></th> </tr> </thead> <tbody> <tr> <td style="text-align: left">Le directeur du</td> <td style="text-align: left"><strong>-1.102</strong></td> </tr> <tr> <td style="text-align: left">Le directeur de</td> <td style="text-align: left"><strong>-1.667</strong></td> </tr> <tr> <td style="text-align: left">La directrice du</td> <td style="text-align: left">-4.574</td> </tr> <tr> <td style="text-align: left">La directrice de</td> <td style="text-align: left">-5.007</td> </tr> </tbody> </table> <p><strong>iteration 5</strong></p> <table> <thead> <tr> <th style="text-align: left">Sequence</th> <th style="text-align: left"><em>log-likelihood</em></th> </tr> </thead> <tbody> <tr> <td style="text-align: left">Le directeur du théâtre</td> <td style="text-align: left"><strong>-1.267</strong></td> </tr> <tr> <td style="text-align: left">Le directeur du secteur</td> <td style="text-align: left">-5.419</td> </tr> <tr> <td style="text-align: left">Le directeur de théâtre</td> <td style="text-align: left"><strong>-2.450</strong></td> </tr> <tr> <td style="text-align: left">Le directeur de la</td> <td style="text-align: left">-2.565</td> </tr> </tbody> </table> <p>We can see how beam search is trying out different possibilities for the next token and adjustment the likelihood after expanding each of the most likely \(B\) beams \(B\) times.</p> <p>It continues like this for 28 iterations. The final list of beam candidates are:</p> <table> <thead> <tr> <th style="text-align: left">Sequence</th> <th style="text-align: left"><em>log-likelihood</em></th> </tr> </thead> <tbody> <tr> <td style="text-align: left">Le directeur du théâtre a immédiatement entrepris une procédure d’évacuation et a appelé la brigade d’incendie pour vérifier une odeur suspecte.</td> <td style="text-align: left"><strong>-12.367</strong></td> </tr> <tr> <td style="text-align: left">Le directeur du théâtre a immédiatement entrepris une procédure d’évacuation et a appelé la brigade d’incendie pour vérifier une odeur suspecte de</td> <td style="text-align: left">-19.076</td> </tr> <tr> <td style="text-align: left">Le directeur du théâtre a immédiatement entrepris une procédure d’évacuation et a appelé la brigade d’incendie à vérifier une odeur suspecte.</td> <td style="text-align: left"><strong>-12.813</strong></td> </tr> <tr> <td style="text-align: left">Le directeur du théâtre a immédiatement entrepris une procédure d’évacuation et a appelé la brigade d’incendie à vérifier une odeur suspecte de</td> <td style="text-align: left">-12.813</td> </tr> </tbody> </table> <p>We can see that 2 of the sequences are incomplete, but because \(B=2\) of the sequences are complete, beam search terminates. This is a bias of beam search that it prefers shorter sequences.</p> <h3 id="handling-unknown-tokens">Handling unknown tokens</h3> <p>In previous attempts at language modeling, a fixed size vocabulary would be constructed and used for training. What happens when the model sees an unknown token at test time? What should the model do? The model would typically just output a special <code class="language-plaintext highlighter-rouge">&lt;UNK&gt;</code> token, standing for unknown. But this is not useful. We don’t want to see that. When using chatgpt for example, we don’t want to see <code class="language-plaintext highlighter-rouge">&lt;UNK&gt;</code> in the output, but what if a user enters something it has never seen before?</p> <p>We mentioned before in the section on <a href="#tokenization">tokenization</a> that the initial vocabulary when using the <code class="language-plaintext highlighter-rouge">sentencepiece</code> algorithm with <code class="language-plaintext highlighter-rouge">byte_fallback=True</code> is that the initial vocabulary contains all UTF-8 bytes. When an unexpected token is encountered in this scenario, the sentencepiece algorithm will break down the token into its UTF-8 bytes, and since each UTF-8 byte is part of the vocabulary, the model will not need to output the <code class="language-plaintext highlighter-rouge">&lt;UNK&gt;</code> token.</p> <p>When we use the byte-pair encoding algorithm, we break up the sequence into familiar chunks, if familiar chunks exist. We can do this for the word <em>suspecte</em> which means <em>suspicious</em>. It breaks up this word into 2 tokens, since the word <em>suspecte</em> by itself wasn’t common enough in the tokenizer training set.</p> <p>In code:</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">target_tokenizer</span><span class="p">.</span><span class="n">processor</span><span class="p">.</span><span class="nf">encode</span><span class="p">(</span><span class="sh">"</span><span class="s">suspecte</span><span class="sh">"</span><span class="p">,</span> <span class="n">out_type</span><span class="o">=</span><span class="nb">str</span><span class="p">)</span>
</code></pre></div></div> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="sh">'</span><span class="s">▁suspec</span><span class="sh">'</span><span class="p">,</span> <span class="sh">'</span><span class="s">te</span><span class="sh">'</span><span class="p">]</span>
</code></pre></div></div> <p>These 2 tokens were common enugh in the tokenizer training set to be included as tokens.</p> <p>The underscore in “▁suspec” seems strange at first; sentencepiece encodes “word boundaries” or starts of words with “_”.</p> <p>To my surprise, I didn’t find any examples of <code class="language-plaintext highlighter-rouge">byte_fallback</code> being activated in the test set. Meaning that every word can be broken up into chunks that are known vocabulary tokens.</p> <p>Let’s take a sequence with a rather rare looking word “Ikhrata”, which is someone’s surname, from the test set:</p> <blockquote> <p>“It is not a matter of something we might choose to do,” said Hasan Ikhrata, executive director of the Southern California Assn. of Governments, which is planning for the state to start tracking miles driven by every California motorist by 2025.</p> </blockquote> <p>This word is not in the training set. How does the tokenizer handle this?</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">source_tokenizer</span><span class="p">.</span><span class="n">processor</span><span class="p">.</span><span class="nf">encode</span><span class="p">(</span><span class="sh">"</span><span class="s">Ikhrata</span><span class="sh">"</span><span class="p">,</span> <span class="n">out_type</span><span class="o">=</span><span class="nb">str</span><span class="p">)</span>
</code></pre></div></div> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="sh">'</span><span class="s">▁I</span><span class="sh">'</span><span class="p">,</span> <span class="sh">'</span><span class="s">kh</span><span class="sh">'</span><span class="p">,</span> <span class="sh">'</span><span class="s">ra</span><span class="sh">'</span><span class="p">,</span> <span class="sh">'</span><span class="s">ta</span><span class="sh">'</span><span class="p">]</span>
</code></pre></div></div> <p>It breaks up the word into familiar chunks, known vocabulary tokens. This is the advantage of using a tokenization algorithm like sentencepiece, compared to just breaking up sequences into words. The word “Ikhrata” would be unknown and we would not know what to do with it.</p> <p>What is the model’s output?</p> <blockquote> <p>« Il ne s’agit pas d’une chose que nous pourrions choisir de faire », a déclaré Hasan Ikherata, directeur exécutif de la Southern California Assn. of Governments, qui prévoit que l’État commencera à suivre les kilomètres parcourus par tous les automobilistes de la Californie d’ici 2025.</p> </blockquote> <p>“Ikhrata” was not found in the training set, and the model output “Ikherata”, which is not good.</p> <p>However, this shows that we can output something rather than <code class="language-plaintext highlighter-rouge">&lt;UNK&gt;</code>.</p> <h3 id="mixed-precision-training">Mixed precision training</h3> <p>The default datatype for network operations in pytorch is <code class="language-plaintext highlighter-rouge">torch.float32</code>.</p> <p>However, it turns out that most deep learning operations don’t require this much precision, and <code class="language-plaintext highlighter-rouge">float16</code> would suffice. But not all operations can use the lower precision, which is why pytorch and the GPU know how to do some operations using <code class="language-plaintext highlighter-rouge">float32</code> and some with <code class="language-plaintext highlighter-rouge">float16</code>. That is why it is called <em>mixed precision</em>.</p> <p>This is a good thing that we don’t need to always use <code class="language-plaintext highlighter-rouge">float32</code> since <code class="language-plaintext highlighter-rouge">float16</code> takes up less memory than <code class="language-plaintext highlighter-rouge">float32</code>, which allows the GPU to access the data quicker and allows us to use larger batch sizes. See <a href="https://pytorch.org/blog/accelerating-training-on-nvidia-gpus-with-pytorch-automatic-mixed-precision/">this article</a> which shows that using mixed precision training achieves the same accuracy as <code class="language-plaintext highlighter-rouge">float32</code> and shows that mixed precision training ran 2-5 times faster.</p> <p>In my experiments using the Nvidia V100 GPUs, training on <code class="language-plaintext highlighter-rouge">float32</code> took <code class="language-plaintext highlighter-rouge">1.80s/batch</code> while training with <code class="language-plaintext highlighter-rouge">float16</code> took <code class="language-plaintext highlighter-rouge">0.99s/batch</code>, which matches what the PyTorch article above reported.</p> <p>This is great, since it means that training time is cut down by half.</p> <h2 id="conclusion">Conclusion</h2> <p>We implemented an RNN model without attention similar to <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> and a model with attention similar to <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a> and found that the model with attention has better overall performance than the model without attention as evaluated by the BLEU score on the 3003 test set examples in the WMT’14 dataset. However, <a class="citation" href="#DBLP:journals/corr/BahdanauCB14">(Bahdanau et al., 2015)</a> reports a steep decrease in BLEU score as the sentence length increases, which we were not able to reproduce. Our results are in line with <a class="citation" href="#10.5555/2969033.2969173">(Sutskever et al., 2014)</a> which reported that the model without attention is robust to sentence length, but the paper that introduced attention is seen as a “paradigm shift” paper that introduced attention, so the community saw value in the attention mechanism though the reported performance in the paper is not as good as previous papers.</p> <p>Researchers ran with the idea of attention, and developed the transformer architecture, which forms the backbone of SOTA “language models” such as the GPT series.</p> <p>Also of note that at the time, non-deep-learning based methods such as Moses, showed better performance on the translation task, but clearly the community invested more effort in deep learning based methods. The transformer model paid off and is significantly more influential than just in doing translation, which Moses is only capable of doing.</p> <p>Importantly, the problem of translation is used, as these papers were focused on, but learning to translate is actually similar to learning to take in an arbitrary sequence and output an arbitrary sequence, which for example chatbots, image generators, video generators, etc need to do. So the applications of this research are more applicable than just to the problem of translation.</p> <p>Next, we’ll build on language models and implement a transformer model rather than an RNN model.</p> <h1 id="references">References</h1>]]></content><author><name></name></author><category term="deep learning"/><category term="rnn"/><category term="machine translation"/><category term="sequences"/><category term="attention"/><summary type="html"><![CDATA[In this article, I’ll introduce language modeling using deep learning and will focus on the problem of translation.]]></summary></entry></feed>