<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>Posts on Liam Atkinson</title>
        <link>https://liamatkinson.com/posts/</link>
        <description>Recent content in Posts on Liam Atkinson</description>
        <generator>Hugo -- gohugo.io</generator>
        <language>en-us</language>
        <copyright>&lt;a href=&#34;https://creativecommons.org/licenses/by-nc/4.0/&#34; target=&#34;_blank&#34; rel=&#34;noopener&#34;&gt;CC BY-NC 4.0&lt;/a&gt;</copyright>
        <lastBuildDate>Sat, 24 Jul 2021 14:11:19 +0200</lastBuildDate>
        <atom:link href="https://liamatkinson.com/posts/index.xml" rel="self" type="application/rss+xml" />
        
        <item>
            <title>Deploying Machine Learning Models (is still terrible)</title>
            <link>https://liamatkinson.com/posts/ml_deployment/</link>
            <pubDate>Sat, 24 Jul 2021 14:11:19 +0200</pubDate>
            
            <guid>https://liamatkinson.com/posts/ml_deployment/</guid>
            <description>Designing, building, and training models are hard problems. Literature is reviewed, data is gathered (and cleaned and annotated). Hours (or perhaps days? weeks?) are spent getting code to work, fixing subtle bugs, tuning training schemes. Finally, the metrics look good. It is time to deploy. And a new world of pain is entered.
