<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kollol Das on Medium]]></title>
        <description><![CDATA[Stories by Kollol Das on Medium]]></description>
        <link>https://medium.com/@kolloldas?source=rss-a71ada66b97f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z3gp0qUFWyfdZ7DYK6cNSw.png</url>
            <title>Stories by Kollol Das on Medium</title>
            <link>https://medium.com/@kolloldas?source=rss-a71ada66b97f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:59:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kolloldas/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building the Mighty Transformer for Sequence Tagging in PyTorch : Part II]]></title>
            <link>https://medium.com/@kolloldas/building-the-mighty-transformer-for-sequence-tagging-in-pytorch-part-ii-c85bf8fd145?source=rss-a71ada66b97f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c85bf8fd145</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Kollol Das]]></dc:creator>
            <pubDate>Wed, 18 Apr 2018 08:55:49 GMT</pubDate>
            <atom:updated>2018-04-23T10:22:59.974Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@kolloldas/building-the-mighty-transformer-for-sequence-tagging-in-pytorch-part-i-a1815655cd8">first part</a> of this series we looked into the main components of the Transformer model — <em>Multi Head attention</em> and <em>Positionwise Feedforward</em>. Now let’s see how they work together.</p><h3>Putting it all Together</h3><p>PyTorch makes object oriented design easy with nn.Module so we can nest components just like in the paper. Following their <em>layer</em> and <em>sublayer</em> terminologies I have structured the code in three files:</p><ul><li><a href="https://github.com/kolloldas/torchnlp/blob/master/torchnlp/modules/transformer/sublayers.py"><em>sublayers.py</em></a>: Defines the innermost components, namely MultiHeadAttention and PositionwiseFeedforward. These are used both by the Encoder and the Decoder layers.</li><li><a href="https://github.com/kolloldas/torchnlp/blob/master/torchnlp/modules/transformer/layers.py"><em>layers.py</em></a><em>:</em> Defines a single layer of of the Encoder and Decoder blocks called EncoderLayer and DecoderLayer respectively. In the block diagram they are the grey regions.</li><li><a href="https://github.com/kolloldas/torchnlp/blob/master/torchnlp/modules/transformer/main.py"><em>main.py</em></a>: Contains definitions of the top level Encoder and Decoder units called Encoder and Decoder . It handles things like multiple layers, timing signal generation and attention masks among others.</li></ul><p>Let’s go through each of their forward() functions starting with the EncoderLayer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/528e35c839bdbeeba3e05a447e844e7b/href">https://medium.com/media/528e35c839bdbeeba3e05a447e844e7b/href</a></iframe><p>I will not cover <a href="https://arxiv.org/abs/1607.06450"><em>LayerNorm</em></a> since it’s a standard affair. You can check the full implementation <a href="https://github.com/kolloldas/torchnlp/blob/master/torchnlp/modules/normalization.py">here</a>. The important bit above is the call to multi head attention:</p><pre>y = self.multi_head_attention(x_norm, x_norm, x_norm)</pre><p>Make the queries, keys and values same, and <em>voila</em> we get self-attention! This term gets thrown around a lot these days and now you know it isn’t something very fancy. This is the component that replaces recurrent and convolutional layers, and, as the authors argue in their paper, it’s faster and more powerful. <em>Dropout</em> and residual connections are combined in one step:</p><pre>x = self.dropout(x + y)</pre><p>Note that the residual input is tapped before layer normalization. The DecoderLayer is similar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6364b71afb4eaee3b4b1e36fa96cb24/href">https://medium.com/media/e6364b71afb4eaee3b4b1e36fa96cb24/href</a></iframe><p>The first difference we note here is that the DecoderLayer takes the inputs as a tuple consisting of the decoder inputs as well as the encoder outputs. I’ve used a tuple so that I can easily pass the inputs through multiple layers using nn.Sequential. Encoder outputs are needed for attention.</p><p>The DecoderLayer does multi head attention twice. First it does a self-attention just like the EncoderLayer but the queries are ‘masked’ (more on that later I promise). The second call uses the encoder outputs as both keys and values:</p><pre>y = self.multi_head_attention_enc_dec(x_norm, encoder_outputs, encoder_outputs)</pre><p>The queries come from the self-attention outputs (with some post processing). To remind you again, the queries for all decoder time steps are available together during training and evaluation due to the nature of Transformer. For a recurrent network you can only get the query one time step at a time since the query at the next time step depends on the attention outputs at the current time step — this is major factor slowing down recurrent networks and making them hard to parallelize. During inference, however, the Transformer <em>also </em>needs to decode one time step at a time. The only way to do it is to run the decoder multiple times, each time expanding the decoder inputs with newly obtained outputs. It is a slow process requiring repeated processing of the same inputs. To partly speed it up, the Tensorflow implementation of Transformer <a href="https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/layers/common_attention.py#L2425">caches</a> the attention outputs for each time step (I’m yet to implement caching in PyTorch).</p><p>Finally at the top level we have the Encoder and the Decoder :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3388947d3256d4ba6036d85e09617d2e/href">https://medium.com/media/3388947d3256d4ba6036d85e09617d2e/href</a></iframe><p>The embedding projection linearly projects the embedding outputs (external to the Transformer) to a common hidden size:</p><pre>self.embedding_proj = nn.Linear(embedding_size, hidden_size, bias=False)</pre><p>Next, a ‘timing signal’ is added so that the model can track sequence ordering better. We’ll go into that in the next section. The encoder layer is applied multiple times using nn.Sequential:</p><pre>self.enc = nn.Sequential(*[EncoderLayer(*params) for l in range(num_layers)])</pre><p>params is a tuple of hyperparameters which is identical for each layer. The Decoder implementation is very similar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bea5865d6893c1bf74c9a2e0f59c1eda/href">https://medium.com/media/bea5865d6893c1bf74c9a2e0f59c1eda/href</a></iframe><p>Like the DecoderLayer the main difference is that there is an additional input coming from the encoder outputs. This is combined with the decoder inputs as a tuple and fed into the DecoderLayer component:</p><pre>y, _ = self.dec((x, encoder_output))</pre><p>The final outputs of the Decoder (or Encoder for our task) goes through an output layer which first projects to a dimension equal to the output vocabulary. After that there can be a <em>Softmax</em> layer or for our case a <a href="https://github.com/kolloldas/torchnlp/blob/master/torchnlp/modules/crf.py"><em>CRF</em></a> layer. That completes the pipeline! Now for those additional tricks..</p><h3>Masked Attention — No Peeking into the Future</h3><p>I mentioned I would cover attention bias mask later when going through the code of MultiHeadAttention. For tasks like translation the decoder is fed previous outputs as input to predict the next output. During training the quick way to get the previous outputs is to <em>shift</em> the training labels right (The first time step gets a special symbol) and feed them as decoder inputs — a technique known as <em>Teacher Forcing</em> in machine learning parlance. However this presents a problem for the Transformer decoder as it can ‘cheat’ by using inputs from future time steps. The places where the short circuiting can happen is the self attention step and both the feedforward steps. (Can you figure out why it cannot happen in the normal attention step?)</p><p>In the self attention step we feed values from all time steps to the MultiHeadAttention component. Recall that we do a weighted linear combination of the <em>Values</em> input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*aJiWfOaTCktprHEgNdeJow.png" /></figure><p>Consider the first row of <em>OUTPUT</em> in the above diagram. It corresponds to the attention output at time <em>t=1</em>. But it is computed from values right up till <em>t=10</em> which are future time steps. To prevent reading these future values we zero out all weights in the <em>WEIGHTS</em> tensor above the main diagonal. This will ensure that future values cannot creep in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*6aTQQSmXUfCQxj3drNEweg.png" /></figure><p>In practice we do not zero out the weight tensor directly as it would need additional normalization to ensure all probabilities add up to one. Instead we add negative infinity to the upper triangle before the <em>Softmax; </em>after exponentiation those values become zero. Also we precompute this matrix if the maximum length is known:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80a29f278873c31c7921c2b84cc4a11a/href">https://medium.com/media/80a29f278873c31c7921c2b84cc4a11a/href</a></iframe><p>A cropped version of the mask is applied in the MultiHeadAttention component:</p><pre>if self.bias_mask is not None:            <br>  logits += Variable(<br>   self.bias_mask[:, :, :logits.shape[-2], :logits.shape[-1]]<br>   .type_as(logits.data))</pre><p>A similar problem occurs in the PositionwiseFeedforward component if we use convolutional layers. A 1D convolution with a filter of width 3 will access the input at time <em>t+1</em> to compute the output at time <em>t</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*3F92MhsXbdJJWl34yQEqGg.png" /><figcaption>Center Padding</figcaption></figure><p>This is due to the way the inputs are automatically padded when we want to keep the output sequence length same as the input sequence length. A slight change in padding makes the problem go away:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*EdaD2nN6gX57_u8s2rGmnQ.png" /><figcaption>Left Padding</figcaption></figure><p>Now the output at time <em>t</em> will only depend on the inputs at time <em>t, t-1</em> and <em>t-2</em>. The nn.Conv1d API in PyTorch doesn’t support this type of padding, so we do it ourselves:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb0cd5538acaa3aa7639a441a3943c32/href">https://medium.com/media/bb0cd5538acaa3aa7639a441a3943c32/href</a></iframe><p>For our sequence tagging task we use only the encoder part of the Transformer and do not feed the outputs back into the encoder. So we will not be using either the bias mask or left padding. Next is the final trick.</p><h3>Positional Encoding — The Timekeeper</h3><p>An inherent feature of recurrent neural networks is their ability to track the ordering of input sequences due the internal state that they maintain. With recurrent layers gone from the Transformer it cannot easily distinguish the input at one time step from the other. To make up for this lack of statefullness, extra positional information needs to be added make each time step unique. An earlier work called <a href="https://arxiv.org/abs/1705.03122"><em>Convolutional Sequence to Sequence Learning</em></a> used positional Embeddings which basically is adding random vectors unique to each time step. Then the model can learn to identify the absolute positions of the inputs. The creators of Transformer one-upped this technique by adding sinusoids which they claim can track relative positions as well since sinusoids are cyclic functions. Our implementation uses sinusoids which is adapted straight from TensorFlow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d204fa8e80fafe991cc46c5020d4221a/href">https://medium.com/media/d204fa8e80fafe991cc46c5020d4221a/href</a></iframe><p>Here channels is the hidden size of our model. Starting from a time scale of 1 we generate <em>sin</em> and <em>cos</em> signals of exponentially increasing wavelengths or reducing frequency (hence -log_timescale_increment in line 13) for each dimension till it reaches 10,000. These numbers were arrived at by experimentation I believe so they might need to change for a new task. Like bias masking we precompute these values and add cropped versions to the inputs (after embedding) during run time:</p><pre>x += Variable(<br>     self.timing_signal[:, :inputs.shape[1], :]<br>     .type_as(inputs.data))</pre><p>With these two tricks applied our Transformer is finally complete. Let’s see it in action now!</p><h3>Transformer vs. BiLSTM — The Face-Off</h3><p>Our Transformer model will be going against the all-too-well-known bidirectional LSTM on the <a href="https://www.clips.uantwerpen.be/conll2000/chunking/">CoNLL 2000 chunking</a> task. It’s quite an old task with the state of the art F1 values hovering around 94–95%. Unlike the top models the only input feature we’re going to use is raw text — no part of speech tags, spelling or capitalization features. However we will use external word embeddings (<a href="https://nlp.stanford.edu/projects/glove/">GloVe</a> 200D and <a href="http://www.logos.t.u-tokyo.ac.jp/~hassy/publications/arxiv2016jmt/">Char N-Grams</a> to be precise) and character embeddings. Both models will use a <a href="https://github.com/kolloldas/torchnlp/blob/master/torchnlp/modules/crf.py">conditional random field</a> (CRF) layer on the output side. We will only be using the encoder part of the Transformer for this experiment since it is a one to one mapping task.</p><p>There is a whole bunch of things that need to be done before we can actually train these models. Conveniently for us I have written a small framework that will take care of the boilerplate. I call it <a href="https://github.com/kolloldas/torchnlp">TorchNLP</a><em> </em>and it does things like:</p><ul><li>Handling the data pipeline (Uses <a href="https://github.com/pytorch/text">TorchText</a> under the hood)</li><li>Loading and saving models</li><li>Training models with configurable hyperparameters</li><li>Evaluating models with metrics like accuracy, F1 etc.</li></ul><p>The Transformer and bidirectional LSTM along with common components like CRFs are already baked into the framework so all we have to do is run the experiments.</p><p>Installation is very simple. You will need Python 3.5+ to run it though. Clone TorchNLP from GitHub:</p><pre>git clone https://github.com/kolloldas/torchnlp.git</pre><p>Set up PyTorch with or without GPU support (preferably in a new Python 3 virtual environment). Go to the root of the TorchNLP project and install the dependencies:</p><pre>pip install -r requirements.txt</pre><p>That’s it for instalation. Start the chunking task:</p><pre>python -i -m torchnlp.chunk</pre><p>This will load up the environment for chunking:</p><pre>Task: Chunking (Shallow parsing)</pre><pre>Available models:<br>-------------------<br>TransformerTagger</pre><pre>Sequence tagger using the Transformer network (<a href="https://arxiv.org/pdf/1706.03762.pdf">https://arxiv.org/pdf/1706.03762.pdf</a>)<br>Specifically it uses the Encoder module. For character embeddings (per word) it uses the same Encoder module above which an additive (Bahdanau) self-attention layer is added</pre><pre>BiLSTMTagger</pre><pre>Sequence tagger using bidirectional LSTM. For character embeddings per word uses (unidirectional) LSTM</pre><pre>Available datasets:<br>-------------------<br>conll2000: Conll 2000 (Chunking)</pre><pre>&gt;&gt;&gt;</pre><p>(If you get any errors at this point means something went wrong with your installation. Please explain the error in the comments section and I’ll be happy to help.)</p><p>Let’s see what hyperparameters our models’ got. Here the BiLSTM:</p><pre>&gt;&gt;&gt; hparams_lstm_chunk()</pre><pre>Hyperparameters:<br> dropout=0.5<br> learning_rate_decay=noam_step<br> optimizer_adam_beta2=0.98<br> optimizer_adam_beta1=0.9<br> embedding_size_word=300<br> learning_rate_warmup_steps=100<br> hidden_size=100<br> embedding_size_tags=100<br> embedding_size_char=25<br> learning_rate=0.05<br> max_length=256<br> batch_size=100<br> num_hidden_layers=2<br> use_crf=True<br> embedding_size_char_per_word=25</pre><p>And the Transformer:</p><pre>&gt;&gt;&gt; hparams_transformer_chunk()</pre><pre>Hyperparameters:<br> relu_dropout=0.2<br> learning_rate_decay=noam_step<br> optimizer_adam_beta2=0.98<br> optimizer_adam_beta1=0.9<br> embedding_size_word=300<br> attention_key_channels=0<br> filter_size_char=64<br> embedding_size_char=16<br> embedding_size_tags=100<br> embedding_size_char_per_word=100<br> dropout=0.2<br> filter_size=128<br> use_crf=True<br> num_hidden_layers=2<br> attention_value_channels=0<br> hidden_size=128<br> input_dropout=0.2<br> learning_rate_warmup_steps=500<br> num_heads=4<br> learning_rate=0.2<br> max_length=256<br> batch_size=100<br> attention_dropout=0.2</pre><p>The Transformer’s got way more knobs to turn than the BiLSTM model. Also note that it is much smaller in terms of parameters than the original model since the task itself is so small. The Transformer will go first. Start the training:</p><pre>&gt;&gt;&gt; train(&#39;chunking&#39;, TransformerTagger, conll2000)</pre><p>You should see the datasets and the word embeddings being downloaded and extracted first. (Be warned that the word embeddings are around 2GB in size.) After that the training will start with a bar showing the progress in each epoch. Training will stop automatically once the F1 value on the validation data peaks (using early stopping). For me it was after 35 epochs:</p><pre>INFO:torchnlp.common.train:Epoch 35 (2754)<br>INFO:torchnlp.common.train:Train Loss: 1.79630<br>INFO:torchnlp.common.train:Validation metrics:<br>INFO:torchnlp.common.train:loss=2.21440, F1=0.94471, <br>acc-seq=0.62640, recall=0.94353, acc=0.96548, precision=0.94589<br>INFO:torchnlp.common.train:Early stopping at iteration 2430, epoch 29, F1=0.94504</pre><p>Looks good. BiLSTM’s turn:</p><pre>&gt;&gt;&gt; train(&#39;chunking&#39;, BiLSTMTagger, conll2000)<br>...<br>INFO:torchnlp.common.train:Epoch 26 (2025)<br>INFO:torchnlp.common.train:Train Loss: 0.68408<br>INFO:torchnlp.common.train:Validation metrics:<br>INFO:torchnlp.common.train:loss=2.32462, F1=0.94619, <br>acc-seq=0.61521, recall=0.94749, acc=0.96784, precision=0.94488<br>INFO:torchnlp.common.train:Early stopping at iteration 1701, epoch 20, F1=0.94669</pre><p>Hmm the BiLSTM has a slightly better F1. It also converged faster. Time to turn some of those knobs on the Transformer. Switching to 2 heads:</p><pre>&gt;&gt;&gt; h2 = hparams_transformer_chunk().update(num_heads=2)<br>&gt;&gt;&gt; train(&#39;chunking_h2&#39;, TransformerTagger, conll2000, hparams=h2)<br>...<br>INFO:torchnlp.common.train:Epoch 54 (4293)<br>INFO:torchnlp.common.train:Train Loss: 1.65368<br>INFO:torchnlp.common.train:Validation metrics:<br>INFO:torchnlp.common.train:loss=2.19627, F1=0.94715, acc-seq=0.63087, recall=0.94915, acc=0.96771, precision=0.94515<br>INFO:torchnlp.common.train:Early stopping at iteration 3969, epoch 48, F1=0.94746</pre><p>Ok now the Transformer is ahead. We could keep tweaking hyperparameters for a long time this way (that’s what research is about after all) but without the luxury of a deep learning cluster to blaze through scores of combinations it will be hard to make progress. Let’s evaluate both models on the test set. The BiLSTM gets:</p><pre>&gt;&gt;&gt; evaluate(&#39;chunking&#39;, BiLSTMTagger, conll2000, &#39;test&#39;)<br>...<br>test set evaluation: chunking-BiLSTMTagger<br>loss=3.19308, F1=0.94238, acc-seq=0.61133, recall=0.94206, acc=0.96500, precision=0.94269</pre><p>94.24% F1. And the Transformer gets:</p><pre>&gt;&gt;&gt; evaluate(&#39;chunking_h2&#39;, TransformerTagger, conll2000, &#39;test&#39;)<br>test set evaluation: chunking_l2-TransformerTagger<br>loss=2.97885, F1=0.94319, acc-seq=0.61581, recall=0.94424, acc=0.96541, precision=0.94215</pre><p>94.32% F1 😑. It’s too close to call as 0.1% is well within error margins. Unless we do a large number of experiments we cannot call it a clear win. It’s a tie for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Q-CMtmyLV_Inx8pcIl3F4w.png" /></figure><p>I would encourage you to play around with the hyperparameters or even change the architecture to see if the Transformer can do any better. If you hit the jackpot let me know!</p><h3>Lessons Learned</h3><p>Our home made Transformer couldn’t really outdo the BiLSTM by a significant margin. While it had fewer trainable parameters at about 200K lesser than the BiLSTM it took longer to converge. So what can we say about Transformer’s overall architecture?</p><p>One thing that I found in the course of experimentation is that the Transformer does worse if we use linear layers instead of convolutional ones in the PositionwiseFeedforward component. Remember that we used only the Encoder half of the Transformer for this task (I did try adding the decoder, it did not improve the results). So I have a hunch that self attention by itself is unable to make inputs at multiple time steps interact <em>multiplicatively</em> which can capture more complex phenomenon<em>. </em>It takes care of pairwise multiplicative interactions between different time steps but does not handle say 3–4 steps together. Using convolutional layers with kernel size 3 could be partly solving this problem but interaction there is additive. Having two layers instead of one also improved the F1 because it allowed more than two time steps to interact nonlinearly. But they are weaker compared to a recurrent network which has strong nonlinear interactions between multiple nearby time steps. So in the end the gains that the Transformer made with self attention and the feedforward combination is probably lost with this inability. Again, more experimentation is needed.</p><p>In the near future perhaps a hybrid model will come along that does weird combinatorial acrobatics to handle multi time step interactions while still being fast at the same time. Maybe one is in the works at Google already, who knows!</p><p>NOTE: I have left out some implementation details (e.g. the Noam learning rate schedule etc) to keep the article length reasonable. You can go through the code to understand these parts which I hope are self explanatory. If you have any specific queries please ask in the comments section and I’ll do my best to answer them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c85bf8fd145" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building the Mighty Transformer for Sequence Tagging in PyTorch : Part I]]></title>
            <link>https://medium.com/@kolloldas/building-the-mighty-transformer-for-sequence-tagging-in-pytorch-part-i-a1815655cd8?source=rss-a71ada66b97f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1815655cd8</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kollol Das]]></dc:creator>
            <pubDate>Wed, 18 Apr 2018 08:54:42 GMT</pubDate>
            <atom:updated>2018-06-23T12:38:22.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIR0CnZVd7d-RRno8_F26Q.jpeg" /></figure><p>Attention mechanisms have taken the deep learning world by storm in the last few years. It is not uncommon nowadays to have an attention related component somewhere in your model. Last year Google pushed attention mechanisms to the extreme when it came out with the Transformer models in its infamous <a href="https://arxiv.org/abs/1706.03762">“Attention is all you need”</a> paper. As the title says, Transformer models ditch recurrent layers for a combination of attention and regular feedforward networks. Not only is the model faster and scalable but it is also more interpretable because we can examine its attention weights to know what it focuses on. While this newfound approach has earned the Transformer new records in translation tasks no one seems have attempted apply this model to sequence tagging tasks yet. This is an area where RNNs still rule the roost. Would the Transformer be able to take out the venerable BiLSTM? I felt it was a great excuse to build our own implementation and that’s what this post will explain.</p><h3>Overview</h3><p>In this two part series we are going to build the Transformer model from scratch and make it compete with a BiLSTM model on the chunking task. We’ll do zero math and instead look at the concepts visually.</p><ul><li>This first part will go through the implementation of the core components that make the Transformer — <em>Multi Head Attention</em> and <em>Position wise Feed Forward Network</em>. We’ll especially detail out the inner workings of attention mechanisms.</li><li>The second part will focus on implementing the remaining bits of the Transformer and putting all the parts together. It will conclude with a face off between the Transformer and BiLSTM.</li></ul><p>We’ll follow the original <a href="https://arxiv.org/abs/1706.03762">Transformer</a> paper to implement our model in <a href="http://pytorch.org/">PyTorch</a>. But we will incorporate the latest improvements from the <a href="https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transformer.py">TensorfFlow</a> implementation of Transformer as well. We will use the freely available <a href="https://www.clips.uantwerpen.be/conll2000/chunking/">CoNLL 2000 Chunking</a> dataset to run the experiments. If you just want to grab the code it’s all there on <a href="https://github.com/kolloldas/torchnlp">Github</a>.</p><h3>Transformer Guts</h3><p>At the top level, the Transformer has an Encoder and Decoder just like sequence-to-sequence models. If we strip away standard neural network embellishments like <em>Dropout</em>, <em>LayerNorm </em>and residual connections, we’ll find that both blocks have two unique components — <em>Multi Head Attention</em> and <em>Position wise Feedforward</em>. They may sound complicated but are not very different from the regular attention and feed-forward layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*mq_H9EGUrTiwf5ZfMva4Sg.png" /><figcaption>The Transformer in all its glory. Note some of the changed blocks from the original paper.</figcaption></figure><h3>Multi-Head Attention — The Beast</h3><p><em>Multi head attention</em> is essentially attention repeated several times in parallel. (If you are not clear about the intuition behind attention I suggest you see this short <a href="https://www.coursera.org/learn/nlp-sequence-models/lecture/RDXpX/attention-model-intuition">video</a> explanation by Andrew Ng on Coursera.) Attention in general can be considered to have three inputs and one output:</p><ul><li><em>Keys</em>: A sequence of vectors also known as the memory. It is the contextual information that we want to look at. In traditional sequence-to-sequence learning they are usually the RNN encoder outputs.</li><li><em>Values:</em> A sequence of vectors from which we aggregate the output through a weighted linear combination. Often <em>Keys </em>serve as <em>Values</em>.</li><li><em>Query:</em> A single vector that we use to probe the <em>Keys</em>. By probing we mean the <em>Query</em> is independently combined with each key<em> </em>to arrive at a single probability. The type of attention determines how the combination is done. Usually <em>Query </em>is the decoder RNN state at a given time step in traditional sequence-to-sequence learning</li><li><em>Output:</em> A single vector which is derived from a linear combination of the <em>Values </em>using the probabilities from the previous step as weights.</li></ul><p>With these definitions in place let’s look at the actual implementation in PyTorch. I will assume that you know how nn.Module works. (If not <a href="http://pytorch.org/tutorials/beginner/pytorch_with_examples.html">here</a> is an excellent introduction). Let’s jump right into the forward() for out MultiHeadAttention component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9fa222a4112d2622a3fa68e95417463/href">https://medium.com/media/a9fa222a4112d2622a3fa68e95417463/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*lfuT-DDgVeHrFAq7_05Dvg.png" /><figcaption>Flow of operations for Multi Head Attention as per the latest TensorFlow implementation</figcaption></figure><p>We’ll go step by step repeating code snippets as needed:</p><p><strong>1. </strong>Project each of the queries, keys and values linearly. By linear projection I mean a single neural network layer without the nonlinear activation. The learnable parameters of these linear projections are important for the attention mechanism:</p><pre>queries = self.query_linear(queries)<br>keys = self.key_linear(keys)        <br>values = self.value_linear(values)</pre><p>This is how the Linears are defined:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9f93d9289b294ec36e5ba75688c8641/href">https://medium.com/media/c9f93d9289b294ec36e5ba75688c8641/href</a></iframe><p>Here input_depth total_key_depth total_value_depth and output_depth are hyperparameters of the model. Note that key and query size should match as we have to do a <a href="https://arxiv.org/abs/1508.04025">dot product</a> between them. Because Transformers don’t have recurrent layers we need not process the queries one step at a time. So the query input here is the entire sequence of queries for a particular layer.</p><p><strong>2.</strong> Split the projected inputs into required number of partitions for multi head attention. Instead of working with a separate linear projections for each head or parallel attention we divide a single projection into partitoins and perform attention independently:</p><pre>queries = self._split_heads(queries)        <br>keys = self._split_heads(keys)        <br>values = self._split_heads(values)</pre><p>Here’s the _split_heads() function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0764f270f6265c0eb104c4a30b2beffc/href">https://medium.com/media/0764f270f6265c0eb104c4a30b2beffc/href</a></iframe><p>The way we split is to reshape the inputs to have an extra <em>heads</em> dimension.</p><p><strong>3. </strong>Scale the queries by a certain factor. This is supposed to prevent the outputs from growing too big which can make learning difficult:</p><pre>queries *= self.query_scale</pre><p>The factor is calculated as the inverse square root of the partition size after splitting:</p><pre>self.query_scale = (total_key_depth//num_heads)**-0.5</pre><p><strong>4.</strong> Take the dot product between the queries and the keys (since we are doing multiplicative attention). We do that for every query and key pair with one single matmul :</p><pre>logits = torch.matmul(queries, keys.permute(0, 1, 3, 2))</pre><p>A lot is happening in that single call so let’s break it down. For illustration we’ll use the following values: sequence_length=10, total_key_depth=32, num_heads=4 which gives us partitions of size 8 after splitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*LdgVw-tgr6twHCIG1vJp7A.png" /></figure><p>To get the dot product we must transpose the (last two dimensions of the) key tensor before the matrix multiplication</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*C_g9gifaN8ig6StBX8Nbaw.png" /></figure><p>The above figures only show the last two dimensions of the input. But they are actually 4D Tensors. How can matmul do 4D Tensors??</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*xqTChgeNxhRcGgXPBiyszw.png" /></figure><p>Turns out it does a matrix multiplication for each higher dimension separately. So as long as the higher dimensions match exactly matmul can handle any number of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/1*xvg7D83FnZWhDvJQ-JeOPA.png" /></figure><p>Of course the last two dimensions should follow matrix multiplication rules.</p><p><strong>5. </strong>Apply a mask on the query key dot products. This step is required mainly for the decoder to prevent future inputs from influencing attention. We’ll cover this in part II.</p><p><strong>6.</strong> Apply <em>Softmax</em> on the dot products to convert them to probabilities:</p><pre>weights = nn.functional.softmax(logits, dim=-1)</pre><p><strong>7.</strong> Add <em>Dropout.</em> This is something that is not there in the original paper but added in the latest TensorFlow implementation.</p><p><strong>8.</strong> Using the probabilities as weights do a linear combination of the <em>values</em>. Again we use a single matmul to do the job across all values in all partitions.</p><pre>contexts = torch.matmul(weights, values)</pre><p>Continuing the earlier illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*D0d-MgkSxQTz6zrZtiGqjw.png" /></figure><p>With matrix multiplication we get all the outputs in one shot. This is what makes vectorization neat!</p><p><strong>9.</strong> Now merge the heads back. Or rather reshape the outputs to get the original 3D shape [batch, sequence length, output depth]:</p><pre>contexts = self._merge_heads(contexts)</pre><p>_merge_heads() is just the reverse of split_heads():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3c70df683947e2a14c981eaf7005ecf/href">https://medium.com/media/b3c70df683947e2a14c981eaf7005ecf/href</a></iframe><p><strong>10.</strong> Finally we do another linear projection to get the output:</p><pre>outputs = self.output_linear(contexts)</pre><p>So there you have it, Multi Head attention in ten steps. See the full implementation in GitHub <a href="https://github.com/kolloldas/torchnlp/blob/master/torchnlp/modules/transformer/sublayers.py">here</a> Now let’s go into the next core component, the <em>Positionwise Feedforward network.</em></p><h3>Positionwise Feedforward Network — The Sidekick</h3><p>Like the name indicates, this is a regular feedforward network applied to <em>each</em> time step of the Multi Head attention outputs. The network has three layers with a non-linearity like ReLU for the hidden layer. You might be wondering why do we need a feedforward network after attention; after all isn’t attention all we need 😈 ? I suspect it is needed to improve model expressiveness. As we saw earlier the multi head attention partitioned the inputs and applied attention independently. There was only a linear projection to the outputs, i.e. the partitions were combined only linearly. The <em>Positionwise Feedforward </em>network thus brings in some non-linear ‘mixing’ if we call it that. In fact for the sequence tagging task we use convolutions instead of fully connected layers. A filter of width 3 allows interactions to happen with adjacent time steps to improve performance. The implementation in PyTorch is straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2f3bad617f3b2e33bd030e6e329f8e3/href">https://medium.com/media/b2f3bad617f3b2e33bd030e6e329f8e3/href</a></iframe><p>self.layers is a nn.ModuleList which can take either linear or convolutional layers. E.g. for linear layers:</p><pre>self.layers = nn.ModuleList([<br>  nn.Linear(input_depth, filter_size), <br>  nn.Linear(filter_size, filter_size), <br>  nn.Linear(filter_size, output_depth)<br>])</pre><p>Again input_depth filter_size and output_depth are all hyperparameters. (My actual implementation is slightly more complex because it allows the total number of layers and each layer type to be configured.)</p><p>With these two components implemented our Transformer is almost completed. All we need to do now is put everything together. The next part will cover that along with some tricks that we apply to improve the model. And of course we’ll run the actual experiments.</p><p>Go to <a href="https://medium.com/@kolloldas/building-the-mighty-transformer-for-sequence-tagging-in-pytorch-part-ii-c85bf8fd145"><em>Building the Mighty Transformer for Sequence Tagging with PyTorch: Part II</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1815655cd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>