Backend services are created and deployed all the time. Doing so with an ML system is often frustratingly hard.</description>
            <content type="html"><![CDATA[<p>Designing, building, and training models are hard problems. Literature is reviewed, data is gathered (and cleaned and annotated). Hours (or perhaps days? weeks?) are spent getting code to work, fixing subtle bugs, tuning training schemes. Finally, the metrics look good. It is time to deploy. And a new world of pain is entered.</p>
<p>Backend services are created and deployed all the time. Doing so with an ML system is often frustratingly hard. Why?</p>
<h4 id="moving-parts">More Moving Parts</h4>
<p>Model weights need to match the architecture. Multiple sets of weights can be produced from a single dataset and single architecture. In reality, neither the dataset nor the model architecture are likely to be static. There may be a feedback loop between the model&rsquo;s usage, and data it is trained on. Models often involve a number of preprocessing steps. This, as well as the model itself, are likely being worked on in real-time.</p>
<h4 id="performance-monitoring--distribution-shift">Performance Monitoring / Distribution Shift</h4>
<p>Related to <a href="#moving-parts">the above</a>, a model being &ldquo;deployed&rdquo; is not the end of the story. In addition to the logging and monitoring needed for traditional backend services, the distribution of input data needs to be monitored. Model performance might decrease (or increase) as the inputs change. This might mean continually annotating a subset of new data, or continually retraining. If retraining is common, a test-set of carefully selected examples might be employed, to ensure the model doesn&rsquo;t accidentally regress.</p>
<h4 id="computationally-expensive">Computationally Expensive</h4>
<p>Software goes faster by doing less (for a given bit of hardware). ML models do a lot. This means they are slower (and usually require more memory) than normal backend services. Increasing the hardware budget can get around some of these problems (and might enable the use of things like GPUs<sup id="fnref:1"><a href="#fn:1" class="footnote-ref" role="doc-noteref">1</a></sup>).</p>
<p>Depending on the application, there may be hard requirements. Perhaps running on a mobile phone, and/or processing a certain number of images per second. Requirements such as these may prohibit many types of model.</p>
<p>None of this is different from non-ML software, but higher computational cost makes these problems harder.</p>
<h4 id="confluence-of-skills">Confluence of Skills</h4>
<p>I mentioned that backend services are created and deployed all the time. This is true, but that doesn&rsquo;t mean doing so is trivial. Engineers can follow best practices developed over many years, and use battle tested technology. DevOps expertise is highly valued, and a key part of deployment. The components required to deploy a system are relatively well understood, and a team is likely to have years of experience using them.</p>
<p>Deploying ML services requires the same knowledge &ndash; as well as an understanding of the model. In spite of this, ML/Data Science teams are often separate from &ldquo;traditional&rdquo; engineering teams. A model might be handed off to a different set of engineers for deployment, or the ML team may be asked to do so themselves<sup id="fnref:2"><a href="#fn:2" class="footnote-ref" role="doc-noteref">2</a></sup>. In either case, the team doing the work does not poses all of the required knowledge. Even worse, those missing skills will have to be learned without the help of experience team members.</p>
<p>For products completely enabled by ML, a very wide range of skills might need to be employed. Model design and training, low level optimisation of c++ or cuda kernels, higher level system architecture that works with model limitations, DevOps, and so on. Building teams that know enough about all of these areas is not trivial.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Machine Learning is probably somewhere around the Trough of Disillusionment on the <a href="https://en.wikipedia.org/wiki/Hype_cycle">Gartner Hype Cycle</a> (though perhaps others feel it is still over hyped). One of the missing pieces needed to build (useful) ML products is knowledge around deployment. This gap is currently being filled. ML Engineering roles are becoming more common, and communities like <a href="https://mlops.community/">MLOps</a> are very active. There are also an increasing number of tools that try to solve various parts of the deployment process &ndash; <a href="https://www.kubeflow.org/">KubeFlow</a>, <a href="https://mlflow.org/">MLFlow</a>, <a href="https://metaflow.org/">MetaFlow</a>, <a href="https://aws.amazon.com/sagemaker/">SageMaker</a>, <a href="https://wandb.ai/site">Weights &amp; Biases</a>, and (very) many more. Of course, understanding the strengths and limitations of each of these tools is a lot of work.</p>
<p>I am thinking of writing a series of code-first blog posts on different topics related to deployment. While there are more than enough resources to be found about training any kind of model, there are far fewer high quality resources related to the practical considerations of deployment. And fundamentally, if you don&rsquo;t deploy a model after all the hard work it takes to train it, what was the point?</p>
<p>If there is anything you would like to see covered (or you are looking for advice), feel free to get in touch <a href="https://twitter.com/latkins_">@latkins_</a> on twitter.</p>
<section class="footnotes" role="doc-endnotes">
<hr>
<ol>
<li id="fn:1" role="doc-endnote">
<p>Unfortunately, you now need to deal with CUDA. <a href="#fnref:1" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
<li id="fn:2" role="doc-endnote">
<p>Fortunately, Data Scientists who are &ldquo;too good&rdquo; to code are nothing like as common as they were 5 years ago. <a href="#fnref:2" class="footnote-backref" role="doc-backlink">&#x21a9;&#xfe0e;</a></p>
</li>
</ol>
</section>
]]></content>
        </item>
        
        <item>
            <title>Notes on Attention</title>
            <link>https://liamatkinson.com/posts/attention-notes/</link>
            <pubDate>Wed, 24 Apr 2019 10:59:18 +0100</pubDate>
            
            <guid>https://liamatkinson.com/posts/attention-notes/</guid>
            <description>There are a few versions of attention that have been proposed, but this post will consider the version discussed in Attention Is All You Need, and the subsequent transformer papers (e.g. BERT, GPT, GPT2, etc). This post will only discuss attention, rather than the full transformer architecture.
Attention, as used in transformer models, is often known as self-attention, or intra-attention, and is used to combine a sequence of vectors into a single vector.</description>
            <content type="html"><![CDATA[<p>There are a few versions of attention that have been proposed, but this post will consider the version discussed in <a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a>, and the subsequent transformer papers (e.g. <a href="https://arxiv.org/abs/1810.04805">BERT</a>, <a href="https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/language-unsupervised/language_understanding_paper.pdf">GPT</a>, <a href="https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf">GPT2</a>, etc). This post will only discuss attention, rather than the full transformer architecture.</p>
<p>Attention, as used in transformer models, is often known as self-attention, or intra-attention, and is used to combine a sequence of vectors into a single vector. It is called &ldquo;attention&rdquo; due to the mechanism used in this combination &ndash; a weight is calculated for each vector in the sequence, such that all weights sum to \(1\). Each vector is scaled by its weight, and the result is the sum of these weighted vectors. Thus, &ldquo;more attention&rdquo; can be paid to vectors by assigning them larger weights.</p>
<h3 id="the-problem">The Problem</h3>
<p>Let&rsquo;s assume we have a sequence \(\textbf{w} = (w_1, w_2, \ldots, w_n)\) of tokens (which we can think of as words, for convenience). We can map these tokens to a sequence \(\textbf{x} = (x_1, x_2, \ldots, x_n)\) of continuous valued <a href="https://en.wikipedia.org/wiki/Word_embedding">embedding vectors</a> &ndash; each of our \(n\) words have an embedding vector. Many tasks in language processing require us to combine these vectors in some way. We may want to predict word level properties, like whether a token corresponds to a <a href="https://en.wikipedia.org/wiki/Named-entity_recognition">named entity</a>. We may want to predict sequence level properties, like the positive/negative <a href="https://en.wikipedia.org/wiki/Sentiment_analysis">sentiment</a> of some text. We might want to produce a summary vector, for use in an auto-regressive <a href="https://en.wikipedia.org/wiki/Language_model">language model</a>, or for the generation of a <a href="https://en.wikipedia.org/wiki/Automatic_summarization">summary</a> of the text. All of these applications (and many more) require us to combine a sequence of word embeddings somehow &ndash; if we didn&rsquo;t, any down stream task would only &ldquo;know&rdquo; about individual words. Attention is one way of performing this combination.</p>
<h4 id="recurrent-neural-networks">Recurrent Neural Networks</h4>
<p>The traditional way of combining sequential vectors is to use a Recurrent Neural Network (assuming you are using neural networks, and something as recent as RNNs can be considered traditional). These are sequential models, and their use makes some intuitive sense &ndash; humans read and understand text sequentially. They also have the nice property of being able to deal with sequences of variable length, which is important when dealing with natural language. However, their sequential nature also presents some problems. Most obviously, the computation time grows linearly with the length of the sequence. The sequential nature also directly leads to problems like vanishing/exploding gradients when training with <a href="https://en.wikipedia.org/wiki/Backpropagation_through_time">backpropagation through time</a>.</p>
<h4 id="self-attention">Self Attention</h4>
<p>Attention is a method for combining vectors that solves some of the problems that RNNs suffer from (e.g. slowness due to their sequential nature), while retaining good performance on tasks in NLP, and allowing for variable length sequences. (It should be noted that a number of methods have been proposed to reduce sequential operations in these sequential tasks &ndash; the paper cites <a href="https://arxiv.org/pdf/1610.08613.pdf">Extended Neural GPU</a>, <a href="https://arxiv.org/abs/1610.10099">ByteNet</a> and <a href="https://arxiv.org/pdf/1705.03122.pdf">ConvS2S</a> as examples). Somewhat confusingly attention was originally applied <a href="https://arxiv.org/abs/1409.0473">in conjunction with RNNs</a>, with &ldquo;Attention Is All You Need&rdquo; being the first paper (as far as I&rsquo;m aware) to exclusively use attention.</p>
<p>Attention maps a sequence of continuous query \(\textbf{q} = (q_1, q_2, \ldots, q_n), q_i \in \mathbb{R}^{d_\text{k}}\), key \(\textbf{k} = (k_1, k_2, \ldots, k_n), k_i \in \mathbb{R}^{d_\text{k}}\), and value vectors \(\textbf{v} = (v_1, v_2, \ldots, v_n), v_i \in \mathbb{R}^{d_\text{v}}\), to a sequence of continuous output vectors \(\textbf{z} = (z_1, z_2, \ldots, z_n), z_i \in \mathbb{R}^{d_\text{v}}\). Each output \(z_i\) is effectively a weighted sum of \(\textbf{v}\), where the weight is computed by a compatibility function applied between \(q_i\) and each \(k_j\). The specific compatibility function used in the transformer model is &ldquo;scaled dot product attention&rdquo;. This takes the dot product between any query-key pair, and scales the result by the square root of the dimension of their vectors, giving a continuous valued output between \(-1\) and \(1\). These values are normalised with a \(\text{softmax}\), and the result treated as weights in a weighted sum. For a single output, \(z_j\), this looks like:</p>
<p>\[\begin{align}
\textbf{c} &amp;= \left(\frac{q_j \cdot k_1}{\sqrt{d_k}}, \frac{q_j \cdot k_2}{\sqrt{d_k}}, \ldots, \frac{q_j \cdot k_n}{\sqrt{d_k}}\right)\\\<br>
\text{softmax}(\textbf{c})_i &amp;= \frac{e^{c_i}}{\sum_{j = 1}^n e^{c_j}}\\\<br>
\textbf{a} &amp;= \left(\text{softmax}(\textbf{c})_1, \text{softmax}(\textbf{c})_2, \ldots, \text{softmax}(\textbf{c})_n \right)\\\<br>
\textbf{z}_j &amp;= \sum_{i=1}^{n} a_i \textbf{v}_i
\end{align}\]</p>
<p>To make the calculation simpler, we can create three input matrices by stacking our vector inputs:</p>
<p>\[\begin{align}
Q &amp;\in \mathbb{R}^{n \times d_\text{k}} \\\<br>
K &amp;\in \mathbb{R}^{n \times d_\text{k}} \\\<br>
V &amp;\in \mathbb{R}^{n \times d_\text{v}}
\end{align}\]</p>
<p>This allows us to write the basic equation of attention as:
\[\text{Attention}(K, Q, V) = \text{softmax} \left( \frac{Q K^T}{\sqrt{d_k}}  \right) V \]</p>
<p>Or, in PyTorch, as:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">import</span> torch.nn.functional <span style="color:#f92672">as</span> F

<span style="color:#66d9ef">def</span> <span style="color:#a6e22e">attn</span>(Q, K, V):
    a <span style="color:#f92672">=</span> F<span style="color:#f92672">.</span>softmax((Q <span style="color:#960050;background-color:#1e0010">@</span> K<span style="color:#f92672">.</span>t()) <span style="color:#f92672">/</span> Q<span style="color:#f92672">.</span>shape[<span style="color:#f92672">-</span><span style="color:#ae81ff">1</span>], dim<span style="color:#f92672">=-</span><span style="color:#ae81ff">1</span>)
    <span style="color:#66d9ef">return</span> a <span style="color:#960050;background-color:#1e0010">@</span> V
</code></pre></div><h5 id="what-does-this-mean">What does this mean?</h5>
<p>Lets think back to our original sequence of embeddings, \(\textbf{x}\). We can choose that \(Q\), \(K\), and \(V\) are all equal to \(\textbf{x}\). In the paper, this is called &ldquo;Encoder self-attention&rdquo; (one of three ways attention is used). Lets say our input tokens are &ldquo;The man walked the dog&rdquo;. To compute the new vectors for each word, we take the projection of each words embedding onto each of the other embeddings (scaled by \(\sqrt{d_k}\) ), normalize these projections so they sum to \(1\), and then sum all of the words embeddings multiplied with the corresponding weight. Thus we get a vector who&rsquo;s magnitude can&rsquo;t grow, and that is a linear combination of all of input embeddings. Interestingly, this means the &ldquo;new&rdquo; vector for a word, \(z_{i}\), will give more weight in the sum to the embeddings, \(x_{j}\), that were similar to its own. To make this a bit more explicit, let&rsquo;s imagine our embeddings \(\textbf{x}\) correspond to the sentence &ldquo;the man walked the dog&rdquo;. We want to compute a new vector the first word, &ldquo;the&rdquo;. To do so, we compute the similarity between &ldquo;the&rdquo;&rsquo;s embedding vector, and the embedding vectors for &ldquo;the&rdquo;, &ldquo;man&rdquo;, &ldquo;walked&rdquo;, &ldquo;the&rdquo;, &ldquo;dog&rdquo;. These similarities are normalised so they sum to \(1\) (and the two &ldquo;the&rdquo; tokens will contribute the maximum similarity score, \(\frac{1}{\sqrt{d_k}}\) ). The new vector is therefore:</p>
<p>\[\begin{align}
z_{\text{the}} &amp;= \text{attention_weight}(\text{&ldquo;the&rdquo;}, \text{&ldquo;the&rdquo;}) \times \text{embedding}(\text{&ldquo;the&rdquo;}) \\\<br>
&amp;+ \text{attention_weight}(\text{&ldquo;the&rdquo;}, \text{&ldquo;man&rdquo;}) \times \text{embedding}(\text{&ldquo;man&rdquo;}) \\\<br>
&amp;+ \text{attention_weight}(\text{&ldquo;the&rdquo;}, \text{&ldquo;walked&rdquo;}) \times \text{embedding}(\text{&ldquo;walked&rdquo;}) \\\<br>
&amp;+ \ldots
\end{align}\]</p>
<h4 id="multi-headed-attention">Multi-Headed Attention</h4>
<p>The paper notes that &ldquo;additive attention&rdquo; performs better than the self attention described above, though it is much slower. Additive attention uses a more complicated compatibility function &ndash; namely a feed forward neural network. Naturally, this is slower than a highly optimized dot-product. Also naturally, it is more expressive. A single dot product can only give us the &ldquo;overall&rdquo; similarity between two vectors, while a feed forward layer can consider combinations of different subspaces.</p>
<p>As a solution, multiple attention &ldquo;heads&rdquo; are used in parallel, each of which can focus on a different subspace. We parameterise the number of heads with \(h\).</p>
<p>\[\begin{align}
\text{Multihead}(Q, K, V) &amp;= \left( \overset{h}{\underset{i = 0}{\parallel}} \text{head}_i \right) W^{O} \\\<br>
\text{head}_i &amp;= \text{Attention}(Q W_i^Q, K W_i^K, V W_i^V)
\end{align}\]</p>
<p>Where \(\parallel\) indicates the concatenation of vectors. Note that \(Q, K, V\) differ from the single headed version, and all are in \( \mathbb{R}^{n \times d_{\text{model}}}\).</p>
<p>Compared to the version of attention discussed in previously, each attention head has three additional matrices, used to learn a linear projection of each of \(Q, K,\) and \(V\). Additionally, \(W^{O}\) is used to project the concatenated output of all heads into \(d_\text{model}\).</p>
<p>\[\begin{align}
W_{i}^Q &amp;\in \mathbb{R}^{d_\text{model} \times d_\text{k}} \\\<br>
W_{i}^K &amp;\in \mathbb{R}^{d_\text{model} \times d_\text{k}} \\\<br>
W_{i}^V &amp;\in \mathbb{R}^{d_\text{model} \times d_\text{v}} \\\<br>
W^O &amp;\in \mathbb{R}^{ h d_\text{v} \times d_\text{model} }
\end{align}\]</p>
<p>A naive PyTorch implementation looks like this:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">import</span> math
<span style="color:#f92672">import</span> torch
<span style="color:#f92672">import</span> torch.nn.functional <span style="color:#f92672">as</span> F
<span style="color:#f92672">from</span> torch <span style="color:#f92672">import</span> nn


<span style="color:#66d9ef">class</span> <span style="color:#a6e22e">MultiHeadNaive</span>(nn<span style="color:#f92672">.</span>Module):
    <span style="color:#66d9ef">def</span> __init__(self, d_model, d_k, d_v, h):
        super()<span style="color:#f92672">.</span>__init__()

        self<span style="color:#f92672">.</span>heads <span style="color:#f92672">=</span> nn<span style="color:#f92672">.</span>ModuleList([AttnHead(d_model, d_k, d_v) <span style="color:#66d9ef">for</span> _ <span style="color:#f92672">in</span> range(h)])
        self<span style="color:#f92672">.</span>Wo <span style="color:#f92672">=</span> nn<span style="color:#f92672">.</span>Linear(h <span style="color:#f92672">*</span> d_v, d_model)

    <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">forward</span>(self, Q, K, V):
        head_results <span style="color:#f92672">=</span> [head(Q, K, V) <span style="color:#66d9ef">for</span> head <span style="color:#f92672">in</span> self<span style="color:#f92672">.</span>heads]
        <span style="color:#66d9ef">return</span> self<span style="color:#f92672">.</span>Wo(torch<span style="color:#f92672">.</span>cat(head_results, dim<span style="color:#f92672">=-</span><span style="color:#ae81ff">1</span>))


<span style="color:#66d9ef">class</span> <span style="color:#a6e22e">AttnHead</span>(nn<span style="color:#f92672">.</span>Module):
    <span style="color:#66d9ef">def</span> __init__(self, d_model, d_k, d_v):
        super()<span style="color:#f92672">.</span>__init__()

        self<span style="color:#f92672">.</span>Wq <span style="color:#f92672">=</span> nn<span style="color:#f92672">.</span>Linear(d_model, d_k)
        self<span style="color:#f92672">.</span>Wk <span style="color:#f92672">=</span> nn<span style="color:#f92672">.</span>Linear(d_model, d_k)
        self<span style="color:#f92672">.</span>Wv <span style="color:#f92672">=</span> nn<span style="color:#f92672">.</span>Linear(d_model, d_v)

    <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">forward</span>(self, Q, K, V):
        <span style="color:#66d9ef">return</span> attn(self<span style="color:#f92672">.</span>Wq(Q), self<span style="color:#f92672">.</span>Wk(K), self<span style="color:#f92672">.</span>Wv(V))


<span style="color:#66d9ef">def</span> <span style="color:#a6e22e">attn</span>(Q, K, V):
    a <span style="color:#f92672">=</span> F<span style="color:#f92672">.</span>softmax((Q <span style="color:#960050;background-color:#1e0010">@</span> K<span style="color:#f92672">.</span>t()) <span style="color:#f92672">/</span> math<span style="color:#f92672">.</span>sqrt(Q<span style="color:#f92672">.</span>shape[<span style="color:#f92672">-</span><span style="color:#ae81ff">1</span>]), dim<span style="color:#f92672">=-</span><span style="color:#ae81ff">1</span>)
    <span style="color:#66d9ef">return</span> a <span style="color:#960050;background-color:#1e0010">@</span> V
</code></pre></div><p>Most implementations are slightly more complicated for reasons of computational efficiency. It is possible to perform all of the \(W^{*}_{i}\) multiplications at one, by choosing a larger matrix:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-python" data-lang="python"><span style="color:#f92672">import</span> math

<span style="color:#f92672">import</span> torch
<span style="color:#f92672">import</span> torch.nn.functional <span style="color:#f92672">as</span> F
<span style="color:#f92672">from</span> torch <span style="color:#f92672">import</span> nn


<span style="color:#66d9ef">class</span> <span style="color:#a6e22e">MultiHead</span>(nn<span style="color:#f92672">.</span>Module):
    <span style="color:#66d9ef">def</span> __init__(self, h, d_model):
        super()<span style="color:#f92672">.</span>__init__()

        <span style="color:#66d9ef">assert</span> d_model <span style="color:#f92672">%</span> h <span style="color:#f92672">==</span> <span style="color:#ae81ff">0</span>, f<span style="color:#e6db74">&#34;d_model, {d_model} not divisible by number of heads, {h}&#34;</span>
        self<span style="color:#f92672">.</span>d_model <span style="color:#f92672">=</span> d_model
        self<span style="color:#f92672">.</span>d_k <span style="color:#f92672">=</span> d_model <span style="color:#f92672">//</span> h
        self<span style="color:#f92672">.</span>h <span style="color:#f92672">=</span> h

        <span style="color:#75715e"># These W^{*} linear layers contain _all_ W^{*}_{i} matices for each head.</span>
        self<span style="color:#f92672">.</span>WQ <span style="color:#f92672">=</span> nn<span style="color:#f92672">.</span>Linear(d_model, d_model)
        self<span style="color:#f92672">.</span>WK <span style="color:#f92672">=</span> nn<span style="color:#f92672">.</span>Linear(d_model, d_model)
        self<span style="color:#f92672">.</span>WV <span style="color:#f92672">=</span> nn<span style="color:#f92672">.</span>Linear(d_model, d_model)
        self<span style="color:#f92672">.</span>WO <span style="color:#f92672">=</span> nn<span style="color:#f92672">.</span>Linear(d_model, d_model)

    <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">forward</span>(self, Q, K, V):
        bs <span style="color:#f92672">=</span> Q<span style="color:#f92672">.</span>shape[<span style="color:#ae81ff">0</span>]

        n <span style="color:#f92672">=</span> Q<span style="color:#f92672">.</span>shape[<span style="color:#ae81ff">1</span>]

        <span style="color:#75715e"># (bs x n x d_model) -&gt; (bs x n x h x d_k) -&gt; (bs x h x n x d_k)</span>
        Qs <span style="color:#f92672">=</span> self<span style="color:#f92672">.</span>WQ(Q)<span style="color:#f92672">.</span>view(bs, <span style="color:#f92672">-</span><span style="color:#ae81ff">1</span>, self<span style="color:#f92672">.</span>h, self<span style="color:#f92672">.</span>d_k)<span style="color:#f92672">.</span>transpose(<span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">2</span>)
        Ks <span style="color:#f92672">=</span> self<span style="color:#f92672">.</span>WK(K)<span style="color:#f92672">.</span>view(bs, <span style="color:#f92672">-</span><span style="color:#ae81ff">1</span>, self<span style="color:#f92672">.</span>h, self<span style="color:#f92672">.</span>d_k)<span style="color:#f92672">.</span>transpose(<span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">2</span>)
        Vs <span style="color:#f92672">=</span> self<span style="color:#f92672">.</span>WV(V)<span style="color:#f92672">.</span>view(bs, <span style="color:#f92672">-</span><span style="color:#ae81ff">1</span>, self<span style="color:#f92672">.</span>h, self<span style="color:#f92672">.</span>d_k)<span style="color:#f92672">.</span>transpose(<span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">2</span>)

        batched_attn <span style="color:#f92672">=</span> attn(Qs, Ks, Vs)

        <span style="color:#75715e"># (bs x h x n x d_k) -&gt; (bs x n x h x d_k) -&gt; (bs x n x d_model)</span>
        concatted_attn <span style="color:#f92672">=</span> batched_attn<span style="color:#f92672">.</span>transpose(<span style="color:#ae81ff">1</span>, <span style="color:#ae81ff">2</span>)<span style="color:#f92672">.</span>contiguous()<span style="color:#f92672">.</span>view(bs, <span style="color:#f92672">-</span><span style="color:#ae81ff">1</span>, self<span style="color:#f92672">.</span>d_model)

        <span style="color:#66d9ef">return</span> self<span style="color:#f92672">.</span>WO(concatted_attn)


<span style="color:#66d9ef">def</span> <span style="color:#a6e22e">attn</span>(Q, K, V):
    <span style="color:#75715e"># Q.matmul(K.transpose(-2, -1): (bs x h x n x d_k) x (bs x h x d_k x n) -&gt; (bs x h x n x n)</span>
    a <span style="color:#f92672">=</span> F<span style="color:#f92672">.</span>softmax((Q<span style="color:#f92672">.</span>matmul(K<span style="color:#f92672">.</span>transpose(<span style="color:#f92672">-</span><span style="color:#ae81ff">2</span>, <span style="color:#f92672">-</span><span style="color:#ae81ff">1</span>))) <span style="color:#f92672">/</span> math<span style="color:#f92672">.</span>sqrt(Q<span style="color:#f92672">.</span>shape[<span style="color:#f92672">-</span><span style="color:#ae81ff">1</span>]), dim<span style="color:#f92672">=-</span><span style="color:#ae81ff">1</span>)

    <span style="color:#75715e"># a.matmul(V): (bs x h x n x n) x (bs x h x n x d_k) -&gt; (bs x h x n x d_k)</span>
    <span style="color:#66d9ef">return</span> a<span style="color:#f92672">.</span>matmul(V)
</code></pre></div><p>This implementation allows more operations to be parallelised, though is a bit more fiddly in terms of keeping track of dimensions. This is a simplified version of the implementation found <a href="http://nlp.seas.harvard.edu/2018/04/03/attention.html">here</a>.</p>
<h3 id="notes">Notes</h3>
<p>It is worth pointing out that neither of these versions of attention actually know about the positions of any of the inputs within a sequence &ndash; changing the order of the sequence would have no impact on the outcome. The full transformer model deals with this by adding &ldquo;positional embeddings&rdquo;. It is also worth point out that attention alone doesn&rsquo;t contain a non-linearity (though the \(\text{softmax}\) used to compute attention weights is non-linear, the weighted sum itself is a linear combination).</p>
<p>An interesting way to think about attention is as an \(n \times n\) matrix. This could be interpreted as describing weighted edges in a graph, where each node is a token. Each attention head learns how to construct this graph for different inputs.</p>
]]></content>
        </item>
        
    </channel>
</rss>
