<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xml:base="https://jaykmody.com" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Jay Mody Blog</title>
    <link>https://jaykmody.com</link>
    <atom:link href="https://jaykmody.com/feed.xml" rel="self" type="application/rss+xml" />
    <description>A blog about things and stuff.</description>
    <language>en</language>
    <item>
      <title>Speculative Sampling</title>
      <link>https://jaykmody.com/blog/speculative-sampling/</link>
      <description>&lt;p&gt;This post provides an overview, implementation, and time complexity analysis of DeepMind&#39;s paper &lt;a href=&quot;https://arxiv.org/abs/2302.01318&quot;&gt;Accelerating Large Language Model Decoding with Speculative Sampling&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Code for this blog post can be found at &lt;a href=&quot;https://github.com/jaymody/speculative-sampling&quot;&gt;github.com/jaymody/speculative-samlping&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;EDIT (Apr 13th, 2023):&lt;/strong&gt; Updated code and time complexity to avoid the extra forward pass of the draft model (credits to &lt;a href=&quot;https://github.com/jaymody/speculative-sampling/issues/1&quot;&gt;KexinFeng&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;&lt;/p&gt;&lt;div class=&quot;table-of-contents&quot;&gt;&lt;ul&gt;&lt;/ul&gt;&lt;/div&gt;&lt;p&gt;&lt;/p&gt;
&lt;h1 id=&quot;autoregressive-sampling&quot; tabindex=&quot;-1&quot;&gt;Autoregressive Sampling&lt;/h1&gt;
&lt;p&gt;The standard way of generating text from a language model is with &lt;strong&gt;autoregressive sampling&lt;/strong&gt;, here&#39;s the algorithm as defined in the paper:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://i.imgur.com/YrLebkI.png&quot; alt=&quot;&quot; /&gt;&lt;/figure&gt;
&lt;p&gt;In code:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def autoregressive_sampling(x, model, N):
    n = len(x)
    T = len(x) + N

    while n &amp;lt; T:
        x = np.append(x, sample(model(x)[-1]))
        n += 1

    return x
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Where:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;x&lt;/code&gt; is a list of integers representing the token ids of the input text&lt;/li&gt;
&lt;li&gt;&lt;code&gt;model&lt;/code&gt; is a language model (like GPT-2) that accepts as input a list of token ids of length &lt;code&gt;seq_len&lt;/code&gt; and outputs a matrix of probabilities of shape &lt;code&gt;[seq_len, vocab_size]&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;N&lt;/code&gt; is the number of tokens we want to decode.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The time complexity of this algorithm is &#92;(O(N &#92;cdot t_{&#92;text{model}})&#92;):&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&#92;(N&#92;): The number of iterations of our while loop, which is just the number of tokens to decode &#92;(N&#92;).&lt;/li&gt;
&lt;li&gt;&#92;(t_{&#92;text{model}}&#92;): The time complexity of each iteration in the loop, which is just the time taken for a single forward pass of our model &#92;(t_{&#92;text{model}}&#92;).&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;speculative-sampling&quot; tabindex=&quot;-1&quot;&gt;Speculative Sampling&lt;/h1&gt;
&lt;p&gt;In &lt;strong&gt;speculative sampling&lt;/strong&gt;, we have two models:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;A smaller, faster &lt;strong&gt;draft model&lt;/strong&gt; (e.g. DeepMind&#39;s 7B Chinchilla model)&lt;/li&gt;
&lt;li&gt;A larger, slower &lt;strong&gt;target model&lt;/strong&gt; (e.g. DeepMind&#39;s 70B Chinchilla model)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The idea is that the draft model &lt;em&gt;speculates&lt;/em&gt; what the output is &#92;(K&#92;) steps into the future, while the target model determines how many of those tokens we should &lt;em&gt;accept&lt;/em&gt;. Here&#39;s an outline of the algorithm:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The draft model decodes &#92;(K&#92;) tokens in the regular autoregressive fashion.&lt;/li&gt;
&lt;li&gt;We get the probability outputs of the target and draft model on the new predicted sequence.&lt;/li&gt;
&lt;li&gt;We compare the target and draft model probabilities to determine how many of the &#92;(K&#92;) tokens we want to keep based on some &lt;strong&gt;rejection criteria&lt;/strong&gt;. If a token is rejected, we &lt;strong&gt;resample&lt;/strong&gt; it using a combination of the two distributions and don&#39;t accept any more tokens.&lt;/li&gt;
&lt;li&gt;If all &#92;(K&#92;) tokens are accepted, we can sample an additional final token from the target model probability output.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;As such, instead of decoding a single token at each iteration, speculative sampling decodes between 1 to &#92;(K + 1&#92;) tokens per iteration. If no tokens are accepted, we resample guaranteeing at least 1 token is decoded. If all &#92;(K&#92;) tokens are accepted, then we can also sample a final token from the target models probability distribution, giving us a total of &#92;(K + 1&#92;) tokens decoded.&lt;/p&gt;
&lt;p&gt;For example, consider the common idiom &amp;quot;The apple doesn&#39;t fall far from the tree&amp;quot;. Given just the first part of the phrase, &amp;quot;The apple doesn&#39;t fall&amp;quot;, in speculative sampling with &#92;(K=4&#92;):&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The draft model speculates the output to be &amp;quot;far from the tree&amp;quot; (4 tokens)&lt;/li&gt;
&lt;li&gt;The target model looks at those tokens, and decides to accept them all, and also sample a final token (i.e. maybe it samples a period &amp;quot;.&amp;quot;).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;As such, in a single iteration, we were able to decode 5 tokens instead of just a single token. However, this may not always be the case, consider instead the input &amp;quot;Not all heroes&amp;quot;:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The draft model speculates the output to be &amp;quot;wear capes and hats&amp;quot; (4 tokens)&lt;/li&gt;
&lt;li&gt;The target model looks at those tokens, but decides to only accepts the first two &amp;quot;wear capes&amp;quot; and discard the rest.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;In this case, only 2 tokens were accepted.&lt;/p&gt;
&lt;p&gt;As long as the draft model is sufficiently faster than the target model &lt;strong&gt;while also&lt;/strong&gt; maintaining a high enough &lt;strong&gt;acceptance rate&lt;/strong&gt;, then speculative sampling should yield a speedup.&lt;/p&gt;
&lt;p&gt;The intuition behind speculative sampling is that certain strings of tokens (common phrases, pronouns, punctuation, etc ...) are fairly easy to predict, so a smaller, less powerful, but faster draft model should be able to quickly predict these instead of having our slower target model doing all the work.&lt;/p&gt;
&lt;p&gt;Another important property of speculative sampling is that it is &lt;strong&gt;mathematically equivalent&lt;/strong&gt; to sampling from the target model, due to the way the rejection criteria and resampling method are designed. The &lt;a href=&quot;https://arxiv.org/pdf/2302.01318.pdf#page=10&quot;&gt;proof for this is shown in the paper (Theorem 1)&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Finally, speculative sampling requires no changes to the model&#39;s architecture, training, or anything like that. It can be used with existing models alongside other inference techniques such as quantization, hardware acceleration, flash attention, etc ... It can also be used with top-p/top-k/temperature.&lt;/p&gt;
&lt;p&gt;Here&#39;s the full algorithm as defined in the paper:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://i.imgur.com/rhR3U46.png&quot; alt=&quot;&quot; /&gt;&lt;/figure&gt;
&lt;p&gt;In code (&lt;a href=&quot;https://github.com/jaymody/speculative-sampling&quot;&gt;full implementation here&lt;/a&gt;):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def max_fn(x):
    x_max = np.where(x &amp;gt; 0, x, 0)
    return x_max / np.sum(x_max)

def speculative_sampling(x, draft_model, target_model, N, K):
    # NOTE: paper indexes arrays starting from 1, python indexes from 0, so
    # we have to add an extra -1 term when indexing using n, T, or t
    n = len(x)
    T = len(x) + N

    while n &amp;lt; T:
        # Step 1: auto-regressive decode K tokens from draft model and get final p
        x_draft = x
        for _ in range(K):
            p = draft_model(x_draft)
            x_draft = np.append(x_draft, sample(p[-1]))

        # Step 2: target model forward passes on x_draft
        q = target_model(x_draft)

        # Step 3: append draft tokens based on rejection criterion and resample
        # a token on rejection
        all_accepted = True
        for _ in range(K):
            i = n - 1
            j = x_draft[i + 1]
            if np.random.random() &amp;lt; min(1, q[i][j] / p[i][j]):  # accepted
                x = np.append(x, j)
                n += 1
            else:  # rejected
                x = np.append(x, sample(max_fn(q[i] - p[i])))  # resample
                n += 1
                all_accepted = False
                break

        # Step 4: if all draft tokens were accepted, sample a final token
        if all_accepted:
            x = np.append(x, sample(q[-1]))
            n += 1

        # just keeping my sanity
        assert n == len(x), f&amp;quot;{n} {len(x)}&amp;quot;

    return x
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The time complexity for this algorithm is &#92;(O(&#92;frac{N}{r(K + 1)} &#92;cdot (t_{&#92;text{draft}}K + t_{&#92;text{target}}))&#92;).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&#92;(&#92;frac{N}{r(K+1)}&#92;): The number of iterations in our while loop. This works out to the number of tokens we want to decode &#92;(N&#92;) divided by the average number of tokens that get decoded per iteration &#92;(r(K + 1)&#92;). The paper doesn&#39;t directly report the average number of tokens that get decoded per iteration, instead they provide the acceptance rate &#92;(r&#92;) (which is the average number of tokens decoded per iteration divided by &#92;(K + 1&#92;))&lt;sup class=&quot;footnote-ref&quot;&gt;&lt;a href=&quot;https://jaykmody.com/blog/speculative-sampling/#fn1&quot; id=&quot;fnref1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;. As such, we can recover the average number of tokens decoded simply by multiplying &#92;(r&#92;) by &#92;(K + 1&#92;).&lt;/li&gt;
&lt;li&gt;&#92;(t_{&#92;text{draft}}K + t_{&#92;text{target}}&#92;): The time complexity for each iteration in the loop. The &#92;(t_{&#92;text{target}}&#92;) term is for the single forward pass of the target model in step 2, and &#92;(t_{&#92;text{draft}}K&#92;) is for the &#92;(K&#92;) forward passes of the draft model in step 1.&lt;/li&gt;
&lt;/ul&gt;
&lt;h1 id=&quot;speedup-results&quot; tabindex=&quot;-1&quot;&gt;Speedup Results&lt;/h1&gt;
&lt;p&gt;The paper reports the following speedups for their 70B Chinchilla model (using a specially trained 7B Chinchilla as the draft model):&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://i.imgur.com/3ZcmZfr.png&quot; alt=&quot;&quot; /&gt;&lt;/figure&gt;
&lt;p&gt;You can see that there was no performance degradation and the decoding process is 2 times faster as compared to autoregressive decoding.&lt;/p&gt;
&lt;p&gt;Let&#39;s compare these empirical speedup numbers to theoretical speedup numbers, which we can calculate using our time complexity equations:&lt;/p&gt;
&lt;p&gt;&#92;[
&#92;begin{align}
&#92;text{speedup} &amp;amp; = &#92;frac{&#92;text{time complexity of autoregressive}}{&#92;text{time complexity of speculative}} &#92;&#92;
&amp;amp; = &#92;frac{N&#92;cdot t_{&#92;text{target}}}{&#92;frac{N}{r(K + 1)} &#92;cdot (t_{&#92;text{draft}}K + t_{&#92;text{target}})}
&amp;amp; &#92;&#92;
&amp;amp; = &#92;frac{r(K + 1) &#92;cdot t_{&#92;text{target}}}{t_{&#92;text{draft}}K + t_{&#92;text{target}}}
&#92;end{align}
&#92;]&lt;/p&gt;
&lt;p&gt;Using the values provided in the paper:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&#92;(K = 4&#92;)&lt;/li&gt;
&lt;li&gt;&#92;(t_{&#92;text{draft}} = 1.8&#92;text{ms}&#92;)&lt;/li&gt;
&lt;li&gt;&#92;(t_{&#92;text{target}} = 14.1&#92;text{ms}&#92;)&lt;/li&gt;
&lt;li&gt;&#92;(r = 0.8&#92;) for HumanEval and &#92;(r = 0.62&#92;) for XSum (see figure 1 in the paper)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For HumanEval we get a theoretical speedup of &lt;strong&gt;2.65&lt;/strong&gt;, while the paper reports an empirical speedup of &lt;strong&gt;2.46&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;For XSum we get a theoretical speedup of &lt;strong&gt;2.05&lt;/strong&gt;, while the paper reports an empirical speedup of &lt;strong&gt;1.92&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;We can reproduce these results by &lt;a href=&quot;https://github.com/jaymody/speculative-sampling&quot;&gt;running our implementation with GPT-2 1.5B as our target model and GPT-2 124M as our draft model&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;python main.py &#92;
    --prompt &amp;quot;Alan Turing theorized that computers would one day become&amp;quot; &#92;
    --n_tokens_to_generate 40 &#92;
    --draft_model_size &amp;quot;124M&amp;quot; &#92;
    --target_model_size &amp;quot;1558M&amp;quot; &#92;
    --K 4 &#92;
    --temperature 0 &#92;
    --seed 123
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Which gives a speedup of &lt;strong&gt;2.23&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;Time = 60.64s
Text = Alan Turing theorized that computers would one day become so powerful that they would be able to think like humans.

In the 1950s, he proposed a way to build a computer that could think like a human. He called it the &amp;quot;T

Speculative Decode
------------------
Time = 27.15s
Text = Alan Turing theorized that computers would one day become so powerful that they would be able to think like humans.

In the 1950s, he proposed a way to build a computer that could think like a human. He called it the &amp;quot;T
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note, the output is the exact same for both methods due to the use of &lt;code&gt;temperature = 0&lt;/code&gt;, which corresponds to &lt;strong&gt;greedy sampling&lt;/strong&gt; (always taking the token with the highest probability). If a non-zero temperature were used, this would not be the case. Although speculative sampling is mathematically the same as sampling from the target model directly, the results of autoregressive and speculative sampling will be different due to randomness. Speculative sampling giving a different result than autoregressive sampling is akin to running autoregressive sampling but with a different seed. When &lt;code&gt;temperature = 0&lt;/code&gt; however, a 100% of the probability is assigned to a single token, so sampling from the distribution becomes deterministic, hence why the outputs are the same. If we instead used &lt;code&gt;temperature = 0.5&lt;/code&gt;, we&#39;d get different outputs:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Autoregressive Decode
---------------------
Time = 49.06s
Text = Alan Turing theorized that computers would one day become self-aware. This is known as the &amp;quot;Turing Test&amp;quot; and it is a test that has been used to determine if a computer is intelligent.

The Turing Test is based on the

Speculative Decode
------------------
Time = 31.60s
Text = Alan Turing theorized that computers would one day become so powerful that they would be able to simulate the behavior of human minds. The Turing Test is a test that asks a computer to recognize whether a given piece of text is a human or a computer generated
&lt;/code&gt;&lt;/pre&gt;
&lt;hr class=&quot;footnotes-sep&quot; /&gt;
&lt;section class=&quot;footnotes&quot;&gt;
&lt;ol class=&quot;footnotes-list&quot;&gt;
&lt;li id=&quot;fn1&quot; class=&quot;footnote-item&quot;&gt;&lt;p&gt;The wording from the paper for &#92;(r&#92;) is a bit misleading. The paper states that &#92;(r&#92;) is &amp;quot;the average number of tokens &lt;strong&gt;accepted&lt;/strong&gt; divided by &#92;(K + 1&#92;)&amp;quot;. This gives the impression they are reporting the rate at which &lt;strong&gt;just&lt;/strong&gt; the draft tokens are accepted (i.e. don&#39;t include the resampled and final sampled tokens). In actuality, &#92;(r&#92;) is &amp;quot;the average number of tokens &lt;strong&gt;decoded&lt;/strong&gt; divided by &#92;(K + 1&#92;)&amp;quot; meaning we also include the resampled and final token. This would make sense since otherwise, they would have to divided &#92;(r&#92;) by &#92;(K&#92;) and not &#92;(K + 1&#92;) when reporting &#92;(r&#92;). I confirmed this with the authors of the paper. &lt;a href=&quot;https://jaykmody.com/blog/speculative-sampling/#fnref1&quot; class=&quot;footnote-backref&quot;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</description>
      <pubDate>Wed, 08 Feb 2023 00:00:00 +0000</pubDate>
      <dc:creator>Jay Mody</dc:creator>
      <guid>https://jaykmody.com/blog/speculative-sampling/</guid>
    </item>
    <item>
      <title>GPT in 60 Lines of NumPy</title>
      <link>https://jaykmody.com/blog/gpt-from-scratch/</link>
      <description>&lt;p&gt;In this post, we&#39;ll implement a GPT from scratch in just &lt;a href=&quot;https://github.com/jaymody/picoGPT/blob/29e78cc52b58ed2c1c483ffea2eb46ff6bdec785/gpt2_pico.py#L3-L58&quot;&gt;60 lines of &lt;code&gt;numpy&lt;/code&gt;&lt;/a&gt;. We&#39;ll then load the trained GPT-2 model weights released by OpenAI into our implementation and generate some text.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;This post assumes familiarity with Python, NumPy, and some basic experience with neural networks.&lt;/li&gt;
&lt;li&gt;This implementation is for educational purposes, so it&#39;s missing lots of features/improvements on purpose to keep it as simple as possible while remaining complete.&lt;/li&gt;
&lt;li&gt;All the code for this blog post can be found at &lt;a href=&quot;https://github.com/jaymody/picoGPT&quot;&gt;github.com/jaymody/picoGPT&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://news.ycombinator.com/item?id=34726115&quot;&gt;Hacker news thread&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://jiqihumanr.github.io/2023/04/13/gpt-from-scratch/&quot;&gt;Chinese translation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://mlwizardry.netlify.app/nlp/gpt-from-scratch/&quot;&gt;Japanese translation&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;EDIT (Feb 9th, 2023):&lt;/strong&gt; Added a &amp;quot;What&#39;s Next&amp;quot; section and updated the intro with some notes.&lt;br /&gt;
&lt;strong&gt;EDIT (Feb 28th, 2023):&lt;/strong&gt; Added some additional sections to &amp;quot;What&#39;s Next&amp;quot;.&lt;/p&gt;
&lt;h2 id=&quot;table-of-contents&quot; tabindex=&quot;-1&quot;&gt;Table of Contents&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;/p&gt;&lt;div class=&quot;table-of-contents&quot;&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#table-of-contents&quot;&gt;Table of Contents&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#what-is-a-gpt%3F&quot;&gt;What is a GPT?&lt;/a&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#input-%2F-output&quot;&gt;Input / Output&lt;/a&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#input&quot;&gt;Input&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#output&quot;&gt;Output&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#generating-text&quot;&gt;Generating Text&lt;/a&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#autoregressive&quot;&gt;Autoregressive&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#sampling&quot;&gt;Sampling&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#training&quot;&gt;Training&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#prompting&quot;&gt;Prompting&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#setup&quot;&gt;Setup&lt;/a&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#encoder&quot;&gt;Encoder&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#hyperparameters&quot;&gt;Hyperparameters&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#parameters&quot;&gt;Parameters&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#basic-layers&quot;&gt;Basic Layers&lt;/a&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#gelu&quot;&gt;GELU&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#softmax&quot;&gt;Softmax&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#layer-normalization&quot;&gt;Layer Normalization&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#linear&quot;&gt;Linear&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#gpt-architecture&quot;&gt;GPT Architecture&lt;/a&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#embeddings&quot;&gt;Embeddings&lt;/a&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#token-embeddings&quot;&gt;Token Embeddings&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#positional-embeddings&quot;&gt;Positional Embeddings&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#combined&quot;&gt;Combined&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#decoder-stack&quot;&gt;Decoder Stack&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#projection-to-vocab&quot;&gt;Projection to Vocab&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#decoder-block&quot;&gt;Decoder Block&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#position-wise-feed-forward-network&quot;&gt;Position-wise Feed Forward Network&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#multi-head-causal-self-attention&quot;&gt;Multi-Head Causal Self Attention&lt;/a&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#attention&quot;&gt;Attention&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#self&quot;&gt;Self&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#causal&quot;&gt;Causal&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#multi-head&quot;&gt;Multi-Head&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#putting-it-all-together&quot;&gt;Putting it All Together&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#what-next%3F&quot;&gt;What Next?&lt;/a&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#gpu%2Ftpu-support&quot;&gt;GPU/TPU Support&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#backpropagation&quot;&gt;Backpropagation&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#batching&quot;&gt;Batching&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#inference-optimization&quot;&gt;Inference Optimization&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#training-1&quot;&gt;Training&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#evaluation&quot;&gt;Evaluation&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#architecture-improvements&quot;&gt;Architecture Improvements&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#stopping-generation&quot;&gt;Stopping Generation&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fine-tuning&quot;&gt;Fine-tuning&lt;/a&gt;&lt;ul&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#classification-fine-tuning&quot;&gt;Classification Fine-tuning&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#generative-fine-tuning&quot;&gt;Generative Fine-tuning&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#instruction-fine-tuning&quot;&gt;Instruction Fine-tuning&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#parameter-efficient-fine-tuning&quot;&gt;Parameter Efficient Fine-tuning&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;p&gt;&lt;/p&gt;
&lt;h2 id=&quot;what-is-a-gpt%3F&quot; tabindex=&quot;-1&quot;&gt;What is a GPT?&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;GPT stands for &lt;strong&gt;Generative Pre-trained Transformer&lt;/strong&gt;. It&#39;s a type of neural network architecture based on the &lt;a href=&quot;https://arxiv.org/pdf/1706.03762.pdf&quot;&gt;&lt;strong&gt;Transformer&lt;/strong&gt;&lt;/a&gt;. &lt;a href=&quot;https://jalammar.github.io/how-gpt3-works-visualizations-animations/&quot;&gt;Jay Alammar&#39;s How GPT3 Works&lt;/a&gt; is an excellent introduction to GPTs at a high level, but here&#39;s the tl;dr:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Generative&lt;/strong&gt;: A GPT &lt;em&gt;generates&lt;/em&gt; text.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Pre-trained&lt;/strong&gt;: A GPT is &lt;em&gt;trained&lt;/em&gt; on lots of text from books, the internet, etc ...&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Transformer&lt;/strong&gt;: A GPT is a decoder-only &lt;em&gt;transformer&lt;/em&gt; neural network.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Large Language Models (LLMs) like &lt;a href=&quot;https://en.wikipedia.org/wiki/GPT-3&quot;&gt;OpenAI&#39;s GPT-3&lt;/a&gt; are just GPTs under the hood. What makes them special is they happen to be &lt;strong&gt;1)&lt;/strong&gt; very big (billions of parameters) and &lt;strong&gt;2)&lt;/strong&gt; trained on lots of data (hundreds of gigabytes of text).&lt;/p&gt;
&lt;p&gt;Fundamentally, a GPT &lt;strong&gt;generates text&lt;/strong&gt; given a &lt;strong&gt;prompt&lt;/strong&gt;. Even with this very simple API (input = text, output = text), a well-trained GPT can do some pretty awesome stuff like &lt;a href=&quot;https://machinelearningknowledge.ai/ezoimgfmt/b2611031.smushcdn.com/2611031/wp-content/uploads/2022/12/ChatGPT-Demo-of-Drafting-an-Email.png?lossy=0&amp;amp;strip=1&amp;amp;webp=1&amp;amp;ezimgfmt=ng:webp/ngcb1&quot;&gt;write your emails&lt;/a&gt;, &lt;a href=&quot;https://machinelearningknowledge.ai/ezoimgfmt/b2611031.smushcdn.com/2611031/wp-content/uploads/2022/12/ChatGPT-Example-Book-Summarization.png?lossy=0&amp;amp;strip=1&amp;amp;webp=1&amp;amp;ezimgfmt=ng:webp/ngcb1&quot;&gt;summarize a book&lt;/a&gt;, &lt;a href=&quot;https://khrisdigital.com/wp-content/uploads/2022/12/image-1.png&quot;&gt;give you instagram caption ideas&lt;/a&gt;, &lt;a href=&quot;https://machinelearningknowledge.ai/ezoimgfmt/b2611031.smushcdn.com/2611031/wp-content/uploads/2022/12/ChatGPT-Examples-Explaining-Black-Holes.png?lossy=0&amp;amp;strip=1&amp;amp;webp=1&amp;amp;ezimgfmt=ng:webp/ngcb1&quot;&gt;explain black holes to a 5 year old&lt;/a&gt;, &lt;a href=&quot;https://machinelearningknowledge.ai/ezoimgfmt/b2611031.smushcdn.com/2611031/wp-content/uploads/2022/12/ChatGPT-Demo-of-Writing-SQL-Queries.png?lossy=0&amp;amp;strip=1&amp;amp;webp=1&amp;amp;ezimgfmt=ng:webp/ngcb1&quot;&gt;code in SQL&lt;/a&gt;, and &lt;a href=&quot;https://machinelearningknowledge.ai/ezoimgfmt/b2611031.smushcdn.com/2611031/wp-content/uploads/2022/12/Chat-GPT-Example-Writing-a-Will.png?lossy=0&amp;amp;strip=1&amp;amp;webp=1&amp;amp;ezimgfmt=ng:webp/ngcb1&quot;&gt;even write your will&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;So that&#39;s a high-level overview of GPTs and their capabilities. Let&#39;s dig into some more specifics.&lt;/p&gt;
&lt;h3 id=&quot;input-%2F-output&quot; tabindex=&quot;-1&quot;&gt;Input / Output&lt;/h3&gt;
&lt;p&gt;The function signature for a GPT looks roughly like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def gpt(inputs: list[int]) -&amp;gt; list[list[float]]:
    # inputs has shape [n_seq]
    # output has shape [n_seq, n_vocab]
    output = # beep boop neural network magic
    return output
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;input&quot; tabindex=&quot;-1&quot;&gt;Input&lt;/h4&gt;
&lt;p&gt;The input is some text represented by a &lt;strong&gt;sequence of integers&lt;/strong&gt; that map to &lt;strong&gt;tokens&lt;/strong&gt; in the text:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# integers represent tokens in our text, for example:
# text   = &amp;quot;not all heroes wear capes&amp;quot;:
# tokens = &amp;quot;not&amp;quot;  &amp;quot;all&amp;quot; &amp;quot;heroes&amp;quot; &amp;quot;wear&amp;quot; &amp;quot;capes&amp;quot;
inputs =   [1,     0,    2,      4,     6]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tokens are sub-pieces of the text, which are produced using some kind of &lt;strong&gt;tokenizer&lt;/strong&gt;. We can map tokens to integers using a &lt;strong&gt;vocabulary&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# the index of a token in the vocab represents the integer id for that token
# i.e. the integer id for &amp;quot;heroes&amp;quot; would be 2, since vocab[2] = &amp;quot;heroes&amp;quot;
vocab = [&amp;quot;all&amp;quot;, &amp;quot;not&amp;quot;, &amp;quot;heroes&amp;quot;, &amp;quot;the&amp;quot;, &amp;quot;wear&amp;quot;, &amp;quot;.&amp;quot;, &amp;quot;capes&amp;quot;]

# a pretend tokenizer that tokenizes on whitespace
tokenizer = WhitespaceTokenizer(vocab)

# the encode() method converts a str -&amp;gt; list[int]
ids = tokenizer.encode(&amp;quot;not all heroes wear&amp;quot;) # ids = [1, 0, 2, 4]

# we can see what the actual tokens are via our vocab mapping
tokens = [tokenizer.vocab[i] for i in ids] # tokens = [&amp;quot;not&amp;quot;, &amp;quot;all&amp;quot;, &amp;quot;heroes&amp;quot;, &amp;quot;wear&amp;quot;]

# the decode() method converts back a list[int] -&amp;gt; str
text = tokenizer.decode(ids) # text = &amp;quot;not all heroes wear&amp;quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In short:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;We have a string.&lt;/li&gt;
&lt;li&gt;We use a tokenizer to break it down into smaller pieces called tokens.&lt;/li&gt;
&lt;li&gt;We use a vocabulary to map those tokens to integers.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In practice, we use more advanced methods of tokenization than simply splitting by whitespace, such as &lt;a href=&quot;https://huggingface.co/course/chapter6/5?fw=pt&quot;&gt;Byte-Pair Encoding&lt;/a&gt; or &lt;a href=&quot;https://huggingface.co/course/chapter6/6?fw=pt&quot;&gt;WordPiece&lt;/a&gt;, but the principle is the same:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;There is a &lt;code&gt;vocab&lt;/code&gt; that maps string tokens to integer indices&lt;/li&gt;
&lt;li&gt;There is an &lt;code&gt;encode&lt;/code&gt; method that converts &lt;code&gt;str -&amp;gt; list[int]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;There is a &lt;code&gt;decode&lt;/code&gt; method that converts &lt;code&gt;list[int] -&amp;gt; str&lt;/code&gt;&lt;sup class=&quot;footnote-ref&quot;&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fn1&quot; id=&quot;fnref1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;h4 id=&quot;output&quot; tabindex=&quot;-1&quot;&gt;Output&lt;/h4&gt;
&lt;p&gt;The output is a &lt;strong&gt;2D array&lt;/strong&gt;, where &lt;code&gt;output[i][j]&lt;/code&gt; is the model&#39;s &lt;strong&gt;predicted probability&lt;/strong&gt; that the token at &lt;code&gt;vocab[j]&lt;/code&gt; is the next token &lt;code&gt;inputs[i+1]&lt;/code&gt;. For example:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;vocab = [&amp;quot;all&amp;quot;, &amp;quot;not&amp;quot;, &amp;quot;heroes&amp;quot;, &amp;quot;the&amp;quot;, &amp;quot;wear&amp;quot;, &amp;quot;.&amp;quot;, &amp;quot;capes&amp;quot;]
inputs = [1, 0, 2, 4] # &amp;quot;not&amp;quot; &amp;quot;all&amp;quot; &amp;quot;heroes&amp;quot; &amp;quot;wear&amp;quot;
output = gpt(inputs)
#              [&amp;quot;all&amp;quot;, &amp;quot;not&amp;quot;, &amp;quot;heroes&amp;quot;, &amp;quot;the&amp;quot;, &amp;quot;wear&amp;quot;, &amp;quot;.&amp;quot;, &amp;quot;capes&amp;quot;]
# output[0] =  [0.75    0.1     0.0       0.15    0.0   0.0    0.0  ]
# given just &amp;quot;not&amp;quot;, the model predicts the word &amp;quot;all&amp;quot; with the highest probability

#              [&amp;quot;all&amp;quot;, &amp;quot;not&amp;quot;, &amp;quot;heroes&amp;quot;, &amp;quot;the&amp;quot;, &amp;quot;wear&amp;quot;, &amp;quot;.&amp;quot;, &amp;quot;capes&amp;quot;]
# output[1] =  [0.0     0.0      0.8     0.1    0.0    0.0   0.1  ]
# given the sequence [&amp;quot;not&amp;quot;, &amp;quot;all&amp;quot;], the model predicts the word &amp;quot;heroes&amp;quot; with the highest probability

#              [&amp;quot;all&amp;quot;, &amp;quot;not&amp;quot;, &amp;quot;heroes&amp;quot;, &amp;quot;the&amp;quot;, &amp;quot;wear&amp;quot;, &amp;quot;.&amp;quot;, &amp;quot;capes&amp;quot;]
# output[-1] = [0.0     0.0     0.0     0.1     0.0    0.05  0.85  ]
# given the whole sequence [&amp;quot;not&amp;quot;, &amp;quot;all&amp;quot;, &amp;quot;heroes&amp;quot;, &amp;quot;wear&amp;quot;], the model predicts the word &amp;quot;capes&amp;quot; with the highest probability
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To get a &lt;strong&gt;next token prediction&lt;/strong&gt; for the whole sequence, we simply take the token with the highest probability in &lt;code&gt;output[-1]&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;vocab = [&amp;quot;all&amp;quot;, &amp;quot;not&amp;quot;, &amp;quot;heroes&amp;quot;, &amp;quot;the&amp;quot;, &amp;quot;wear&amp;quot;, &amp;quot;.&amp;quot;, &amp;quot;capes&amp;quot;]
inputs = [1, 0, 2, 4] # &amp;quot;not&amp;quot; &amp;quot;all&amp;quot; &amp;quot;heroes&amp;quot; &amp;quot;wear&amp;quot;
output = gpt(inputs)
next_token_id = np.argmax(output[-1]) # next_token_id = 6
next_token = vocab[next_token_id] # next_token = &amp;quot;capes&amp;quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Taking the token with the highest probability as our prediction is known as &lt;a href=&quot;https://docs.cohere.ai/docs/controlling-generation-with-top-k-top-p#1-pick-the-top-token-greedy-decoding&quot;&gt;&lt;strong&gt;greedy decoding&lt;/strong&gt;&lt;/a&gt; or &lt;strong&gt;greedy sampling&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;The task of predicting the next logical word in a sequence is called &lt;strong&gt;language modeling&lt;/strong&gt;. As such, we can call a GPT a &lt;strong&gt;language model&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Generating a single word is cool and all, but what about entire sentences, paragraphs, etc ...?&lt;/p&gt;
&lt;h3 id=&quot;generating-text&quot; tabindex=&quot;-1&quot;&gt;Generating Text&lt;/h3&gt;
&lt;h4 id=&quot;autoregressive&quot; tabindex=&quot;-1&quot;&gt;Autoregressive&lt;/h4&gt;
&lt;p&gt;We can generate full sentences by iteratively getting the next token prediction from our model. At each iteration, we append the predicted token back into the input:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def generate(inputs, n_tokens_to_generate):
    for _ in range(n_tokens_to_generate): # auto-regressive decode loop
        output = gpt(inputs) # model forward pass
        next_id = np.argmax(output[-1]) # greedy sampling
        inputs.append(int(next_id)) # append prediction to input
    return inputs[len(inputs) - n_tokens_to_generate :]  # only return generated ids

input_ids = [1, 0] # &amp;quot;not&amp;quot; &amp;quot;all&amp;quot;
output_ids = generate(input_ids, 3) # output_ids = [2, 4, 6]
output_tokens = [vocab[i] for i in output_ids] # &amp;quot;heroes&amp;quot; &amp;quot;wear&amp;quot; &amp;quot;capes&amp;quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This process of predicting a future value (regression), and adding it back into the input (auto), is why you might see a GPT described as &lt;strong&gt;autoregressive&lt;/strong&gt;.&lt;/p&gt;
&lt;h4 id=&quot;sampling&quot; tabindex=&quot;-1&quot;&gt;Sampling&lt;/h4&gt;
&lt;p&gt;We can introduce some &lt;strong&gt;stochasticity&lt;/strong&gt; (randomness) to our generations by sampling from the probability distribution instead of being greedy:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;inputs = [1, 0, 2, 4] # &amp;quot;not&amp;quot; &amp;quot;all&amp;quot; &amp;quot;heroes&amp;quot; &amp;quot;wear&amp;quot;
output = gpt(inputs)
np.random.choice(np.arange(vocab_size), p=output[-1]) # capes
np.random.choice(np.arange(vocab_size), p=output[-1]) # hats
np.random.choice(np.arange(vocab_size), p=output[-1]) # capes
np.random.choice(np.arange(vocab_size), p=output[-1]) # capes
np.random.choice(np.arange(vocab_size), p=output[-1]) # pants
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This allows us to generate different sentences given the same input. When combined with techniques like &lt;a href=&quot;https://docs.cohere.ai/docs/controlling-generation-with-top-k-top-p#2-pick-from-amongst-the-top-tokens-top-k&quot;&gt;&lt;strong&gt;top-k&lt;/strong&gt;&lt;/a&gt;, &lt;a href=&quot;https://docs.cohere.ai/docs/controlling-generation-with-top-k-top-p#3-pick-from-amongst-the-top-tokens-whose-probabilities-add-up-to-15-top-p&quot;&gt;&lt;strong&gt;top-p&lt;/strong&gt;&lt;/a&gt;, and &lt;a href=&quot;https://docs.cohere.ai/docs/temperature&quot;&gt;&lt;strong&gt;temperature&lt;/strong&gt;&lt;/a&gt;, which modify the distribution prior to sampling, the quality of our outputs is greatly increased.  These techniques also introduce some hyperparameters that we can play around with to get different generation behaviors (for example, increasing temperature makes our model take more risks and thus be more &amp;quot;creative&amp;quot;).&lt;/p&gt;
&lt;h3 id=&quot;training&quot; tabindex=&quot;-1&quot;&gt;Training&lt;/h3&gt;
&lt;p&gt;We train a GPT like any other neural network, using &lt;a href=&quot;https://arxiv.org/pdf/1609.04747.pdf&quot;&gt;&lt;strong&gt;gradient descent&lt;/strong&gt;&lt;/a&gt; with respect to some &lt;strong&gt;loss function&lt;/strong&gt;. In the case of a GPT, we take the &lt;strong&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=ErfnhcEV1O8&quot;&gt;cross entropy loss&lt;/a&gt; over the language modeling task&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def lm_loss(inputs: list[int], params) -&amp;gt; float:
    # the labels y are just the input shifted 1 to the left
    #
    # inputs = [not,     all,   heros,   wear,   capes]
    #      x = [not,     all,   heroes,  wear]
    #      y = [all,  heroes,     wear,  capes]
    #
    # of course, we don&#39;t have a label for inputs[-1], so we exclude it from x
    #
    # as such, for N inputs, we have N - 1 langauge modeling example pairs
    x, y = inputs[:-1], inputs[1:] # both have shape [num_tokens_in_seq - 1]

    # forward pass
    # all the predicted next token probability distributions at each position
    output = gpt(x, params) # has shape [num_tokens_in_seq - 1, num_tokens_in_vocab]

    # cross entropy loss
    # we take the average over all N-1 examples
    loss = np.mean(-np.log(output[np.arange(len(output)), y]))

    return loss

def train(texts: list[list[str]], params) -&amp;gt; float:
    for text in texts:
        inputs = tokenizer.encode(text)
        loss = lm_loss(inputs, params)
        gradients = compute_gradients_via_backpropagation(loss, params)
        params = gradient_descent_update_step(gradients, params)
    return params
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is a heavily simplified training setup, but it illustrates the point. Notice the addition of &lt;code&gt;params&lt;/code&gt; to our &lt;code&gt;gpt&lt;/code&gt; function signature (we left this out in the previous sections for simplicity). During each iteration of the training loop:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;We compute the language modeling loss for the given input text example&lt;/li&gt;
&lt;li&gt;The loss determines our gradients, which we compute via backpropagation&lt;/li&gt;
&lt;li&gt;We use the gradients to update our model parameters such that the loss is minimized (gradient descent)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Notice, we don&#39;t use explicitly labelled data. Instead, we are able to produce the input/label pairs from just the raw text itself. This is referred to as &lt;strong&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Self-supervised_learning&quot;&gt;self-supervised learning&lt;/a&gt;&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Self-supervision enables us to massively scale training data. Just get our hands on as much raw text as possible and throw it at the model. For example, GPT-3 was trained on &lt;strong&gt;300 billion tokens&lt;/strong&gt; of text from the internet and books:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://miro.medium.com/max/1400/1*Sc3Gi73hepgrOLnx8bXFBA.png&quot; alt=&quot;&quot; /&gt;&lt;figcaption&gt;Table 2.2 from GPT-3 paper&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Of course, you need a sufficiently large model to be able to learn from all this data, which is why GPT-3 has &lt;strong&gt;175 billion parameters&lt;/strong&gt; and probably cost between &lt;a href=&quot;https://twitter.com/eturner303/status/1266264358771757057&quot;&gt;$1m-10m in compute cost to train&lt;/a&gt;.&lt;sup class=&quot;footnote-ref&quot;&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fn2&quot; id=&quot;fnref2&quot;&gt;[2]&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;This self-supervised training step is called &lt;strong&gt;pre-training&lt;/strong&gt;, since we can reuse the &amp;quot;pre-trained&amp;quot; models weights to further train the model on downstream tasks, such as classifying if a tweet is toxic or not. Pre-trained models are also sometimes called &lt;strong&gt;foundation models&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Training the model on downstream tasks is called &lt;strong&gt;fine-tuning&lt;/strong&gt;, since the model weights have already been pre-trained to understand language, it&#39;s just being fine-tuned to the specific task at hand.&lt;/p&gt;
&lt;p&gt;The &amp;quot;pre-training on a general task + fine-tuning on a specific task&amp;quot; strategy is called &lt;a href=&quot;https://en.wikipedia.org/wiki/Transfer_learning&quot;&gt;transfer learning&lt;/a&gt;.&lt;/p&gt;
&lt;h3 id=&quot;prompting&quot; tabindex=&quot;-1&quot;&gt;Prompting&lt;/h3&gt;
&lt;p&gt;In principle, the original &lt;a href=&quot;https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/language-unsupervised/language_understanding_paper.pdf&quot;&gt;GPT&lt;/a&gt; paper was only about the benefits of pre-training a transformer model for transfer learning. The paper showed that pre-training a 117M GPT achieved state-of-the-art performance on various &lt;strong&gt;NLP&lt;/strong&gt; (natural language processing) tasks when fine-tuned on labelled datasets.&lt;/p&gt;
&lt;p&gt;It wasn&#39;t until the &lt;a href=&quot;https://d4mucfpksywv.cloudfront.net/better-language-models/language_models_are_unsupervised_multitask_learners.pdf&quot;&gt;GPT-2&lt;/a&gt; and  &lt;a href=&quot;https://arxiv.org/abs/2005.14165&quot;&gt;GPT-3&lt;/a&gt; papers that we realized a GPT model pre-trained on enough data with enough parameters was capable of performing any arbitrary task &lt;strong&gt;by itself&lt;/strong&gt;, no fine-tuning needed. Just prompt the model, perform autoregressive language modeling, and voila, the model magically gives us an appropriate response. This is referred to as &lt;strong&gt;in-context learning&lt;/strong&gt;, because the model is using just the context of the prompt to perform the task. In-context learning can be zero shot, one shot, or few shot:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://i.imgur.com/VKZXC0K.png&quot; alt=&quot;&quot; /&gt;&lt;figcaption&gt;Figure 2.1 from the GPT-3 Paper&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Generating text given a prompt is also sometimes referred to as &lt;strong&gt;conditional generation&lt;/strong&gt;, since our model is generating some output &lt;em&gt;conditioned&lt;/em&gt; on some input.&lt;/p&gt;
&lt;p&gt;GPTs are not limited to NLP tasks. You can condition the model on anything you want. For example, you can turn a GPT into a &lt;strong&gt;chatbot&lt;/strong&gt; (i.e. &lt;a href=&quot;https://openai.com/blog/chatgpt/&quot;&gt;ChatGPT&lt;/a&gt;) by conditioning it on the conversation history. You can also further condition the chatbot to behave a certain way by prepending the prompt with some kind of description (i.e. &amp;quot;You are a chatbot. Be polite, speak in full sentences, don&#39;t say harmful things, etc ...&amp;quot;). Conditioning the model like this can even give your &lt;a href=&quot;https://imgur.com/a/AbDFcgk&quot;&gt;chatbot a persona&lt;/a&gt;. This is often referred to as a &lt;strong&gt;system prompt&lt;/strong&gt;. However, this is not robust, you can still &lt;a href=&quot;https://twitter.com/zswitten/status/1598380220943593472&quot;&gt;&amp;quot;jailbreak&amp;quot; the model and make it misbehave&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;With that out of the way, let&#39;s finally get to the actual implementation.&lt;/p&gt;
&lt;h2 id=&quot;setup&quot; tabindex=&quot;-1&quot;&gt;Setup&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;Clone the repository for this tutorial:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;git clone https://github.com/jaymody/picoGPT
cd picoGPT
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then let&#39;s install our dependencies:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;pip install -r requirements.txt
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note: This code was tested with &lt;code&gt;Python 3.9.10&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;A quick breakdown of each of the files:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;encoder.py&lt;/code&gt;&lt;/strong&gt; contains the code for OpenAI&#39;s BPE Tokenizer, taken straight from their &lt;a href=&quot;https://github.com/openai/gpt-2/blob/master/src/encoder.py&quot;&gt;gpt-2 repo&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;utils.py&lt;/code&gt;&lt;/strong&gt; contains the code to download and load the GPT-2 model weights, tokenizer, and hyperparameters.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;gpt2.py&lt;/code&gt;&lt;/strong&gt; contains the actual GPT model and generation code, which we can run as a python script.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;gpt2_pico.py&lt;/code&gt;&lt;/strong&gt; is the same as &lt;code&gt;gpt2.py&lt;/code&gt;, but in even fewer lines of code. Why? Because why not.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;We&#39;ll be reimplementing &lt;code&gt;gpt2.py&lt;/code&gt; from scratch, so let&#39;s delete it and recreate it as an empty file:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;rm gpt2.py
touch gpt2.py
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As a starting point, paste the following code into &lt;code&gt;gpt2.py&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import numpy as np


def gpt2(inputs, wte, wpe, blocks, ln_f, n_head):
    pass # TODO: implement this


def generate(inputs, params, n_head, n_tokens_to_generate):
    from tqdm import tqdm

    for _ in tqdm(range(n_tokens_to_generate), &amp;quot;generating&amp;quot;):  # auto-regressive decode loop
        logits = gpt2(inputs, **params, n_head=n_head)  # model forward pass
        next_id = np.argmax(logits[-1])  # greedy sampling
        inputs.append(int(next_id))  # append prediction to input

    return inputs[len(inputs) - n_tokens_to_generate :]  # only return generated ids


def main(prompt: str, n_tokens_to_generate: int = 40, model_size: str = &amp;quot;124M&amp;quot;, models_dir: str = &amp;quot;models&amp;quot;):
    from utils import load_encoder_hparams_and_params

    # load encoder, hparams, and params from the released open-ai gpt-2 files
    encoder, hparams, params = load_encoder_hparams_and_params(model_size, models_dir)

    # encode the input string using the BPE tokenizer
    input_ids = encoder.encode(prompt)

    # make sure we are not surpassing the max sequence length of our model
    assert len(input_ids) + n_tokens_to_generate &amp;lt; hparams[&amp;quot;n_ctx&amp;quot;]

    # generate output ids
    output_ids = generate(input_ids, params, hparams[&amp;quot;n_head&amp;quot;], n_tokens_to_generate)

    # decode the ids back into a string
    output_text = encoder.decode(output_ids)

    return output_text


if __name__ == &amp;quot;__main__&amp;quot;:
    import fire

    fire.Fire(main)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Breaking down each of the 4 sections:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;The &lt;code&gt;gpt2&lt;/code&gt; function is the actual GPT code we&#39;ll be implementing. You&#39;ll notice that the function signature includes some extra stuff in addition to &lt;code&gt;inputs&lt;/code&gt;:
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;wte&lt;/code&gt;, &lt;code&gt;wpe&lt;/code&gt;, &lt;code&gt;blocks&lt;/code&gt;, and &lt;code&gt;ln_f&lt;/code&gt; are the parameters of our model.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;n_head&lt;/code&gt; is a hyperparameter that is needed during the forward pass.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;generate&lt;/code&gt; function is the autoregressive decoding algorithm we saw earlier. We use greedy sampling for simplicity. &lt;a href=&quot;https://www.google.com/search?q=tqdm&quot;&gt;&lt;code&gt;tqdm&lt;/code&gt;&lt;/a&gt; is a progress bar to help us visualize the decoding process as it generates tokens one at a time.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;main&lt;/code&gt; function handles:
&lt;ol&gt;
&lt;li&gt;Loading the tokenizer (&lt;code&gt;encoder&lt;/code&gt;), model weights (&lt;code&gt;params&lt;/code&gt;), and hyperparameters (&lt;code&gt;hparams&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;Encoding the input prompt into token IDs using the tokenizer&lt;/li&gt;
&lt;li&gt;Calling the generate function&lt;/li&gt;
&lt;li&gt;Decoding the output IDs into a string&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/google/python-fire&quot;&gt;&lt;code&gt;fire.Fire(main)&lt;/code&gt;&lt;/a&gt; just turns our file into a CLI application, so we can eventually run our code with: &lt;code&gt;python gpt2.py &amp;quot;some prompt here&amp;quot;&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Let&#39;s take a closer look at &lt;code&gt;encoder&lt;/code&gt;, &lt;code&gt;hparams&lt;/code&gt;, and &lt;code&gt;params&lt;/code&gt;, in a notebook, or an interactive python session, run:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from utils import load_encoder_hparams_and_params
encoder, hparams, params = load_encoder_hparams_and_params(&amp;quot;124M&amp;quot;, &amp;quot;models&amp;quot;)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This will &lt;a href=&quot;https://github.com/jaymody/picoGPT/blob/a750c145ba4d09d5764806a6c78c71ffaff88e64/utils.py#L13-L40&quot;&gt;download the necessary model and tokenizer files&lt;/a&gt; to &lt;code&gt;models/124M&lt;/code&gt; and &lt;a href=&quot;https://github.com/jaymody/picoGPT/blob/a750c145ba4d09d5764806a6c78c71ffaff88e64/utils.py#L68-L82&quot;&gt;load &lt;code&gt;encoder&lt;/code&gt;, &lt;code&gt;hparams&lt;/code&gt;, and &lt;code&gt;params&lt;/code&gt;&lt;/a&gt; into our code.&lt;/p&gt;
&lt;h3 id=&quot;encoder&quot; tabindex=&quot;-1&quot;&gt;Encoder&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;encoder&lt;/code&gt; is the BPE tokenizer used by GPT-2:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; ids = encoder.encode(&amp;quot;Not all heroes wear capes.&amp;quot;)
&amp;gt;&amp;gt;&amp;gt; ids
[3673, 477, 10281, 5806, 1451, 274, 13]

&amp;gt;&amp;gt;&amp;gt; encoder.decode(ids)
&amp;quot;Not all heroes wear capes.&amp;quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Using the vocabulary of the tokenizer (stored in &lt;code&gt;encoder.decoder&lt;/code&gt;), we can take a peek at what the actual tokens look like:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; [encoder.decoder[i] for i in ids]
[&#39;Not&#39;, &#39;Ġall&#39;, &#39;Ġheroes&#39;, &#39;Ġwear&#39;, &#39;Ġcap&#39;, &#39;es&#39;, &#39;.&#39;]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice, sometimes our tokens are words (e.g. &lt;code&gt;Not&lt;/code&gt;), sometimes they are words but with a space in front of them (e.g. &lt;code&gt;Ġall&lt;/code&gt;, the &lt;a href=&quot;https://github.com/karpathy/minGPT/blob/37baab71b9abea1b76ab957409a1cc2fbfba8a26/mingpt/bpe.py#L22-L33&quot;&gt;&lt;code&gt;Ġ&lt;/code&gt; represents a space&lt;/a&gt;), sometimes there are part of a word (e.g. capes is split into &lt;code&gt;Ġcap&lt;/code&gt; and &lt;code&gt;es&lt;/code&gt;), and sometimes they are punctuation (e.g. &lt;code&gt;.&lt;/code&gt;).&lt;/p&gt;
&lt;p&gt;One nice thing about BPE is that it can encode any arbitrary string. If it encounters something that is not present in the vocabulary, it just breaks it down into substrings it does understand:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; [encoder.decoder[i] for i in encoder.encode(&amp;quot;zjqfl&amp;quot;)]
[&#39;z&#39;, &#39;j&#39;, &#39;q&#39;, &#39;fl&#39;]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We can also check the size of the vocabulary:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; len(encoder.decoder)
50257
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The vocabulary, as well as the byte-pair merges which determines how strings are broken down, is obtained by &lt;em&gt;training&lt;/em&gt; the tokenizer. When we load the tokenizer, we&#39;re loading the already trained vocab and byte-pair merges from some files, which were downloaded alongside the model files when we ran &lt;code&gt;load_encoder_hparams_and_params&lt;/code&gt;. See &lt;code&gt;models/124M/encoder.json&lt;/code&gt; (the vocabulary) and &lt;code&gt;models/124M/vocab.bpe&lt;/code&gt; (byte-pair merges).&lt;/p&gt;
&lt;h3 id=&quot;hyperparameters&quot; tabindex=&quot;-1&quot;&gt;Hyperparameters&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;hparams&lt;/code&gt; is a dictionary that contains the hyper-parameters of our model:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; hparams
{
  &amp;quot;n_vocab&amp;quot;: 50257, # number of tokens in our vocabulary
  &amp;quot;n_ctx&amp;quot;: 1024, # maximum possible sequence length of the input
  &amp;quot;n_embd&amp;quot;: 768, # embedding dimension (determines the &amp;quot;width&amp;quot; of the network)
  &amp;quot;n_head&amp;quot;: 12, # number of attention heads (n_embd must be divisible by n_head)
  &amp;quot;n_layer&amp;quot;: 12 # number of layers (determines the &amp;quot;depth&amp;quot; of the network)
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We&#39;ll use these symbols in our code&#39;s comments to show the underlying shape of things. We&#39;ll also use  &lt;code&gt;n_seq&lt;/code&gt; to denote the length of our input sequence (i.e. &lt;code&gt;n_seq = len(inputs)&lt;/code&gt;).&lt;/p&gt;
&lt;h3 id=&quot;parameters&quot; tabindex=&quot;-1&quot;&gt;Parameters&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;params&lt;/code&gt; is a nested json dictionary that hold the trained weights of our model. The leaf nodes of the json are NumPy arrays. If we print &lt;code&gt;params&lt;/code&gt;, replacing the arrays with their shapes, we get:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; import numpy as np
&amp;gt;&amp;gt;&amp;gt; def shape_tree(d):
&amp;gt;&amp;gt;&amp;gt;     if isinstance(d, np.ndarray):
&amp;gt;&amp;gt;&amp;gt;         return list(d.shape)
&amp;gt;&amp;gt;&amp;gt;     elif isinstance(d, list):
&amp;gt;&amp;gt;&amp;gt;         return [shape_tree(v) for v in d]
&amp;gt;&amp;gt;&amp;gt;     elif isinstance(d, dict):
&amp;gt;&amp;gt;&amp;gt;         return {k: shape_tree(v) for k, v in d.items()}
&amp;gt;&amp;gt;&amp;gt;     else:
&amp;gt;&amp;gt;&amp;gt;         ValueError(&amp;quot;uh oh&amp;quot;)
&amp;gt;&amp;gt;&amp;gt;
&amp;gt;&amp;gt;&amp;gt; print(shape_tree(params))
{
    &amp;quot;wpe&amp;quot;: [1024, 768],
    &amp;quot;wte&amp;quot;: [50257, 768],
    &amp;quot;ln_f&amp;quot;: {&amp;quot;b&amp;quot;: [768], &amp;quot;g&amp;quot;: [768]},
    &amp;quot;blocks&amp;quot;: [
        {
            &amp;quot;attn&amp;quot;: {
                &amp;quot;c_attn&amp;quot;: {&amp;quot;b&amp;quot;: [2304], &amp;quot;w&amp;quot;: [768, 2304]},
                &amp;quot;c_proj&amp;quot;: {&amp;quot;b&amp;quot;: [768], &amp;quot;w&amp;quot;: [768, 768]},
            },
            &amp;quot;ln_1&amp;quot;: {&amp;quot;b&amp;quot;: [768], &amp;quot;g&amp;quot;: [768]},
            &amp;quot;ln_2&amp;quot;: {&amp;quot;b&amp;quot;: [768], &amp;quot;g&amp;quot;: [768]},
            &amp;quot;mlp&amp;quot;: {
                &amp;quot;c_fc&amp;quot;: {&amp;quot;b&amp;quot;: [3072], &amp;quot;w&amp;quot;: [768, 3072]},
                &amp;quot;c_proj&amp;quot;: {&amp;quot;b&amp;quot;: [768], &amp;quot;w&amp;quot;: [3072, 768]},
            },
        },
        ... # repeat for n_layers
    ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;These are loaded from the original OpenAI tensorflow checkpoint:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; import tensorflow as tf
&amp;gt;&amp;gt;&amp;gt; tf_ckpt_path = tf.train.latest_checkpoint(&amp;quot;models/124M&amp;quot;)
&amp;gt;&amp;gt;&amp;gt; for name, _ in tf.train.list_variables(tf_ckpt_path):
&amp;gt;&amp;gt;&amp;gt;     arr = tf.train.load_variable(tf_ckpt_path, name).squeeze()
&amp;gt;&amp;gt;&amp;gt;     print(f&amp;quot;{name}: {arr.shape}&amp;quot;)
model/h0/attn/c_attn/b: (2304,)
model/h0/attn/c_attn/w: (768, 2304)
model/h0/attn/c_proj/b: (768,)
model/h0/attn/c_proj/w: (768, 768)
model/h0/ln_1/b: (768,)
model/h0/ln_1/g: (768,)
model/h0/ln_2/b: (768,)
model/h0/ln_2/g: (768,)
model/h0/mlp/c_fc/b: (3072,)
model/h0/mlp/c_fc/w: (768, 3072)
model/h0/mlp/c_proj/b: (768,)
model/h0/mlp/c_proj/w: (3072, 768)
model/h1/attn/c_attn/b: (2304,)
model/h1/attn/c_attn/w: (768, 2304)
...
model/h9/mlp/c_proj/b: (768,)
model/h9/mlp/c_proj/w: (3072, 768)
model/ln_f/b: (768,)
model/ln_f/g: (768,)
model/wpe: (1024, 768)
model/wte: (50257, 768)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The &lt;a href=&quot;https://github.com/jaymody/picoGPT/blob/29e78cc52b58ed2c1c483ffea2eb46ff6bdec785/utils.py#L43-L65&quot;&gt;following code&lt;/a&gt; converts the above tensorflow variables into our &lt;code&gt;params&lt;/code&gt; dictionary.&lt;/p&gt;
&lt;p&gt;For reference, here&#39;s the shapes of &lt;code&gt;params&lt;/code&gt; but with the numbers replaced by the &lt;code&gt;hparams&lt;/code&gt; they represent:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;{
    &amp;quot;wpe&amp;quot;: [n_ctx, n_embd],
    &amp;quot;wte&amp;quot;: [n_vocab, n_embd],
    &amp;quot;ln_f&amp;quot;: {&amp;quot;b&amp;quot;: [n_embd], &amp;quot;g&amp;quot;: [n_embd]},
    &amp;quot;blocks&amp;quot;: [
        {
            &amp;quot;attn&amp;quot;: {
                &amp;quot;c_attn&amp;quot;: {&amp;quot;b&amp;quot;: [3*n_embd], &amp;quot;w&amp;quot;: [n_embd, 3*n_embd]},
                &amp;quot;c_proj&amp;quot;: {&amp;quot;b&amp;quot;: [n_embd], &amp;quot;w&amp;quot;: [n_embd, n_embd]},
            },
            &amp;quot;ln_1&amp;quot;: {&amp;quot;b&amp;quot;: [n_embd], &amp;quot;g&amp;quot;: [n_embd]},
            &amp;quot;ln_2&amp;quot;: {&amp;quot;b&amp;quot;: [n_embd], &amp;quot;g&amp;quot;: [n_embd]},
            &amp;quot;mlp&amp;quot;: {
                &amp;quot;c_fc&amp;quot;: {&amp;quot;b&amp;quot;: [4*n_embd], &amp;quot;w&amp;quot;: [n_embd, 4*n_embd]},
                &amp;quot;c_proj&amp;quot;: {&amp;quot;b&amp;quot;: [n_embd], &amp;quot;w&amp;quot;: [4*n_embd, n_embd]},
            },
        },
        ... # repeat for n_layers
    ]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You&#39;ll probably want to come back to reference this dictionary to check the shape of the weights as we implement our GPT. We&#39;ll match the variable names in our code with the keys of this dictionary for consistency.&lt;/p&gt;
&lt;h2 id=&quot;basic-layers&quot; tabindex=&quot;-1&quot;&gt;Basic Layers&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;Last thing before we get into the actual GPT architecture itself, let&#39;s implement some of the more basic neural network layers that are non-specific to GPTs.&lt;/p&gt;
&lt;h3 id=&quot;gelu&quot; tabindex=&quot;-1&quot;&gt;GELU&lt;/h3&gt;
&lt;p&gt;The non-linearity (&lt;strong&gt;activation function&lt;/strong&gt;) of choice for GPT-2 is &lt;a href=&quot;https://arxiv.org/pdf/1606.08415.pdf&quot;&gt;GELU (Gaussian Error Linear Units)&lt;/a&gt;, an alternative for ReLU:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://miro.medium.com/max/491/1*kwHcbpKUNLda8tvCiwudqQ.png&quot; alt=&quot;&quot; /&gt;&lt;figcaption&gt;Figure 1 from the GELU paper&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;It is approximated by the following function:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def gelu(x):
    return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x**3)))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Like ReLU, GELU operates element-wise on the input:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; gelu(np.array([[1, 2], [-2, 0.5]]))
array([[ 0.84119,  1.9546 ],
       [-0.0454 ,  0.34571]])
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;softmax&quot; tabindex=&quot;-1&quot;&gt;Softmax&lt;/h3&gt;
&lt;p&gt;Good ole &lt;a href=&quot;https://en.wikipedia.org/wiki/Softmax_function&quot;&gt;softmax&lt;/a&gt;:&lt;/p&gt;
&lt;p&gt;&#92;[
&#92;text{softmax}(x)_i = &#92;frac{e^{x_i}}{&#92;sum_j e^{x_j}}
&#92;]&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def softmax(x):
    exp_x = np.exp(x - np.max(x, axis=-1, keepdims=True))
    return exp_x / np.sum(exp_x, axis=-1, keepdims=True)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We use the &lt;a href=&quot;https://jaykmody.com/blog/stable-softmax/&quot;&gt;&lt;code&gt;max(x)&lt;/code&gt; trick for numerical stability&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Softmax is used to a convert set of real numbers (between &#92;(-&#92;infty&#92;) and &#92;(&#92;infty&#92;)) to probabilities (between 0 and 1, with the numbers all summing to 1). We apply &lt;code&gt;softmax&lt;/code&gt; over the last axis of the input.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; x = softmax(np.array([[2, 100], [-5, 0]]))
&amp;gt;&amp;gt;&amp;gt; x
array([[0.00034, 0.99966],
       [0.26894, 0.73106]])
&amp;gt;&amp;gt;&amp;gt; x.sum(axis=-1)
array([1., 1.])
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;layer-normalization&quot; tabindex=&quot;-1&quot;&gt;Layer Normalization&lt;/h3&gt;
&lt;p&gt;&lt;a href=&quot;https://arxiv.org/pdf/1607.06450.pdf&quot;&gt;Layer normalization&lt;/a&gt; standardizes values to have a mean of 0 and a variance of 1:&lt;/p&gt;
&lt;p&gt;&#92;[
&#92;text{LayerNorm}(x) = &#92;gamma &#92;cdot &#92;frac{x - &#92;mu}{&#92;sqrt{&#92;sigma^2}} + &#92;beta
&#92;]where &#92;(&#92;mu&#92;) is the mean of &#92;(x&#92;), &#92;(&#92;sigma^2&#92;) is the variance of &#92;(x&#92;), and &#92;(&#92;gamma&#92;) and &#92;(&#92;beta&#92;) are learnable parameters.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def layer_norm(x, g, b, eps: float = 1e-5):
    mean = np.mean(x, axis=-1, keepdims=True)
    variance = np.var(x, axis=-1, keepdims=True)
    x = (x - mean) / np.sqrt(variance + eps)  # normalize x to have mean=0 and var=1 over last axis
    return g * x + b  # scale and offset with gamma/beta params
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Layer normalization ensures that the inputs for each layer are always within a consistent range, which is supposed to speed up and stabilize the training process. Like &lt;a href=&quot;https://arxiv.org/pdf/1502.03167.pdf&quot;&gt;Batch Normalization&lt;/a&gt;, the normalized output is then scaled and offset with two learnable vectors gamma and beta. The small epsilon term in the denominator is used to avoid a division by zero error.&lt;/p&gt;
&lt;p&gt;Layer norm is used instead of batch norm in the transformer for &lt;a href=&quot;https://stats.stackexchange.com/questions/474440/why-do-transformers-use-layer-norm-instead-of-batch-norm&quot;&gt;various reasons&lt;/a&gt;. The differences between various normalization techniques is outlined &lt;a href=&quot;https://tungmphung.com/deep-learning-normalization-methods/&quot;&gt;in this excellent blog post&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;We apply layer normalization over the last axis of the input.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; x = np.array([[2, 2, 3], [-5, 0, 1]])
&amp;gt;&amp;gt;&amp;gt; x = layer_norm(x, g=np.ones(x.shape[-1]), b=np.zeros(x.shape[-1]))
&amp;gt;&amp;gt;&amp;gt; x
array([[-0.70709, -0.70709,  1.41418],
       [-1.397  ,  0.508  ,  0.889  ]])
&amp;gt;&amp;gt;&amp;gt; x.var(axis=-1)
array([0.99996, 1.     ]) # floating point shenanigans
&amp;gt;&amp;gt;&amp;gt; x.mean(axis=-1)
array([-0., -0.])
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;linear&quot; tabindex=&quot;-1&quot;&gt;Linear&lt;/h3&gt;
&lt;p&gt;Your standard matrix multiplication + bias:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def linear(x, w, b):  # [m, in], [in, out], [out] -&amp;gt; [m, out]
    return x @ w + b
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Linear layers are often referred to as &lt;strong&gt;projections&lt;/strong&gt; (since they are projecting from one vector space to another vector space).&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; x = np.random.normal(size=(64, 784)) # input dim = 784, batch/sequence dim = 64
&amp;gt;&amp;gt;&amp;gt; w = np.random.normal(size=(784, 10)) # output dim = 10
&amp;gt;&amp;gt;&amp;gt; b = np.random.normal(size=(10,))
&amp;gt;&amp;gt;&amp;gt; x.shape # shape before linear projection
(64, 784)
&amp;gt;&amp;gt;&amp;gt; linear(x, w, b).shape # shape after linear projection
(64, 10)
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;gpt-architecture&quot; tabindex=&quot;-1&quot;&gt;GPT Architecture&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;The GPT architecture follows that of the &lt;a href=&quot;https://arxiv.org/pdf/1706.03762.pdf&quot;&gt;transformer&lt;/a&gt;:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://machinelearningmastery.com/wp-content/uploads/2021/08/attention_research_1.png&quot; alt=&quot;&quot; /&gt;&lt;figcaption&gt;Figure 1 from Attention is All You Need&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;But uses only the decoder stack (the right part of the diagram):&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://i.imgur.com/c4Z6PG8.png&quot; alt=&quot;&quot; /&gt;&lt;figcaption&gt;GPT Architecture&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;Note, the middle &amp;quot;cross-attention&amp;quot; layer is also removed since we got rid of the encoder.&lt;/p&gt;
&lt;p&gt;At a high level, the GPT architecture has three sections:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Text + positional &lt;strong&gt;embeddings&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;A transformer &lt;strong&gt;decoder stack&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;projection to vocab&lt;/strong&gt; step&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In code, it looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def gpt2(inputs, wte, wpe, blocks, ln_f, n_head):  # [n_seq] -&amp;gt; [n_seq, n_vocab]
    # token + positional embeddings
    x = wte[inputs] + wpe[range(len(inputs))]  # [n_seq] -&amp;gt; [n_seq, n_embd]

    # forward pass through n_layer transformer blocks
    for block in blocks:
        x = transformer_block(x, **block, n_head=n_head)  # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]

    # projection to vocab
    x = layer_norm(x, **ln_f)  # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]
    return x @ wte.T  # [n_seq, n_embd] -&amp;gt; [n_seq, n_vocab]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Let&#39;s break down each of these three sections into more detail.&lt;/p&gt;
&lt;h3 id=&quot;embeddings&quot; tabindex=&quot;-1&quot;&gt;Embeddings&lt;/h3&gt;
&lt;h4 id=&quot;token-embeddings&quot; tabindex=&quot;-1&quot;&gt;Token Embeddings&lt;/h4&gt;
&lt;p&gt;Token IDs by themselves are not very good representations for a neural network. For one, the relative magnitudes of the token IDs falsely communicate information (for example, if &lt;code&gt;Apple = 5&lt;/code&gt; and &lt;code&gt;Table = 10&lt;/code&gt; in our vocab, then we are implying that &lt;code&gt;2 * Table = Apple&lt;/code&gt;). Secondly, a single number is not a lot of &lt;em&gt;dimensionality&lt;/em&gt; for a neural network to work with.&lt;/p&gt;
&lt;p&gt;To address these limitations, we&#39;ll take advantage of &lt;a href=&quot;https://jaykmody.com/blog/attention-intuition/#word-vectors-and-similarity&quot;&gt;word vectors&lt;/a&gt;, specifically via a learned embedding matrix:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;wte[inputs] # [n_seq] -&amp;gt; [n_seq, n_embd]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Recall,  &lt;code&gt;wte&lt;/code&gt; is a &lt;code&gt;[n_vocab, n_embd]&lt;/code&gt; matrix. It acts as a lookup table, where the &#92;(i&#92;)th row in the matrix corresponds to the learned vector for the &#92;(i&#92;)th token in our vocabulary. &lt;code&gt;wte[inputs]&lt;/code&gt; uses &lt;a href=&quot;https://numpy.org/doc/stable/user/basics.indexing.html#integer-array-indexing&quot;&gt;integer array indexing&lt;/a&gt; to retrieve the vectors corresponding to each token in our input.&lt;/p&gt;
&lt;p&gt;Like any other parameter in our network, &lt;code&gt;wte&lt;/code&gt; is learned. That is, it is randomly initialized at the start of training and then updated via gradient descent.&lt;/p&gt;
&lt;h4 id=&quot;positional-embeddings&quot; tabindex=&quot;-1&quot;&gt;Positional Embeddings&lt;/h4&gt;
&lt;p&gt;One quirk of the transformer architecture is that it doesn&#39;t take into account position. That is, if we randomly shuffled our input and then accordingly unshuffled the output, the output would be the same as if we never shuffled the input in the first place (the ordering of inputs doesn&#39;t have any effect on the output).&lt;/p&gt;
&lt;p&gt;Of course, the ordering of words is a crucial part of language (duh), so we need some way to encode positional information into our inputs. For this, we can just use another learned embedding matrix:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;wpe[range(len(inputs))] # [n_seq] -&amp;gt; [n_seq, n_embd]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Recall, &lt;code&gt;wpe&lt;/code&gt; is a &lt;code&gt;[n_ctx, n_embd]&lt;/code&gt; matrix. The &#92;(i&#92;)th row of the matrix contains a vector that encodes information about the &#92;(i&#92;)th position in the input. Similar to &lt;code&gt;wte&lt;/code&gt;, this matrix is learned during gradient descent.&lt;/p&gt;
&lt;p&gt;Notice, this restricts our model to a maximum sequence length of &lt;code&gt;n_ctx&lt;/code&gt;.&lt;sup class=&quot;footnote-ref&quot;&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fn3&quot; id=&quot;fnref3&quot;&gt;[3]&lt;/a&gt;&lt;/sup&gt; That is, &lt;code&gt;len(inputs) &amp;lt;= n_ctx&lt;/code&gt; must hold.&lt;/p&gt;
&lt;h4 id=&quot;combined&quot; tabindex=&quot;-1&quot;&gt;Combined&lt;/h4&gt;
&lt;p&gt;We can add our token and positional embeddings to get a combined embedding that encodes both token and positional information.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# token + positional embeddings
x = wte[inputs] + wpe[range(len(inputs))]  # [n_seq] -&amp;gt; [n_seq, n_embd]

# x[i] represents the word embedding for the ith word + the positional
# embedding for the ith position
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;decoder-stack&quot; tabindex=&quot;-1&quot;&gt;Decoder Stack&lt;/h3&gt;
&lt;p&gt;This is where all the magic happens and the &amp;quot;deep&amp;quot; in deep learning comes in. We pass our embedding through a stack of &lt;code&gt;n_layer&lt;/code&gt; transformer decoder blocks.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# forward pass through n_layer transformer blocks
for block in blocks:
    x = transformer_block(x, **block, n_head=n_head)  # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Stacking more layers is what allows us to control how &lt;em&gt;deep&lt;/em&gt; our network is. GPT-3 for example, has a &lt;a href=&quot;https://preview.redd.it/n9fgba8b0qr01.png?auto=webp&amp;amp;s=e86d2d3447c777d3222016e81a0adfaec1a95592&quot;&gt;whopping 96 layers&lt;/a&gt;. On the other hand, choosing a larger &lt;code&gt;n_embd&lt;/code&gt; value allows us to control how &lt;em&gt;wide&lt;/em&gt; our network is (for example, GPT-3 uses an embedding size of 12288).&lt;/p&gt;
&lt;h3 id=&quot;projection-to-vocab&quot; tabindex=&quot;-1&quot;&gt;Projection to Vocab&lt;/h3&gt;
&lt;p&gt;In our final step, we project the output of the final transformer block to a probability distribution over our vocab:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# projection to vocab
x = layer_norm(x, **ln_f)  # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]
return x @ wte.T  # [n_seq, n_embd] -&amp;gt; [n_seq, n_vocab]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Couple things to note here:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;We first pass &lt;code&gt;x&lt;/code&gt; through a &lt;strong&gt;final layer normalization&lt;/strong&gt; layer before doing the projection to vocab. This is specific to the GPT-2 architecture (this is not present in the original GPT and Transformer papers).&lt;/li&gt;
&lt;li&gt;We are &lt;strong&gt;reusing the embedding matrix&lt;/strong&gt; &lt;code&gt;wte&lt;/code&gt; for the projection. Other GPT implementations may choose to use a separate learned weight matrix for the projection, however sharing the embedding matrix has a couple of advantages:
&lt;ul&gt;
&lt;li&gt;You save some parameters (although at GPT-3 scale, this is negligible).&lt;/li&gt;
&lt;li&gt;Since the matrix is both responsible for mapping both &lt;em&gt;to&lt;/em&gt; words and &lt;em&gt;from&lt;/em&gt; words, in theory, it &lt;em&gt;may&lt;/em&gt; learn a richer representation compared to having two separate matrixes.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;We &lt;strong&gt;don&#39;t apply &lt;code&gt;softmax&lt;/code&gt;&lt;/strong&gt; at the end, so our outputs will be &lt;a href=&quot;https://developers.google.com/machine-learning/glossary/#logits&quot;&gt;logits&lt;/a&gt; instead of probabilities between 0 and 1. This is done for several reasons:
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;softmax&lt;/code&gt; is &lt;a href=&quot;https://en.wikipedia.org/wiki/Monotonic_function&quot;&gt;monotonic&lt;/a&gt;, so for greedy sampling &lt;code&gt;np.argmax(logits)&lt;/code&gt; is equivalent to &lt;code&gt;np.argmax(softmax(logits))&lt;/code&gt; making &lt;code&gt;softmax&lt;/code&gt; redundant&lt;/li&gt;
&lt;li&gt;&lt;code&gt;softmax&lt;/code&gt; is irreversible, meaning we can always go from &lt;code&gt;logits&lt;/code&gt; to &lt;code&gt;probabilities&lt;/code&gt; by applying &lt;code&gt;softmax&lt;/code&gt;, but we can&#39;t go back to &lt;code&gt;logits&lt;/code&gt; from &lt;code&gt;probabilities&lt;/code&gt;, so for maximum flexibility, we output the &lt;code&gt;logits&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Numerically stability (for example, to compute cross entropy loss, taking &lt;a href=&quot;https://jaykmody.com/blog/stable-softmax/#cross-entropy-and-log-softmax&quot;&gt;&lt;code&gt;log(softmax(logits))&lt;/code&gt; is numerically unstable compared to &lt;code&gt;log_softmax(logits)&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The projection to vocab step is also sometimes called the &lt;strong&gt;language modeling head&lt;/strong&gt;. What does &amp;quot;head&amp;quot; mean? Once your GPT is pre-trained, you can swap out the language modeling head with some other kind of projection, like a &lt;strong&gt;classification head&lt;/strong&gt; for fine-tuning the model on some classification task. So your model can have multiple heads, kind of like a &lt;a href=&quot;https://en.wikipedia.org/wiki/Lernaean_Hydra&quot;&gt;hydra&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;So that&#39;s the GPT architecture at a high level, let&#39;s actually dig a bit deeper into what the decoder blocks are doing.&lt;/p&gt;
&lt;h3 id=&quot;decoder-block&quot; tabindex=&quot;-1&quot;&gt;Decoder Block&lt;/h3&gt;
&lt;p&gt;The transformer decoder block consists of two sublayers:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Multi-head causal self attention&lt;/li&gt;
&lt;li&gt;Position-wise feed forward neural network&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def transformer_block(x, mlp, attn, ln_1, ln_2, n_head):  # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]
    # multi-head causal self attention
    x = x + mha(layer_norm(x, **ln_1), **attn, n_head=n_head)  # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]

    # position-wise feed forward network
    x = x + ffn(layer_norm(x, **ln_2), **mlp)  # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]

    return x
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each sublayer utilizes layer normalization on their inputs as well as a residual connection (i.e. add the input of the sublayer to the output of the sublayer).&lt;/p&gt;
&lt;p&gt;Some things to note:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Multi-head causal self attention&lt;/strong&gt; is what facilitates the communication between the inputs. Nowhere else in the network does the model allow inputs to &amp;quot;see&amp;quot; each other. The embeddings, position-wise feed forward network, layer norms, and projection to vocab all operate on our inputs position-wise. Modeling relationships between inputs is tasked solely to attention.&lt;/li&gt;
&lt;li&gt;The &lt;strong&gt;Position-wise feed forward neural network&lt;/strong&gt; is just a regular 2 layer fully connected neural network. This just adds a bunch of learnable parameters for our model to work with to facilitate learning.&lt;/li&gt;
&lt;li&gt;In the original transformer paper, layer norm is placed on the output &lt;code&gt;layer_norm(x + sublayer(x))&lt;/code&gt; while we place layer norm on the input &lt;code&gt;x + sublayer(layer_norm(x))&lt;/code&gt; to match GPT-2. This is referred to as &lt;strong&gt;pre-norm&lt;/strong&gt; and has been shown to be &lt;a href=&quot;https://arxiv.org/pdf/2002.04745.pdf&quot;&gt;important in improving the performance of the transformer&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Residual connections&lt;/strong&gt; (popularized by &lt;a href=&quot;https://arxiv.org/pdf/1512.03385.pdf&quot;&gt;ResNet&lt;/a&gt;) serve a couple of different purposes:
&lt;ol&gt;
&lt;li&gt;Makes it easier to optimize neural networks that are deep (i.e. networks that have lots of layers). The idea here is that we are providing &amp;quot;shortcuts&amp;quot; for the gradients to flow back through the network, making it easier to optimize the earlier layers in the network.&lt;/li&gt;
&lt;li&gt;Without residual connections, deeper models see a degradation in performance when adding more layers (possibly because it&#39;s hard for the gradients to flow all the way back through a deep network without losing information). Residual connections seem to give a bit of an accuracy boost for deeper networks.&lt;/li&gt;
&lt;li&gt;Can help with the &lt;a href=&quot;https://programmathically.com/understanding-the-exploding-and-vanishing-gradients-problem/&quot;&gt;vanishing/exploding gradients problem&lt;/a&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Let&#39;s dig a little deeper into the 2 sublayers.&lt;/p&gt;
&lt;h3 id=&quot;position-wise-feed-forward-network&quot; tabindex=&quot;-1&quot;&gt;Position-wise Feed Forward Network&lt;/h3&gt;
&lt;p&gt;This is just a simple multi-layer perceptron with 2 layers:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def ffn(x, c_fc, c_proj):  # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]
    # project up
    a = gelu(linear(x, **c_fc))  # [n_seq, n_embd] -&amp;gt; [n_seq, 4*n_embd]

    # project back down
    x = linear(a, **c_proj)  # [n_seq, 4*n_embd] -&amp;gt; [n_seq, n_embd]

    return x
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Nothing super fancy here, we just project from &lt;code&gt;n_embd&lt;/code&gt; up to a higher dimension &lt;code&gt;4*n_embd&lt;/code&gt; and then back down to &lt;code&gt;n_embd&lt;/code&gt;&lt;sup class=&quot;footnote-ref&quot;&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fn4&quot; id=&quot;fnref4&quot;&gt;[4]&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;
&lt;p&gt;Recall, from our &lt;code&gt;params&lt;/code&gt; dictionary, that our &lt;code&gt;mlp&lt;/code&gt; params look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;quot;mlp&amp;quot;: {
    &amp;quot;c_fc&amp;quot;: {&amp;quot;b&amp;quot;: [4*n_embd], &amp;quot;w&amp;quot;: [n_embd, 4*n_embd]},
    &amp;quot;c_proj&amp;quot;: {&amp;quot;b&amp;quot;: [n_embd], &amp;quot;w&amp;quot;: [4*n_embd, n_embd]},
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;multi-head-causal-self-attention&quot; tabindex=&quot;-1&quot;&gt;Multi-Head Causal Self Attention&lt;/h3&gt;
&lt;p&gt;This layer is probably the most difficult part of the transformer to understand. So let&#39;s work our way up to &amp;quot;Multi-Head Causal Self Attention&amp;quot; by breaking each word down into its own section:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Attention&lt;/li&gt;
&lt;li&gt;Self&lt;/li&gt;
&lt;li&gt;Causal&lt;/li&gt;
&lt;li&gt;Multi-Head&lt;/li&gt;
&lt;/ol&gt;
&lt;h4 id=&quot;attention&quot; tabindex=&quot;-1&quot;&gt;Attention&lt;/h4&gt;
&lt;p&gt;I have another &lt;a href=&quot;https://jaykmody.com/blog/attention-intuition/&quot;&gt;blog post&lt;/a&gt; on this topic, where we derive the scaled dot product equation proposed in the &lt;a href=&quot;https://arxiv.org/pdf/1706.03762.pdf&quot;&gt;original transformer paper&lt;/a&gt; from the ground up:&lt;br /&gt;
&#92;[&#92;text{attention}(Q, K, V) = &#92;text{softmax}(&#92;frac{QK^T}{&#92;sqrt{d_k}})V&#92;]As such, I&#39;m going to skip an explanation for attention in this post. You can also reference &lt;a href=&quot;https://lilianweng.github.io/posts/2018-06-24-attention/&quot;&gt;Lilian Weng&#39;s Attention? Attention!&lt;/a&gt; and &lt;a href=&quot;https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/&quot;&gt;Jay Alammar&#39;s The Illustrated Transformer&lt;/a&gt; which are also great explanations for attention.&lt;/p&gt;
&lt;p&gt;We&#39;ll just adapt our attention implementation from my blog post:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def attention(q, k, v):  # [n_q, d_k], [n_k, d_k], [n_k, d_v] -&amp;gt; [n_q, d_v]
    return softmax(q @ k.T / np.sqrt(q.shape[-1])) @ v
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;self&quot; tabindex=&quot;-1&quot;&gt;Self&lt;/h4&gt;
&lt;p&gt;When &lt;code&gt;q&lt;/code&gt;, &lt;code&gt;k&lt;/code&gt;, and &lt;code&gt;v&lt;/code&gt; all come from the same source, we are performing &lt;a href=&quot;https://lilianweng.github.io/posts/2018-06-24-attention/#self-attention&quot;&gt;self-attention&lt;/a&gt; (i.e. letting our input sequence attend to itself):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def self_attention(x): # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]
    return attention(q=x, k=x, v=x)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For example, if our input is &lt;code&gt;&amp;quot;Jay went to the store, he bought 10 apples.&amp;quot;&lt;/code&gt;, we would be letting the word &amp;quot;he&amp;quot; attend to all the other words, including &amp;quot;Jay&amp;quot;, meaning the model can learn to recognize that &amp;quot;he&amp;quot; is referring to &amp;quot;Jay&amp;quot;.&lt;/p&gt;
&lt;p&gt;We can enhance self attention by introducing projections for &lt;code&gt;q&lt;/code&gt;, &lt;code&gt;k&lt;/code&gt;, &lt;code&gt;v&lt;/code&gt; and the attention output:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def self_attention(x, w_k, w_q, w_v, w_proj): # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]
    # qkv projections
    q = x @ w_q # [n_seq, n_embd] @ [n_embd, n_embd] -&amp;gt; [n_seq, n_embd]
    k = x @ w_k # [n_seq, n_embd] @ [n_embd, n_embd] -&amp;gt; [n_seq, n_embd]
    v = x @ w_v # [n_seq, n_embd] @ [n_embd, n_embd] -&amp;gt; [n_seq, n_embd]

    # perform self attention
    x = attention(q, k, v) # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]

    # out projection
    x = x @ w_proj # [n_seq, n_embd] @ [n_embd, n_embd] -&amp;gt; [n_seq, n_embd]

    return x
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This enables our model to learn a mapping for &lt;code&gt;q&lt;/code&gt;, &lt;code&gt;k&lt;/code&gt;, and &lt;code&gt;v&lt;/code&gt; that best helps attention distinguish relationships between inputs.&lt;/p&gt;
&lt;p&gt;We can reduce the number of matrix multiplication from 4 to just 2 if we combine &lt;code&gt;w_q&lt;/code&gt;, &lt;code&gt;w_k&lt;/code&gt; and &lt;code&gt;w_v&lt;/code&gt; into a single matrix &lt;code&gt;w_fc&lt;/code&gt;, perform the projection, and then split the result:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def self_attention(x, w_fc, w_proj): # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]
    # qkv projections
    x = x @ w_fc # [n_seq, n_embd] @ [n_embd, 3*n_embd] -&amp;gt; [n_seq, 3*n_embd]

    # split into qkv
    q, k, v = np.split(x, 3, axis=-1) # [n_seq, 3*n_embd] -&amp;gt; 3 of [n_seq, n_embd]

    # perform self attention
    x = attention(q, k, v) # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]

    # out projection
    x = x @ w_proj # [n_seq, n_embd] @ [n_embd, n_embd] = [n_seq, n_embd]

    return x
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This is a bit more efficient as modern accelerators (GPUs) can take better advantage of one large matrix multiplication rather than 3 separate small ones happening sequentially.&lt;/p&gt;
&lt;p&gt;Finally, we add bias vectors to match the implementation of GPT-2, use our &lt;code&gt;linear&lt;/code&gt; function, and rename our parameters to match our &lt;code&gt;params&lt;/code&gt; dictionary:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def self_attention(x, c_attn, c_proj): # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]
    # qkv projections
    x = linear(x, **c_attn) # [n_seq, n_embd] -&amp;gt; [n_seq, 3*n_embd]

    # split into qkv
    q, k, v = np.split(x, 3, axis=-1) # [n_seq, 3*n_embd] -&amp;gt; 3 of [n_seq, n_embd]

    # perform self attention
    x = attention(q, k, v) # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]

    # out projection
    x = linear(x, **c_proj) # [n_seq, n_embd] @ [n_embd, n_embd] = [n_seq, n_embd]

    return x
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Recall, from our &lt;code&gt;params&lt;/code&gt; dictionary, our &lt;code&gt;attn&lt;/code&gt; params look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;quot;attn&amp;quot;: {
    &amp;quot;c_attn&amp;quot;: {&amp;quot;b&amp;quot;: [3*n_embd], &amp;quot;w&amp;quot;: [n_embd, 3*n_embd]},
    &amp;quot;c_proj&amp;quot;: {&amp;quot;b&amp;quot;: [n_embd], &amp;quot;w&amp;quot;: [n_embd, n_embd]},
},
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;causal&quot; tabindex=&quot;-1&quot;&gt;Causal&lt;/h4&gt;
&lt;p&gt;There is a bit of an issue with our current self-attention setup, our inputs can see into the future! For example, if our input is &lt;code&gt;[&amp;quot;not&amp;quot;, &amp;quot;all&amp;quot;, &amp;quot;heroes&amp;quot;, &amp;quot;wear&amp;quot;, &amp;quot;capes&amp;quot;]&lt;/code&gt;, during self attention we are allowing &amp;quot;wear&amp;quot; to see &amp;quot;capes&amp;quot;. This means our output probabilities for &amp;quot;wear&amp;quot; will be biased since the model already knows the correct answer is &amp;quot;capes&amp;quot;. This is no good since our model will just learn that the correct answer for input &#92;(i&#92;) can be taken from input &#92;(i+1&#92;).&lt;/p&gt;
&lt;p&gt;To prevent this, we need to somehow modify our attention matrix to &lt;em&gt;hide&lt;/em&gt; or &lt;strong&gt;mask&lt;/strong&gt; our inputs from being able to see into the future. For example, let&#39;s pretend our attention matrix looks like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;       not    all    heroes wear   capes
   not 0.116  0.159  0.055  0.226  0.443
   all 0.180  0.397  0.142  0.106  0.175
heroes 0.156  0.453  0.028  0.129  0.234
  wear 0.499  0.055  0.133  0.017  0.295
 capes 0.089  0.290  0.240  0.228  0.153
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each row corresponds to a query and the columns to a key. In this case, looking at the row for &amp;quot;wear&amp;quot;, you can see that it is attending to &amp;quot;capes&amp;quot; in the last column with a weight of 0.295. To prevent this, we want to set that entry to &lt;code&gt;0.0&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;      not    all    heroes wear   capes
   not 0.116  0.159  0.055  0.226  0.443
   all 0.180  0.397  0.142  0.106  0.175
heroes 0.156  0.453  0.028  0.129  0.234
  wear 0.499  0.055  0.133  0.017  0.
 capes 0.089  0.290  0.240  0.228  0.153
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In general, to prevent all the queries in our input from looking into the future, we set all positions &#92;(i, j&#92;) where &#92;(j &gt; i&#92;)  to &lt;code&gt;0&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;       not    all    heroes wear   capes
   not 0.116  0.     0.     0.     0.
   all 0.180  0.397  0.     0.     0.
heroes 0.156  0.453  0.028  0.     0.
  wear 0.499  0.055  0.133  0.017  0.
 capes 0.089  0.290  0.240  0.228  0.153
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We call this &lt;strong&gt;masking&lt;/strong&gt;. One issue with our above masking approach is our rows no longer sum to 1 (since we are setting them to 0 after the &lt;code&gt;softmax&lt;/code&gt; has been applied). To make sure our rows still sum to 1, we need to modify our attention matrix before the &lt;code&gt;softmax&lt;/code&gt; is applied.&lt;/p&gt;
&lt;p&gt;This can be achieved by setting entries that are to be masked to &#92;(-&#92;infty&#92;) prior to the &lt;code&gt;softmax&lt;/code&gt;&lt;sup class=&quot;footnote-ref&quot;&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fn5&quot; id=&quot;fnref5&quot;&gt;[5]&lt;/a&gt;&lt;/sup&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def attention(q, k, v, mask):  # [n_q, d_k], [n_k, d_k], [n_k, d_v], [n_q, n_k] -&amp;gt; [n_q, d_v]
    return softmax(q @ k.T / np.sqrt(q.shape[-1]) + mask) @ v
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;where &lt;code&gt;mask&lt;/code&gt; is the matrix (for &lt;code&gt;n_seq=5&lt;/code&gt;):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;0 -1e10 -1e10 -1e10 -1e10
0   0   -1e10 -1e10 -1e10
0   0     0   -1e10 -1e10
0   0     0     0   -1e10
0   0     0     0     0
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We use &lt;code&gt;-1e10&lt;/code&gt; instead of &lt;code&gt;-np.inf&lt;/code&gt; as &lt;code&gt;-np.inf&lt;/code&gt; can cause &lt;code&gt;nans&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Adding &lt;code&gt;mask&lt;/code&gt; to our attention matrix instead of just explicitly setting the values to &lt;code&gt;-1e10&lt;/code&gt; works because practically, any number plus &lt;code&gt;-inf&lt;/code&gt; is just &lt;code&gt;-inf&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;We can compute the &lt;code&gt;mask&lt;/code&gt; matrix in NumPy with &lt;code&gt;(1 - np.tri(n_seq)) * -1e10&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Putting it all together, we get:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def attention(q, k, v, mask):  # [n_q, d_k], [n_k, d_k], [n_k, d_v], [n_q, n_k] -&amp;gt; [n_q, d_v]
    return softmax(q @ k.T / np.sqrt(q.shape[-1]) + mask) @ v

def causal_self_attention(x, c_attn, c_proj): # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]
    # qkv projections
    x = linear(x, **c_attn) # [n_seq, n_embd] -&amp;gt; [n_seq, 3*n_embd]

    # split into qkv
    q, k, v = np.split(x, 3, axis=-1) # [n_seq, 3*n_embd] -&amp;gt; 3 of [n_seq, n_embd]

    # causal mask to hide future inputs from being attended to
    causal_mask = (1 - np.tri(x.shape[0], dtype=x.dtype)) * -1e10  # [n_seq, n_seq]

    # perform causal self attention
    x = attention(q, k, v, causal_mask) # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]

    # out projection
    x = linear(x, **c_proj) # [n_seq, n_embd] @ [n_embd, n_embd] = [n_seq, n_embd]

    return x
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;multi-head&quot; tabindex=&quot;-1&quot;&gt;Multi-Head&lt;/h4&gt;
&lt;p&gt;We can further improve our implementation by performing &lt;code&gt;n_head&lt;/code&gt; separate attention computations, splitting our queries, keys, and values into &lt;strong&gt;heads&lt;/strong&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def mha(x, c_attn, c_proj, n_head):  # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]
    # qkv projection
    x = linear(x, **c_attn)  # [n_seq, n_embd] -&amp;gt; [n_seq, 3*n_embd]

    # split into qkv
    qkv = np.split(x, 3, axis=-1)  # [n_seq, 3*n_embd] -&amp;gt; [3, n_seq, n_embd]

    # split into heads
    qkv_heads = list(map(lambda x: np.split(x, n_head, axis=-1), qkv))  # [3, n_seq, n_embd] -&amp;gt; [3, n_head, n_seq, n_embd/n_head]

    # causal mask to hide future inputs from being attended to
    causal_mask = (1 - np.tri(x.shape[0], dtype=x.dtype)) * -1e10  # [n_seq, n_seq]

    # perform attention over each head
    out_heads = [attention(q, k, v, causal_mask) for q, k, v in zip(*qkv_heads)]  # [3, n_head, n_seq, n_embd/n_head] -&amp;gt; [n_head, n_seq, n_embd/n_head]

    # merge heads
    x = np.hstack(out_heads)  # [n_head, n_seq, n_embd/n_head] -&amp;gt; [n_seq, n_embd]

    # out projection
    x = linear(x, **c_proj)  # [n_seq, n_embd] -&amp;gt; [n_seq, n_embd]

    return x
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;There are three steps added here:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Split &lt;code&gt;q, k, v&lt;/code&gt; into &lt;code&gt;n_head&lt;/code&gt; heads:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# split into heads
qkv_heads = list(map(lambda x: np.split(x, n_head, axis=-1), qkv))  # [3, n_seq, n_embd] -&amp;gt; [n_head, 3, n_seq, n_embd/n_head]
&lt;/code&gt;&lt;/pre&gt;
&lt;ol start=&quot;2&quot;&gt;
&lt;li&gt;Compute attention for each head:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# perform attention over each head
out_heads = [attention(q, k, v) for q, k, v in zip(*qkv_heads)]  # [n_head, 3, n_seq, n_embd/n_head] -&amp;gt; [n_head, n_seq, n_embd/n_head]
&lt;/code&gt;&lt;/pre&gt;
&lt;ol start=&quot;3&quot;&gt;
&lt;li&gt;Merge the outputs of each head:&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# merge heads
x = np.hstack(out_heads)  # [n_head, n_seq, n_embd/n_head] -&amp;gt; [n_seq, n_embd]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice, this reduces the dimension from &lt;code&gt;n_embd&lt;/code&gt; to &lt;code&gt;n_embd/n_head&lt;/code&gt; for each attention computation. This is a tradeoff. For reduced dimensionality, our model gets additional &lt;em&gt;subspaces&lt;/em&gt; to work when modeling relationships via attention. For example, maybe one attention head is responsible for connecting pronouns to the person the pronoun is referencing. Maybe another might be responsible for grouping sentences by periods. Another could simply be identifying which words are entities, and which are not. Although, it&#39;s probably just another neural network black box.&lt;/p&gt;
&lt;p&gt;The code we wrote performs the attention computations over each head sequentially in a loop (one at a time), which is not very efficient. In practice, you&#39;d want to do these in parallel. For simplicity, we&#39;ll just leave this sequential.&lt;/p&gt;
&lt;p&gt;With that, we&#39;re finally done our GPT implementation! Now, all that&#39;s left to do is put it all together and run our code.&lt;/p&gt;
&lt;h2 id=&quot;putting-it-all-together&quot; tabindex=&quot;-1&quot;&gt;Putting it All Together&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;Putting everything together, we get &lt;a href=&quot;https://github.com/jaymody/picoGPT/blob/main/gpt2.py&quot;&gt;gpt2.py&lt;/a&gt;, which in its entirety is a mere 120 lines of code (&lt;a href=&quot;https://github.com/jaymody/picoGPT/blob/a750c145ba4d09d5764806a6c78c71ffaff88e64/gpt2_pico.py#L3-L58&quot;&gt;60 lines if you remove comments and whitespace&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;We can test our implementation with:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;python gpt2.py &#92;
    &amp;quot;Alan Turing theorized that computers would one day become&amp;quot; &#92;
    --n_tokens_to_generate 8
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;which gives the output:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;the most powerful machines on the planet.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;It works!!!&lt;/p&gt;
&lt;p&gt;We can test that our implementation gives identical results to &lt;a href=&quot;https://github.com/openai/gpt-2&quot;&gt;OpenAI&#39;s official GPT-2 repo&lt;/a&gt; using the following &lt;a href=&quot;https://gist.github.com/jaymody/9054ca64eeea7fad1b58a185696bb518&quot;&gt;Dockerfile&lt;/a&gt; (Note: this won&#39;t work on M1 Macbooks because of tensorflow shenanigans and also warning, it downloads all 4 GPT-2 model sizes, which is a lot of GBs of stuff to download):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-bash&quot;&gt;docker build -t &amp;quot;openai-gpt-2&amp;quot; &amp;quot;https://gist.githubusercontent.com/jaymody/9054ca64eeea7fad1b58a185696bb518/raw/Dockerfile&amp;quot;
docker run -dt &amp;quot;openai-gpt-2&amp;quot; --name &amp;quot;openai-gpt-2-app&amp;quot;
docker exec -it &amp;quot;openai-gpt-2-app&amp;quot; /bin/bash -c &#39;python3 src/interactive_conditional_samples.py --length 8 --model_type 124M --top_k 1&#39;
# paste &amp;quot;Alan Turing theorized that computers would one day become&amp;quot; when prompted
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;which should give an identical result:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;the most powerful machines on the planet.
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;what-next%3F&quot; tabindex=&quot;-1&quot;&gt;What Next?&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;This implementation is cool and all, but it&#39;s missing a ton of bells and whistles:&lt;/p&gt;
&lt;h3 id=&quot;gpu%2Ftpu-support&quot; tabindex=&quot;-1&quot;&gt;GPU/TPU Support&lt;/h3&gt;
&lt;p&gt;Replace NumPy with &lt;a href=&quot;https://github.com/google/jax&quot;&gt;JAX&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import jax.numpy as np
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That&#39;s it. You can now use the code with GPUs and even &lt;a href=&quot;https://cloud.google.com/tpu/docs/system-architecture-tpu-vm&quot;&gt;TPUs&lt;/a&gt;! Just make sure you &lt;a href=&quot;https://github.com/google/jax#installation&quot;&gt;install JAX correctly&lt;/a&gt;.&lt;/p&gt;
&lt;h3 id=&quot;backpropagation&quot; tabindex=&quot;-1&quot;&gt;Backpropagation&lt;/h3&gt;
&lt;p&gt;Again, if we replace NumPy with &lt;a href=&quot;https://github.com/google/jax&quot;&gt;JAX&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import jax.numpy as np
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then computing the gradients is as easy as:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def lm_loss(params, inputs, n_head) -&amp;gt; float:
    x, y = inputs[:-1], inputs[1:]
    logits = gpt2(x, **params, n_head=n_head)
    loss = np.mean(-log_softmax(logits)[y])
    return loss

grads = jax.grad(lm_loss)(params, inputs, n_head)
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;batching&quot; tabindex=&quot;-1&quot;&gt;Batching&lt;/h3&gt;
&lt;p&gt;Once again, if we replace NumPy with &lt;a href=&quot;https://github.com/google/jax&quot;&gt;JAX&lt;/a&gt;&lt;sup class=&quot;footnote-ref&quot;&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fn6&quot; id=&quot;fnref6&quot;&gt;[6]&lt;/a&gt;&lt;/sup&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import jax.numpy as np
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then, making our &lt;code&gt;gpt2&lt;/code&gt; function batched is as easy as:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;gpt2_batched = jax.vmap(gpt2, in_axes=[0, None, None, None, None, None])
gpt2_batched(batched_inputs) # [batch, seq_len] -&amp;gt; [batch, seq_len, vocab]
&lt;/code&gt;&lt;/pre&gt;
&lt;h3 id=&quot;inference-optimization&quot; tabindex=&quot;-1&quot;&gt;Inference Optimization&lt;/h3&gt;
&lt;p&gt;Our implementation is quite inefficient. The quickest and most impactful optimization you can make (outside of GPU + batching support) would be to implement a &lt;a href=&quot;https://kipp.ly/blog/transformer-inference-arithmetic/#kv-cache&quot;&gt;kv cache&lt;/a&gt;. Also, we implemented our attention head computations sequentially, when we should really be doing it in parallel&lt;sup class=&quot;footnote-ref&quot;&gt;&lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fn7&quot; id=&quot;fnref7&quot;&gt;[7]&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;
&lt;p&gt;There&#39;s many many more inference optimizations. I recommend &lt;a href=&quot;https://lilianweng.github.io/posts/2023-01-10-inference-optimization/&quot;&gt;Lillian Weng&#39;s Large Transformer Model Inference Optimization&lt;/a&gt; and &lt;a href=&quot;https://kipp.ly/blog/transformer-inference-arithmetic/&quot;&gt;Kipply&#39;s Transformer Inference Arithmetic&lt;/a&gt; as a starting point.&lt;/p&gt;
&lt;h3 id=&quot;training-1&quot; tabindex=&quot;-1&quot;&gt;Training&lt;/h3&gt;
&lt;p&gt;Training a GPT is pretty standard for a neural network (gradient descent w.r.t a loss function). Of course, you also need to use the standard bag of tricks when training a GPT  (i.e. use the Adam optimizer, find the optimal learning rate, regularization via dropout and/or weight decay, use a learning rate scheduler, use the correct weight initialization, batching, etc ...).&lt;/p&gt;
&lt;p&gt;The real secret sauce to training a good GPT model is the ability to &lt;strong&gt;scale the data and the model&lt;/strong&gt;, which is where the real challenge is.&lt;/p&gt;
&lt;p&gt;For scaling data, you&#39;ll want a corpus of text that is big, high quality, and diverse.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Big means billions of tokens (terabytes of data). For example, check out &lt;a href=&quot;https://pile.eleuther.ai/&quot;&gt;The Pile&lt;/a&gt;, which is an open source pre-training dataset for large language models.&lt;/li&gt;
&lt;li&gt;High quality means you want to filter out duplicate examples, unformatted text, incoherent text, garbage text, etc ...&lt;/li&gt;
&lt;li&gt;Diverse means varying sequence lengths, about lots of different topics, from different sources, with differing perspectives, etc ... Of course, if there are any biases in the data, it will reflect in the model, so you need to be careful of that as well.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Scaling the model to billions of parameters involves a cr*p ton of engineering (and money lol). Training frameworks can get &lt;a href=&quot;https://github.com/NVIDIA/Megatron-LM&quot;&gt;absurdly long and complex&lt;/a&gt;. A good place to start would be &lt;a href=&quot;https://lilianweng.github.io/posts/2021-09-25-train-large/&quot;&gt;Lillian Weng&#39;s How to Train Really Large Models on Many GPUs&lt;/a&gt;. On the topic there&#39;s also the &lt;a href=&quot;https://arxiv.org/pdf/1909.08053.pdf&quot;&gt;NVIDIA&#39;s Megatron Framework&lt;/a&gt;, &lt;a href=&quot;https://arxiv.org/pdf/2204.06514.pdf&quot;&gt;Cohere&#39;s Training Framework&lt;/a&gt;, &lt;a href=&quot;https://arxiv.org/pdf/2204.02311.pdf&quot;&gt;Google&#39;s PALM&lt;/a&gt;, the open source &lt;a href=&quot;https://github.com/kingoflolz/mesh-transformer-jax&quot;&gt;mesh-transformer-jax&lt;/a&gt; (used to train EleutherAI&#39;s open source models), and &lt;a href=&quot;https://arxiv.org/pdf/2203.15556.pdf&quot;&gt;many&lt;/a&gt; &lt;a href=&quot;https://www.microsoft.com/en-us/research/blog/turing-nlg-a-17-billion-parameter-language-model-by-microsoft/&quot;&gt;many&lt;/a&gt; &lt;a href=&quot;https://arxiv.org/pdf/2005.14165.pdf&quot;&gt;more&lt;/a&gt;.&lt;/p&gt;
&lt;h3 id=&quot;evaluation&quot; tabindex=&quot;-1&quot;&gt;Evaluation&lt;/h3&gt;
&lt;p&gt;Oh boy, how does one even evaluate LLMs? Honestly, it&#39;s really hard problem. &lt;a href=&quot;https://arxiv.org/abs/2211.09110&quot;&gt;HELM&lt;/a&gt; is pretty comprehensive and a good place to start, but you should always be skeptical of &lt;a href=&quot;https://en.wikipedia.org/wiki/Goodhart%27s_law&quot;&gt;benchmarks and evaluation metrics&lt;/a&gt;.&lt;/p&gt;
&lt;h3 id=&quot;architecture-improvements&quot; tabindex=&quot;-1&quot;&gt;Architecture Improvements&lt;/h3&gt;
&lt;p&gt;I recommend taking a look at &lt;a href=&quot;https://github.com/lucidrains/x-transformers&quot;&gt;Phil Wang&#39;s X-Transformer&#39;s&lt;/a&gt;. It has the latest and greatest research on the transformer architecture. &lt;a href=&quot;https://arxiv.org/pdf/2102.11972.pdf&quot;&gt;This paper&lt;/a&gt; is also a pretty good summary (see Table 1). Facebook&#39;s recent &lt;a href=&quot;https://arxiv.org/pdf/2302.13971.pdf&quot;&gt;LLaMA paper&lt;/a&gt; is also probably a good reference for standard architecture improvements (as of February 2023).&lt;/p&gt;
&lt;h3 id=&quot;stopping-generation&quot; tabindex=&quot;-1&quot;&gt;Stopping Generation&lt;/h3&gt;
&lt;p&gt;Our current implementation requires us to specify the exact number of tokens we&#39;d like to generate ahead of time. This is not a very good approach as our generations end up being too long, too short, or cutoff mid-sentence.&lt;/p&gt;
&lt;p&gt;To resolve this, we can introduce a special &lt;strong&gt;end of sentence (EOS) token&lt;/strong&gt;. During pre-training, we append the EOS token to the end of our input (i.e. &lt;code&gt;tokens = [&amp;quot;not&amp;quot;, &amp;quot;all&amp;quot;, &amp;quot;heroes&amp;quot;, &amp;quot;wear&amp;quot;, &amp;quot;capes&amp;quot;, &amp;quot;.&amp;quot;, &amp;quot;&amp;lt;|EOS|&amp;gt;&amp;quot;]&lt;/code&gt;). During generation, we simply stop whenever we encounter the EOS token (or if we hit some maximum sequence length):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def generate(inputs, eos_id, max_seq_len):
	prompt_len = len(inputs)
	while inputs[-1] != eos_id and len(inputs) &amp;lt; max_seq_len:
        output = gpt(inputs)
        next_id = np.argmax(output[-1])
        inputs.append(int(next_id))
    return inputs[prompt_len:]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;GPT-2 was not pre-trained with an EOS token, so we can&#39;t use this approach in our code, but most LLMs nowadays use an EOS token.&lt;/p&gt;
&lt;h3 id=&quot;fine-tuning&quot; tabindex=&quot;-1&quot;&gt;Fine-tuning&lt;/h3&gt;
&lt;p&gt;We briefly touched on fine-tuning in the training section. Recall, fine-tuning is when we re-use the pre-trained weights to train the model on some downstream task. We call this process transfer-learning.&lt;/p&gt;
&lt;p&gt;In theory, we could use zero-shot or few-shot prompting to get the model to complete our task, however, if you have access to a labelled dataset, fine-tuning a GPT is going to yield better results (results that can scale given additional data and higher quality data).&lt;/p&gt;
&lt;p&gt;There are a couple different topics related to fine-tuning, I&#39;ve broken them down below:&lt;/p&gt;
&lt;h4 id=&quot;classification-fine-tuning&quot; tabindex=&quot;-1&quot;&gt;Classification Fine-tuning&lt;/h4&gt;
&lt;p&gt;In classification fine-tuning, we give the model some text and we ask it to predict which class it belongs to. For example, consider the &lt;a href=&quot;https://huggingface.co/datasets/imdb&quot;&gt;IMDB dataset&lt;/a&gt;, which contains movie reviews that rate the movie as either good, or bad:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;--- Example 1 ---
Text: I wouldn&#39;t rent this one even on dollar rental night.
Label: Bad
--- Example 2 ---
Text: I don&#39;t know why I like this movie so well, but I never get tired of watching it.
Label: Good
--- Example 3 ---
...
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To fine-tune our model, we replace the language modeling head with a classification head, which we apply to the last token output:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def gpt2(inputs, wte, wpe, blocks, ln_f, cls_head, n_head):
    x = wte[inputs] + wpe[range(len(inputs))]
    for block in blocks:
        x = transformer_block(x, **block, n_head=n_head)
    x = layer_norm(x, **ln_f)

	# project to n_classes
	# [n_embd] @ [n_embd, n_classes] -&amp;gt; [n_classes]
    return x[-1] @ cls_head
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We only use the last token output &lt;code&gt;x[-1]&lt;/code&gt; because we only need to produce a single probability distribution for the entire input instead of &lt;code&gt;n_seq&lt;/code&gt; distributions as in the case of language modeling. We take the last token in particular (instead of say the first token or a combination of all the tokens) because the last token is the only token that is allowed to attend to the entire sequence and thus has information about the input text as a whole.&lt;/p&gt;
&lt;p&gt;As per usual, we optimize w.r.t. the cross entropy loss:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def singe_example_loss_fn(inputs: list[int], label: int, params) -&amp;gt; float:
    logits = gpt(inputs, **params)
    probs = softmax(logits)
    loss = -np.log(probs[label]) # cross entropy loss
    return loss
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;generative-fine-tuning&quot; tabindex=&quot;-1&quot;&gt;Generative Fine-tuning&lt;/h4&gt;
&lt;p&gt;Some tasks can&#39;t be neatly categorized into classes. For example, consider the task of summarization. We can fine-tune these types of task by simply performing language modeling on the input concatenated with the label. For example, here&#39;s what a single summarization training sample might look like:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;--- Article ---
This is an article I would like to summarize.
--- Summary ---
This is the summary.
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We train the model as we do during pre-training (optimize w.r.t language modeling loss).&lt;/p&gt;
&lt;p&gt;At predict time, we feed the model the everything up to &lt;code&gt;--- Summary ---&lt;/code&gt; and then perform auto-regressive language modeling to generate the summary.&lt;/p&gt;
&lt;p&gt;The choice of the delimiters &lt;code&gt;--- Article ---&lt;/code&gt; and &lt;code&gt;--- Summary ---&lt;/code&gt; are arbitrary. How you choose to format the text is up to you, as long as it is consistent between training and inference.&lt;/p&gt;
&lt;p&gt;Notice, we can also formulate classification tasks as generative tasks (for example with IMDB):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-text&quot;&gt;--- Text ---
I wouldn&#39;t rent this one even on dollar rental night.
--- Label ---
Bad
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;However, this will probably perform worse than doing classification fine-tuning directly (loss includes language modeling on the entire sequence, not just the final prediction, so the loss specific to the prediction will get diluted)&lt;/p&gt;
&lt;h4 id=&quot;instruction-fine-tuning&quot; tabindex=&quot;-1&quot;&gt;Instruction Fine-tuning&lt;/h4&gt;
&lt;p&gt;Most state-of-the-art large language models these days also undergo an additional &lt;strong&gt;instruction fine-tuning&lt;/strong&gt; step after being pre-trained. In this step, the model is fine-tuned (generative) on thousands of instruction prompt + completion pairs that were &lt;strong&gt;human labeled&lt;/strong&gt;. Instruction fine-tuning can also be referred to as &lt;strong&gt;supervised fine-tuning&lt;/strong&gt;, since the data is human labelled (i.e. &lt;strong&gt;supervised&lt;/strong&gt;).&lt;/p&gt;
&lt;p&gt;So what&#39;s the benefit of instruction fine-tuning? While predicting the next word in a wikipedia article makes the model is good at continuing sentences, it doesn&#39;t make it particularly good at following instructions, or having a conversation, or summarizing a document (all the things we would like a GPT to do). Fine-tuning them on human labelled instruction + completion pairs is a way to teach the model how it can be more useful, and make them easier to interact with. This call this &lt;strong&gt;AI alignment&lt;/strong&gt;, as we are aligning the model to do and behave as we want it to. Alignment is an active area of research, and includes more than just following instructions (bias, safety, intent, etc ...).&lt;/p&gt;
&lt;p&gt;What does this instruction data look like exactly? Google&#39;s &lt;a href=&quot;https://arxiv.org/pdf/2109.01652.pdf&quot;&gt;FLAN&lt;/a&gt; models were trained on various academic NLP datasets (which are already human labelled):&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://i.imgur.com/9W2bwJF.png&quot; alt=&quot;&quot; /&gt;&lt;figcaption&gt;Figure 3 from FLAN paper&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;OpenAI&#39;s &lt;a href=&quot;https://arxiv.org/pdf/2203.02155.pdf&quot;&gt;InstructGPT&lt;/a&gt; on the other hand was trained on prompts collected from their own API. They then paid workers to write completions for those prompts. Here&#39;s a breakdown of the data:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://i.imgur.com/FaRRbCa.png&quot; alt=&quot;&quot; /&gt;&lt;figcaption&gt;Table 1 and 2 from InstructGPT paper&lt;/figcaption&gt;&lt;/figure&gt;
&lt;h4 id=&quot;parameter-efficient-fine-tuning&quot; tabindex=&quot;-1&quot;&gt;Parameter Efficient Fine-tuning&lt;/h4&gt;
&lt;p&gt;When we talk about fine-tuning in the above sections, it is assumed that we are updating all of the model parameters. While this yields the best performance, it is costly both in terms of compute (need to back propagate over the entire model) and in terms of storage (for each fine-tuned model, you need to store a completely new copy of the parameters). For instruction fine-tuning, this is fine, we want maximum performance, but if you then wanted to fine-tune 100 different models for various downstream tasks, then you&#39;d have a problem.&lt;/p&gt;
&lt;p&gt;The most simple approach to this problem is to &lt;strong&gt;only update the head&lt;/strong&gt; and &lt;strong&gt;freeze&lt;/strong&gt; (i.e. make untrainable) the rest of the model. This would speed up training and greatly reduce the number of new parameters, however it would not perform nearly as well as a full fine-tune (we are lacking the &lt;em&gt;deep&lt;/em&gt; in deep learning). We could instead &lt;strong&gt;selectively freeze&lt;/strong&gt; specific layers (i.e. freeze all layers except the last 4, or freeze every other layer, or freeze all parameters except multi-head attention parameters), which would help restore some of the depth. This will perform a lot better, but we become a lot less parameter efficient and reduce our training speed ups.&lt;/p&gt;
&lt;p&gt;Instead, we can utilize &lt;strong&gt;parameter-efficient fine-tuning&lt;/strong&gt; (PEFT) methods. PEFT is active area of research, and there are &lt;a href=&quot;https://aclanthology.org/2021.emnlp-main.243.pdf&quot;&gt;lots&lt;/a&gt; &lt;a href=&quot;https://arxiv.org/pdf/2110.07602.pdf&quot;&gt;of&lt;/a&gt; &lt;a href=&quot;https://arxiv.org/pdf/2101.00190.pdf&quot;&gt;different&lt;/a&gt; &lt;a href=&quot;https://arxiv.org/pdf/2103.10385.pdf&quot;&gt;methods&lt;/a&gt; &lt;a href=&quot;https://arxiv.org/pdf/2106.09685.pdf&quot;&gt;to&lt;/a&gt; &lt;a href=&quot;https://arxiv.org/pdf/1902.00751.pdf&quot;&gt;choose&lt;/a&gt; &lt;a href=&quot;https://arxiv.org/abs/2205.05638&quot;&gt;from&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;As an example, take the &lt;a href=&quot;https://arxiv.org/pdf/1902.00751.pdf&quot;&gt;Adapters paper&lt;/a&gt;. In this approach, we add an additional &amp;quot;adapter&amp;quot; layer after the FFN and MHA layers in the transformer block. The adapter layer is just a simple 2 layer fully connected neural network, where the input and output dimensions are &lt;code&gt;n_embd&lt;/code&gt;, and the hidden dimension is smaller than &lt;code&gt;n_embd&lt;/code&gt;:&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://miro.medium.com/max/633/0*Z2FMWTCmdkgevHr-.png&quot; alt=&quot;&quot; /&gt;&lt;figcaption&gt;Figure 2 from the Adapters paper&lt;/figcaption&gt;&lt;/figure&gt;
&lt;p&gt;The size of the hidden dimension is a hyper-parameter that we can set, enabling us to tradeoff parameters for performance. For a BERT model, the paper showed that using this approach can reduce the number of trained parameters to 2% while only sustaining a small hit in performance (&amp;lt;1%) when compared to a full fine-tune.&lt;/p&gt;
&lt;hr class=&quot;footnotes-sep&quot; /&gt;
&lt;section class=&quot;footnotes&quot;&gt;
&lt;ol class=&quot;footnotes-list&quot;&gt;
&lt;li id=&quot;fn1&quot; class=&quot;footnote-item&quot;&gt;&lt;p&gt;For certain applications, the tokenizer doesn&#39;t require a &lt;code&gt;decode&lt;/code&gt; method. For example, if you want to classify if a movie review is saying the movie was good or bad, you only need to be able to &lt;code&gt;encode&lt;/code&gt; the text and do a forward pass of the model, there is no need for &lt;code&gt;decode&lt;/code&gt;. For generating text however, &lt;code&gt;decode&lt;/code&gt; is a requirement. &lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fnref1&quot; class=&quot;footnote-backref&quot;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&quot;fn2&quot; class=&quot;footnote-item&quot;&gt;&lt;p&gt;Although, with the &lt;a href=&quot;https://arxiv.org/pdf/2210.11416.pdf&quot;&gt;InstructGPT&lt;/a&gt; and &lt;a href=&quot;https://arxiv.org/pdf/2203.15556.pdf&quot;&gt;Chinchilla&lt;/a&gt; papers, we&#39;ve realized that we don&#39;t actually need to train models that big. An optimally trained and instruction fine-tuned GPT at 1.3B parameters can outperform GPT-3 at 175B parameters. &lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fnref2&quot; class=&quot;footnote-backref&quot;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&quot;fn3&quot; class=&quot;footnote-item&quot;&gt;&lt;p&gt;The original transformer paper used a &lt;a href=&quot;https://nlp.seas.harvard.edu/2018/04/03/attention.html#positional-encoding&quot;&gt;calculated positional embedding&lt;/a&gt; which they found performed just as well as learned positional embeddings, but has the distinct advantage that you can input any arbitrarily long sequence (you are not restricted by a maximum sequence length). However, in practice, your model is only going to be as the good sequence lengths that it was trained on. You can&#39;t just train a GPT on sequences that are 1024 long and then expect it to perform well at 16k tokens long. Recently however, there has been some success with relative positional embeddings, such as &lt;a href=&quot;https://arxiv.org/pdf/2108.12409.pdf&quot;&gt;Alibi&lt;/a&gt; and &lt;a href=&quot;https://arxiv.org/pdf/2104.09864v4.pdf&quot;&gt;RoPE&lt;/a&gt;. &lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fnref3&quot; class=&quot;footnote-backref&quot;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&quot;fn4&quot; class=&quot;footnote-item&quot;&gt;&lt;p&gt;Different GPT models may choose a different hidden width that is not &lt;code&gt;4*n_embd&lt;/code&gt;, however this is the common practice for GPT models. Also, we give the multi-head attention layer a lot of &lt;em&gt;attention&lt;/em&gt; (pun intended) for driving the success of the transformer, but at the scale of GPT-3, &lt;a href=&quot;https://twitter.com/stephenroller/status/1579993017234382849&quot;&gt;80% of the model parameters are contained in the feed forward layer&lt;/a&gt;. Just something to think about. &lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fnref4&quot; class=&quot;footnote-backref&quot;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&quot;fn5&quot; class=&quot;footnote-item&quot;&gt;&lt;p&gt;If you&#39;re not convinced, stare at the softmax equation and convince yourself this is true (maybe even pull out a pen and paper):&lt;br /&gt;
&#92;[
&#92;text{softmax}(&#92;vec{x})_i=&#92;frac{e^{x_i}}{&#92;sum_je^{x_j}}
&#92;] &lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fnref5&quot; class=&quot;footnote-backref&quot;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&quot;fn6&quot; class=&quot;footnote-item&quot;&gt;&lt;p&gt;I love JAX ❤️. &lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fnref6&quot; class=&quot;footnote-backref&quot;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&quot;fn7&quot; class=&quot;footnote-item&quot;&gt;&lt;p&gt;Using JAX, this is as simple as &lt;code&gt;heads = jax.vmap(attention, in_axes=(0, 0, 0, None))(q, k, v, causal_mask)&lt;/code&gt;. &lt;a href=&quot;https://jaykmody.com/blog/gpt-from-scratch/#fnref7&quot; class=&quot;footnote-backref&quot;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</description>
      <pubDate>Mon, 30 Jan 2023 00:00:00 +0000</pubDate>
      <dc:creator>Jay Mody</dc:creator>
      <guid>https://jaykmody.com/blog/gpt-from-scratch/</guid>
    </item>
    <item>
      <title>Numerically Stable Softmax and Cross Entropy</title>
      <link>https://jaykmody.com/blog/stable-softmax/</link>
      <description>&lt;p&gt;In this post, we&#39;ll take a look at softmax and cross entropy loss, two very common mathematical functions used in deep learning. We&#39;ll see that naive implementations are numerically unstable, and then we&#39;ll derive implementations that are numerically stable.&lt;/p&gt;
&lt;h2 id=&quot;symbols&quot; tabindex=&quot;-1&quot;&gt;Symbols&lt;/h2&gt;
&lt;hr /&gt;
&lt;ul&gt;
&lt;li&gt;&#92;(x&#92;): Input vector of dimensionality &#92;(d&#92;).&lt;/li&gt;
&lt;li&gt;&#92;(y&#92;): Correct class, an integer on the range &#92;(y &#92;in [1&#92;ldots K]&#92;).&lt;/li&gt;
&lt;li&gt;&#92;(&#92;hat{y}&#92;): Raw outputs (i.e. logits) of our neural network, vector of dimensionality &#92;(K&#92;).&lt;/li&gt;
&lt;li&gt;We use &#92;(&#92;log&#92;) to denote the natural logarithm.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id=&quot;softmax&quot; tabindex=&quot;-1&quot;&gt;Softmax&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;The softmax function is defined as:&lt;br /&gt;
&#92;[
&#92;text{softmax}(x)_i = &#92;frac{e^{x_i}}{&#92;sum_j e^{x_j}}
&#92;]&lt;br /&gt;
The softmax function converts a vector of real numbers (&#92;(x&#92;)) to a vector of probabilities (such that &#92;(&#92;sum_i &#92;text{softmax}(x)_i = 1&#92;) and &#92;(0 &#92;leq &#92;text{softmax}(x)_i &#92;leq 1&#92;)). This is useful for converting the raw final output of a neural network (often referred to as &lt;strong&gt;logits&lt;/strong&gt;) into probabilities.&lt;/p&gt;
&lt;p&gt;In code:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def softmax(x):
    # assumes x is a vector
    return np.exp(x) / np.sum(np.exp(x))

x = np.array([1.2, 2, -4, 0.0]) # might represent raw output logits of a neural network
softmax(x)
# outputs: [0.28310553, 0.63006295, 0.00156177, 0.08526975]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For very large inputs, we start seeing some numerical instability:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;x = np.array([1.2, 2000, -4000, 0.0])
softmax(x)
# outputs: [0., nan, 0.,  0.]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Why? Because floating point numbers aren&#39;t magic, they have limits:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;np.finfo(np.float64).max
# 1.7976931348623157e+308, largest positive number

np.finfo(np.float64).tiny
# 2.2250738585072014e-308, smallest positive number at full precision

np.finfo(np.float64).smallest_subnormal
# 5e-324, smallest positive number
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When we go beyond these limits, we start seeing funky behavior:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;np.finfo(np.float64).max * 2
# inf, overflow error

np.inf - np.inf
# nan, not a number error

np.finfo(np.float64).smallest_subnormal / 2
# 0.0, underflow error
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Looking back at our softmax example that resulted in &lt;code&gt;[0., nan, 0.,  0.]&lt;/code&gt;, we can see that the overflow of &lt;code&gt;np.exp(2000) = np.inf&lt;/code&gt; is causing the &lt;code&gt;nan&lt;/code&gt;, since we end up with &lt;code&gt;np.inf / np.inf = nan&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;If we want to avoid &lt;code&gt;nans&lt;/code&gt;, we need to avoid &lt;code&gt;infs&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;To avoid &lt;code&gt;infs&lt;/code&gt;, we need to avoid overflows.&lt;/p&gt;
&lt;p&gt;To avoid overflows, we need to prevent our numbers from growing too large.&lt;/p&gt;
&lt;p&gt;Underflows on the other hand don&#39;t seem quite as detrimental. Worst case scenario, we get the result &lt;code&gt;0&lt;/code&gt; and lose all precision (i.e. &lt;code&gt;np.exp(-4000) = 0)&lt;/code&gt;. While this is not ideal, this is a lot better than running into &lt;code&gt;inf&lt;/code&gt; and &lt;code&gt;nan&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Given the relative stability of floating point underflows vs overflows, how can we fix softmax?&lt;/p&gt;
&lt;p&gt;Let&#39;s revisit our softmax equation and apply some tricks:&lt;br /&gt;
&#92;[
&#92;begin{align}
&#92;text{softmax}(x)_i
&amp;amp;= &#92;frac{e^{x_i}}{&#92;sum_j e^{x_j}} &#92;&#92;
&amp;amp;= 1&#92;cdot &#92;frac{e^{x_i}}{&#92;sum_j e^{x_j}} &#92;&#92;
&amp;amp;= &#92;frac{C}{C}&#92;frac{e^{x_i}}{&#92;sum_j e^{x_j}} &#92;&#92;
&amp;amp;= &#92;frac{Ce^{x_i}}{&#92;sum_j Ce^{x_j}} &#92;&#92;
&amp;amp;= &#92;frac{e^{x_i + &#92;log C}}{&#92;sum_j e^{x_j + &#92;log C}} &#92;&#92;
&#92;end{align}
&#92;]&lt;br /&gt;
Here, we&#39;re taking advantage of the rule &#92;(a&#92;cdot b^x = b^{x + &#92;log_b a}&#92;). As a result, we are given the ability to offset our inputs by any constant of our choosing. For example, if we set that constant to &#92;(&#92;log C = -&#92;max(x)&#92;):&lt;br /&gt;
&#92;[
&#92;text{softmax}(x)_i = &#92;frac{e^{x_i - &#92;max(x)}}{&#92;sum_j e^{x_j - &#92;max(x)}}
&#92;]&lt;/p&gt;
&lt;p&gt;We get a numerically stable version of softmax:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;All exponentiated values will be between 0 and 1 (&#92;(0 &#92;leq e^{x_i - &#92;max(x)} &#92;leq 1&#92;)) since the value in the exponent is always negative (&#92;(x_i - &#92;max(x) &#92;leq 0&#92;))
&lt;ul&gt;
&lt;li&gt;This prevents overflow errors (but we are still prone to underflows)&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;At least one of the exponentiated values is 1 in the case when &#92;(x_i = &#92;max(x)&#92;): &#92;(e^{ &#92;max(x)- &#92;max(x)} = e^0 = 1&#92;)
&lt;ul&gt;
&lt;li&gt;i.e. at least one value is guaranteed not to underflow&lt;/li&gt;
&lt;li&gt;Thus, our denominator will always be &#92;(&gt;= 1&#92;), preventing division by zero errors&lt;/li&gt;
&lt;li&gt;We have at least one non-zero numerator, so softmax can&#39;t result in a zero vector&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In code:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def softmax(x):
    # assumes x is a vector
    x = x - np.max(x)
    return np.exp(x) / np.sum(np.exp(x))

x = np.array([1.2, 2, -4, 0])
softmax(x)
# outputs: [0.28310553, 0.63006295, 0.00156177, 0.08526975]

# works for large numbers!!!
x = np.array([1.2, 2, -4, 0]) * 1000
softmax(x)
# outputs: [0., 1., 0., 0.]
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;cross-entropy-and-log-softmax&quot; tabindex=&quot;-1&quot;&gt;Cross Entropy and Log Softmax&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;The cross entropy between two probability distributions is defined as.&lt;br /&gt;
&#92;[
H(p, q) = -&#92;sum_i p_i&#92;log(q_i)
&#92;]&lt;br /&gt;
where &#92;(p&#92;) and &#92;(q&#92;) are our probability distributions represented as probability vectors (that is &#92;(p_i&#92;) and &#92;(q_i&#92;) are the probabilities of event &#92;(i&#92;) occurring for &#92;(p&#92;) and &#92;(q&#92;) respectively). This &lt;a href=&quot;https://www.youtube.com/watch?v=ErfnhcEV1O8&quot;&gt;video has a great explanation for cross entropy&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Roughly speaking, cross entropy measures the similarity of two probability distributions. In the context of neural networks, it&#39;s common to use cross entropy as a loss function for classification problems where:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&#92;(q&#92;) is our predicted probabilities vector (i.e. the softmax of our raw network outputs, also called &lt;strong&gt;logits&lt;/strong&gt;, denoted as &#92;(&#92;hat{y}&#92;)), that is &#92;(q = &#92;text{softmax}(&#92;hat{y})&#92;)&lt;/li&gt;
&lt;li&gt;&#92;(p&#92;)  is a one-hot encoded vector of our label, that is a probability vector that assigns 100% probability to the position &#92;(y&#92;) (our label for the correct class): &#92;(p_i = &#92;begin{cases} 1 &amp;amp; i = y &#92;&#92; 0 &amp;amp; i &#92;neq y &#92;end{cases}&#92;)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In this setup, cross entropy simplifies to:&lt;br /&gt;
&#92;[
&#92;begin{align}
H(p, q)
&amp;amp;= -&#92;sum_i p_i&#92;log(q_i) &#92;&#92;
&amp;amp;= -p_y&#92;cdot&#92;log(q_y) -&#92;sum_{i &#92;neq y} p_i&#92;log(q_i) &#92;&#92;
&amp;amp;= -1&#92;cdot&#92;log(q_y) -&#92;sum_{i &#92;neq y} 0&#92;cdot&#92;log(q_i) &#92;&#92;
&amp;amp;= -&#92;log(q_y) - 0 &#92;sum_{i &#92;neq y} &#92;log(q_i) &#92;&#92;
&amp;amp;= -&#92;log(q_y) &#92;&#92;
&amp;amp;= -&#92;log(&#92;text{softmax}(&#92;hat{y})_y)
&#92;end{align}
&#92;]&lt;/p&gt;
&lt;p&gt;In code:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def cross_entropy(y_hat, y_true):
    # assume y_hat is a vector and y_true is an integer
    return -np.log(softmax(y_hat)[y_true])

cross_entropy(
    y_hat=np.random.normal(size=(10)),
    y_true=3,
)
# 2.580982279204241
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;For large numbers in &lt;code&gt;y_hat&lt;/code&gt;, we start seeing &lt;code&gt;inf&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;cross_entropy(
    y_hat = np.array([-1000, 1000]),
    y_true = 0,
)
# inf
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The problem is that &lt;code&gt;softmax([-1000, 1000]) = [0, 1]&lt;/code&gt;, and since &lt;code&gt;y_true = 0&lt;/code&gt;, we get &lt;code&gt;-log(0) = inf&lt;/code&gt;. So we need some way to avoid taking the log of zero. To prevent this, we can rearrange our equation for &lt;code&gt;log(softmax(x))&lt;/code&gt;:&lt;br /&gt;
&#92;[
&#92;begin{align}
&#92;log(&#92;text{softmax}(x)_i)
&amp;amp; = &#92;log(&#92;frac{e^{x_i - &#92;max(x)}}{&#92;sum_j e^{x_j - &#92;max(x)}}) &#92;&#92;
&amp;amp;= &#92;log(e^{x_i - &#92;max(x)}) - &#92;log(&#92;sum_j e^{x_j - &#92;max(x)}) &#92;&#92;
&amp;amp;= (x_i - &#92;max(x))&#92;log(e) - &#92;log(&#92;sum_j e^{x_j - &#92;max(x)}) &#92;&#92;
&amp;amp;= (x_i - &#92;max(x))&#92;cdot 1 - &#92;log(&#92;sum_j e^{x_j - &#92;max(x)}) &#92;&#92;
&amp;amp;= x_i - &#92;max(x) - &#92;log(&#92;sum_j e^{x_j - &#92;max(x)}) &#92;&#92;
&#92;end{align}
&#92;]&lt;br /&gt;
This new equation guarantees that the sum inside the log will always be &#92;(&#92;geq 1&#92;), so we no longer need to worry about &lt;code&gt;log(0)&lt;/code&gt; errors.&lt;/p&gt;
&lt;p&gt;In code:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;def log_softmax(x):
    # assumes x is a vector
    x_max = np.max(x)
    return x - x_max - np.log(np.sum(np.exp(x - x_max)))

def cross_entropy(y_hat, y_true):
    return -log_softmax(y_hat)[y_true]

cross_entropy(
    y_hat=np.random.normal(size=(10)),
    y_true=3,
)
# 2.580982279204241

# works for large inputs!!!!
cross_entropy(
    y_hat = np.array([-1000, 1000]),
    y_true = 0,
)
# 2000.0
&lt;/code&gt;&lt;/pre&gt;
</description>
      <pubDate>Thu, 15 Dec 2022 00:00:00 +0000</pubDate>
      <dc:creator>Jay Mody</dc:creator>
      <guid>https://jaykmody.com/blog/stable-softmax/</guid>
    </item>
    <item>
      <title>An Intuition for Attention</title>
      <link>https://jaykmody.com/blog/attention-intuition/</link>
      <description>&lt;p&gt;ChatGPT and other large language models use a special type of neural network called the transformer. The transformer defining feature is the &lt;em&gt;attention&lt;/em&gt; mechanism. Attention is defined by the equation:&lt;/p&gt;
&lt;p&gt;&#92;[&#92;text{attention}(Q, K, V) = &#92;text{softmax}(&#92;frac{QK^T}{&#92;sqrt{d_k}})V&#92;]&lt;/p&gt;
&lt;p&gt;Attention can come in different forms, but this version of attention (known as scaled dot product attention) was first proposed in the original &lt;a href=&quot;https://arxiv.org/pdf/1706.03762.pdf&quot;&gt;transformer paper&lt;/a&gt;. In this post, we&#39;ll build an intuition for the above equation by deriving it from the ground up.&lt;/p&gt;
&lt;p&gt;To start, let&#39;s take a look at the problem attention aims to solve, the key-value lookup.&lt;/p&gt;
&lt;h2 id=&quot;key-value-lookups&quot; tabindex=&quot;-1&quot;&gt;Key-Value Lookups&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;A key-value (kv) lookup involves three components:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;A list of &#92;(n_k&#92;) &lt;strong&gt;keys&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;A list of &#92;(n_k&#92;) &lt;strong&gt;values&lt;/strong&gt; (that map 1-to-1 with the keys, forming key-value pairs)&lt;/li&gt;
&lt;li&gt;A &lt;strong&gt;query&lt;/strong&gt;, for which we want to &lt;em&gt;match&lt;/em&gt; with the keys and get some value based on the match&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;You&#39;re probably familiar with this concept as a dictionary or hash map:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; d = {
&amp;gt;&amp;gt;&amp;gt;     &amp;quot;apple&amp;quot;: 10,
&amp;gt;&amp;gt;&amp;gt;     &amp;quot;banana&amp;quot;: 5,
&amp;gt;&amp;gt;&amp;gt;     &amp;quot;chair&amp;quot;: 2,
&amp;gt;&amp;gt;&amp;gt; }
&amp;gt;&amp;gt;&amp;gt; d.keys()
[&#39;apple&#39;, &#39;banana&#39;, &#39;chair&#39;]
&amp;gt;&amp;gt;&amp;gt; d.values()
[10, 5, 2]
&amp;gt;&amp;gt;&amp;gt; query = &amp;quot;apple&amp;quot;
&amp;gt;&amp;gt;&amp;gt; d[query]
10
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Dictionaries let us perform lookups based on an &lt;em&gt;exact&lt;/em&gt; string match.&lt;/p&gt;
&lt;p&gt;What if instead we wanted to do a lookup based on the &lt;em&gt;meaning&lt;/em&gt; of a word?&lt;/p&gt;
&lt;h2 id=&quot;key-value-lookups-based-on-meaning&quot; tabindex=&quot;-1&quot;&gt;Key-Value Lookups based on Meaning&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;Say we wanted to look up the word &amp;quot;fruit&amp;quot; in our previous example, how do we choose which key is the best match?&lt;/p&gt;
&lt;p&gt;It&#39;s obviously not &amp;quot;chair&amp;quot;, but both &amp;quot;apple&amp;quot; and &amp;quot;banana&amp;quot; seem like a good match. It&#39;s hard to choose one or the other, fruit feels more like a combination of apple and banana rather than a strict match for either.&lt;/p&gt;
&lt;p&gt;So, let&#39;s not choose. Instead, we&#39;ll do exactly that, take a combination of apple and banana. For example, say we assign a 60% meaning based match for apple, a 40% match for banana, and 0% match for chair. We compute our final output value as the &lt;strong&gt;weighted sum&lt;/strong&gt; of the values with the percentages:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; query = &amp;quot;fruit&amp;quot;
&amp;gt;&amp;gt;&amp;gt; d = {&amp;quot;apple&amp;quot;: 10, &amp;quot;banana&amp;quot;: 5, &amp;quot;chair&amp;quot;: 2}
&amp;gt;&amp;gt;&amp;gt; 0.6 * d[&amp;quot;apple&amp;quot;] + 0.4 * d[&amp;quot;banana&amp;quot;] + 0.0 * d[&amp;quot;chair&amp;quot;]
8
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In a sense, we are determining how much &lt;strong&gt;attention&lt;/strong&gt; our query should be paying to each key-value pair based on &lt;em&gt;meaning&lt;/em&gt;. The amount of &amp;quot;attention&amp;quot; is represented as a decimal percentage, called an &lt;strong&gt;attention score&lt;/strong&gt;. Mathematically, we can define our output as a simple weighted sum:&lt;br /&gt;
&#92;[
&#92;sum_{i} &#92;alpha_iv_i
&#92;]where &#92;(&#92;alpha_i&#92;) is our attention score for the &#92;(i&#92;)th kv pair and &#92;(v_i&#92;) is the &#92;(i&#92;)th value. Remember, the attention scores are decimal percentages, that is they must be between 0 and 1 inclusive (&#92;(0 &#92;leq &#92;alpha_i &#92;leq 1&#92;)) and their sum must be 1 (&#92;(&#92;sum_i a_i = 1&#92;)).&lt;/p&gt;
&lt;p&gt;Okay, but where did we get these attention scores from? In our example, I just kind of chose them based on what I &lt;em&gt;felt&lt;/em&gt;. While I think I did a pretty good job, this approach doesn&#39;t seem sustainable (unless you can find a way to make a copy of me inside your computer).&lt;/p&gt;
&lt;p&gt;Instead, let&#39;s take a look at how &lt;strong&gt;word vectors&lt;/strong&gt; can help solve our problem of determining attention scores.&lt;/p&gt;
&lt;h2 id=&quot;word-vectors-and-similarity&quot; tabindex=&quot;-1&quot;&gt;Word Vectors and Similarity&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;Imagine we represent a word with a vector of numbers. Ideally, the values in the vector should in some way capture the &lt;em&gt;meaning&lt;/em&gt; of the word it represents. For example, imagine we have the following word vectors (visualized in 2D space):&lt;/p&gt;
&lt;figure&gt;&lt;img src=&quot;https://i.imgur.com/VDnSf7P.png&quot; alt=&quot;&quot; /&gt;&lt;/figure&gt;
&lt;p&gt;You can see that words that are &lt;em&gt;similar&lt;/em&gt; are clustered together. Fruits are clustered at the top right, vegetables are clustered at the top left, and furniture is clustered at the bottom. In fact, you can even see that the vegetable and fruit clusters are closer to each other than they are to the furniture cluster, since they are more closely related things.&lt;/p&gt;
&lt;p&gt;You can even imagine doing arithmetic on word vectors. For example, given the words &amp;quot;king&amp;quot;, &amp;quot;queen&amp;quot;, &amp;quot;man&amp;quot;, and &amp;quot;woman&amp;quot; and their respective vector representations &#92;(&#92;boldsymbol{v}_{&#92;text{king}}, &#92;boldsymbol{v}_{&#92;text{queen}}, &#92;boldsymbol{v}_{&#92;text{man}}, &#92;boldsymbol{v}_{&#92;text{women}}&#92;), we can imagine that:&lt;br /&gt;
&#92;[&#92;boldsymbol{v}_{&#92;text{queen}} - &#92;boldsymbol{v}_{&#92;text{woman}} + &#92;boldsymbol{v}_{&#92;text{man}} &#92;sim &#92;boldsymbol{v}_{&#92;text{king}}&#92;]That is, the vector for &amp;quot;queen&amp;quot; minus &amp;quot;woman&amp;quot; plus &amp;quot;man&amp;quot; should result in a vector that is &lt;em&gt;similar&lt;/em&gt; to the vector for &amp;quot;king&amp;quot;.&lt;/p&gt;
&lt;p&gt;But what does it exactly mean for two vectors to be &lt;em&gt;similar&lt;/em&gt;? In the fruits/vegetables example, we were using distance as a measure of similarity (in particular, &lt;a href=&quot;https://en.wikipedia.org/wiki/Euclidean_distance&quot;&gt;euclidean distance&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;There are also &lt;a href=&quot;https://towardsdatascience.com/9-distance-measures-in-data-science-918109d069fa&quot;&gt;other ways to measure similarity between two vectors&lt;/a&gt;, each with its own advantages and disadvantages. Possibly the simplest measure of similarity between two vectors is their dot product:&lt;br /&gt;
&#92;[&#92;boldsymbol{v} &#92;cdot &#92;boldsymbol{w} = &#92;sum_{i}v_i w_i&#92;]&lt;a href=&quot;https://www.youtube.com/watch?v=LyGKycYT2v0&quot;&gt;3blue1brown has a great video on the intuition behind dot product&lt;/a&gt;, but for our purposes all we need to know is:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If two vectors are pointing in the same direction, the dot product will be &amp;gt; 0 (i.e. similar)&lt;/li&gt;
&lt;li&gt;If they are pointing in opposing directions, the dot product will be &amp;lt; 0 (i.e. dissimilar)&lt;/li&gt;
&lt;li&gt;If they are exactly perpendicular, the dot product will be 0 (i.e. neutral)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Using this information, we can define a simple heuristic to determine the similarity between two word vectors: The greater the dot product, the more similar two words are in &lt;em&gt;meaning&lt;/em&gt;.&lt;sup class=&quot;footnote-ref&quot;&gt;&lt;a href=&quot;https://jaykmody.com/blog/attention-intuition/#fn1&quot; id=&quot;fnref1&quot;&gt;[1]&lt;/a&gt;&lt;/sup&gt;&lt;/p&gt;
&lt;p&gt;Okay cool, but where do these word vectors actually come from? In the context of neural networks, they usually come from some kind of learned embedding or latent representation. That is, initially the word vectors are just random numbers, but as the neural network is trained, their values are adjusted to become better and better representations for words. How does a neural network learn these better representations? That is beyond the scope of this blog post, you&#39;ll have to take an intro to deep learning course for that. For now, we just need to accept that word vectors exist, and that they somehow are able to capture the meaning of words.&lt;/p&gt;
&lt;h2 id=&quot;attention-scores-using-the-dot-product&quot; tabindex=&quot;-1&quot;&gt;Attention Scores using the Dot Product&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;Let&#39;s return to our example of fruits, but this time around using word vectors to represent our words. That is &#92;(&#92;boldsymbol{q} = &#92;boldsymbol{v}_{&#92;text{fruit}}&#92;) and &#92;(&#92;boldsymbol{k} = [&#92;boldsymbol{v}_{&#92;text{apple}} &#92; &#92;boldsymbol{v}_{&#92;text{banana}} &#92; &#92;boldsymbol{v}_{&#92;text{chair}}]&#92;), such that &#92;(&#92;boldsymbol{v} &#92;in &#92;mathbb{R}^{d_k}&#92;) (that is each vector has the same dimensionality of &#92;(d_k&#92;), which is a value we choose when training a neural network).&lt;/p&gt;
&lt;p&gt;Using our new dot product similarity measure, we can compute the similarity between the query and the &#92;(i&#92;)th key as:&lt;br /&gt;
&#92;[
x_i = &#92;boldsymbol{q} &#92;cdot &#92;boldsymbol{k}_i
&#92;]&lt;br /&gt;
Generalizing this further, we can compute the dot product for all &#92;(n_k&#92;) keys with:&lt;br /&gt;
&#92;[
&#92;boldsymbol{x} = &#92;boldsymbol{q}{K}^T
&#92;]where &#92;(&#92;boldsymbol{x}&#92;) is our vector of dot products &#92;(&#92;boldsymbol{x} = [x_1, x_2, &#92;ldots, x_{n_k - 1}, x_{n_k}]&#92;) and &#92;(K&#92;) is a row-wise matrix of our key vectors (i.e. our key vectors stacked on-top of each-other to form a &#92;(n_k&#92;) by &#92;(d_k&#92;) matrix such that &#92;(k_i&#92;) is the &#92;(i&#92;)th row of &#92;(K&#92;)). If you&#39;re having trouble understanding this, see the following footnote &lt;sup class=&quot;footnote-ref&quot;&gt;&lt;a href=&quot;https://jaykmody.com/blog/attention-intuition/#fn2&quot; id=&quot;fnref2&quot;&gt;[2]&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;
&lt;p&gt;Recall that our attention scores need to be decimal percentages (between 0 and 1 and sum to 1). Our dot product values however can be any real number (i.e. between &#92;(-&#92;infty&#92;) and &#92;(&#92;infty&#92;)). To transform our dot product values to decimal percentages, we&#39;ll use the &lt;a href=&quot;https://en.wikipedia.org/wiki/Softmax_function&quot;&gt;softmax function&lt;/a&gt;:&lt;br /&gt;
&#92;[
&#92;text{softmax}(&#92;boldsymbol{x})_i = &#92;frac{e^{x_i}}{&#92;sum_j e^{x_j}}
&#92;]&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;&amp;gt;&amp;gt;&amp;gt; import numpy as np
&amp;gt;&amp;gt;&amp;gt; def softmax(x):
&amp;gt;&amp;gt;&amp;gt;     # assumes x is a vector
&amp;gt;&amp;gt;&amp;gt;     return np.exp(x) / np.sum(np.exp(x))
&amp;gt;&amp;gt;&amp;gt;
&amp;gt;&amp;gt;&amp;gt; softmax(np.array([4.0, -1.0, 2.1]))
[0.8648, 0.0058, 0.1294]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;✅ Each number is between 0 and 1&lt;/li&gt;
&lt;li&gt;✅ The numbers sum to 1&lt;/li&gt;
&lt;li&gt;✅ The larger valued inputs get more &amp;quot;weight&amp;quot;&lt;/li&gt;
&lt;li&gt;✅ The sorted order is preserved (i.e. the 4.0 is still the largest after softmax, and -1.0 is still the lowest), this is because softmax is a &lt;a href=&quot;https://en.wikipedia.org/wiki/Monotonic_function&quot;&gt;monotonic&lt;/a&gt; function&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This satisfies all the desired properties of an attention scores. Thus, we can compute the attention score for the &#92;(i&#92;)th key-value pair with:&lt;br /&gt;
&#92;[
&#92;alpha_i = &#92;text{softmax}(&#92;boldsymbol{x})_i = &#92;text{softmax}(&#92;boldsymbol{q}K^T)_i
&#92;]Plugging this into our weighted sum we get:&lt;br /&gt;
&#92;[
&#92;begin{align}
&#92;sum_{i}&#92;alpha_iv_i
= &amp;amp; &#92;sum_i &#92;text{softmax}(&#92;boldsymbol{x})_iv_i&#92;&#92;
= &amp;amp; &#92;sum_i &#92;text{softmax}(&#92;boldsymbol{q}K^T)_iv_i&#92;&#92;
= &amp;amp;&#92; &#92;text{softmax}(&#92;boldsymbol{q}K^T)&#92;boldsymbol{v}
&#92;end{align}
&#92;]&lt;br /&gt;
Note: In the last step, we pack our values into a vector &#92;(&#92;boldsymbol{v} = [v_1, v_2, ..., v_{n_k -1}, v_{n_k}]&#92;), which allows us to get rid of the summation notation in favor of a dot product.&lt;/p&gt;
&lt;p&gt;And that&#39;s it, we have a full working definition for attention:&lt;br /&gt;
&#92;[
&#92;text{attention}(&#92;boldsymbol{q}, K, &#92;boldsymbol{v}) = &#92;text{softmax}(&#92;boldsymbol{q}K^T)&#92;boldsymbol{v}
&#92;]In code:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import numpy as np

def get_word_vector(word, d_k=8):
    &amp;quot;&amp;quot;&amp;quot;Hypothetical mapping that returns a word vector of size
    d_k for the given word. For demonstrative purposes, we initialize
    this vector randomly, but in practice this would come from a learned
    embedding or some kind of latent representation.&amp;quot;&amp;quot;&amp;quot;
    return np.random.normal(size=(d_k,))

def softmax(x):
    # assumes x is a vector
    return np.exp(x) / np.sum(np.exp(x))

def attention(q, K, v):
    # assumes q is a vector of shape (d_k)
    # assumes K is a matrix of shape (n_k, d_k)
    # assumes v is a vector of shape (n_k)
    return softmax(q @ K.T) @ v

def kv_lookup(query, keys, values):
    return attention(
        q = get_word_vector(query),
        K = np.array([get_word_vector(key) for key in keys]),
        v = values,
    )

# returns some float number
print(kv_lookup(&amp;quot;fruit&amp;quot;, [&amp;quot;apple&amp;quot;, &amp;quot;banana&amp;quot;, &amp;quot;chair&amp;quot;], [10, 5, 2]))
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;scaled-dot-product-attention&quot; tabindex=&quot;-1&quot;&gt;Scaled Dot Product Attention&lt;/h2&gt;
&lt;hr /&gt;
&lt;p&gt;In principle, the attention equation we derived in the last section is complete. However, we&#39;ll need to make a couple of changes to match the version in &lt;a href=&quot;https://arxiv.org/pdf/1706.03762.pdf&quot;&gt;Attention is All You Need&lt;/a&gt;.&lt;/p&gt;
&lt;h4 id=&quot;values-as-vectors&quot; tabindex=&quot;-1&quot;&gt;Values as Vectors&lt;/h4&gt;
&lt;p&gt;Currently, our values in the key-value pairs are just numbers. However, we could also instead replace them with vectors of some size &#92;(d_v&#92;). For example, with &#92;(d_v = 4&#92;), you might have:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;d = {
    &amp;quot;apple&amp;quot;: [0.9, 0.2, -0.5, 1.0]
    &amp;quot;banana&amp;quot;: [1.2, 2.0, 0.1, 0.2]
    &amp;quot;chair&amp;quot;: [-1.2, -2.0, 1.0, -0.2]
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;When we compute our output via a weighted sum, we&#39;d be doing a weighted sum over vectors instead of numbers (i.e. scalar-vector multiplication instead of scalar-scalar multiplication). This is desirable because vectors let us hold/convey more information than just a single number.&lt;/p&gt;
&lt;p&gt;To adjust for this change in our equation, instead of multiply our attention scores by a vector &#92;(v&#92;) we multiply it by the row-wise matrix of our value vectors &#92;(V&#92;) (similar to how we stacked our keys to form &#92;(K&#92;)):&lt;br /&gt;
&#92;[
&#92;text{attention}(&#92;boldsymbol{q}, K, V) = &#92;text{softmax}(&#92;boldsymbol{q}K^T)V
&#92;]Of course, our output is no longer a scalar, instead it would be a vector of dimensionality &#92;(d_v&#92;).&lt;/p&gt;
&lt;h4 id=&quot;scaling&quot; tabindex=&quot;-1&quot;&gt;Scaling&lt;/h4&gt;
&lt;p&gt;The dot product between our query and keys can get really large in magnitude if &#92;(d_k&#92;) is large. This makes the output of softmax more &lt;em&gt;extreme&lt;/em&gt;. For example, &lt;code&gt;softmax([3, 2, 1]) = [0.665, 0.244, 0.090]&lt;/code&gt;, but with larger values &lt;code&gt;softmax([30, 20, 10]) = [9.99954600e-01, 4.53978686e-05, 2.06106005e-09]&lt;/code&gt;. When training a neural network, this would mean the gradients would become really small which is undesirable. As a solution, we scale our pre-softmax scores by &#92;(&#92;frac{1}{&#92;sqrt{d_k}}&#92;):&lt;/p&gt;
&lt;p&gt;&#92;[
&#92;text{attention}(&#92;boldsymbol{q}, K, V) = &#92;text{softmax}(&#92;frac{&#92;boldsymbol{q}K^T}{&#92;sqrt{d_k}})V
&#92;]&lt;/p&gt;
&lt;h4 id=&quot;multiple-queries&quot; tabindex=&quot;-1&quot;&gt;Multiple Queries&lt;/h4&gt;
&lt;p&gt;In practice, we often want to perform multiple lookups for &#92;(n_q&#92;) different queries rather than just a single query. Of course, we could always do this one at a time, plugging each query individually into the above equation. However, if we stack of query vectors row-wise as a matrix &#92;(Q&#92;) (in the same way we did for &#92;(K&#92;) and &#92;(V&#92;)), we can compute our output as an &#92;(n_q&#92;) by &#92;(d_v&#92;) matrix where row &#92;(i&#92;) is the output vector for the attention on the &#92;(i&#92;)th query:&lt;br /&gt;
&#92;[
&#92;text{attention}(Q, K, V) = &#92;text{softmax}(&#92;frac{QK^T}{&#92;sqrt{d_k}})V
&#92;]that is, &#92;(&#92;text{attention}(Q, K, V)_i = &#92;text{attention}(q_i, K, V)&#92;).&lt;/p&gt;
&lt;p&gt;This makes computation faster than if we ran attention for each query sequentially (say, in a for loop) since we can parallelize calculations (particularly when using a GPU).&lt;/p&gt;
&lt;p&gt;Note, our input to softmax becomes a matrix instead of a vector. When we write softmax here, we mean that we are taking the softmax along each row of the matrix independently, as if we were doing things sequentially.&lt;/p&gt;
&lt;h4 id=&quot;result&quot; tabindex=&quot;-1&quot;&gt;Result&lt;/h4&gt;
&lt;p&gt;With that, we have our final equation for scaled dot product attention as it&#39;s written in the original paper:&lt;br /&gt;
&#92;[
&#92;text{attention}(Q, K, V) = &#92;text{softmax}(&#92;frac{QK^T}{&#92;sqrt{d_k}})V
&#92;]In code:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;import numpy as np

def softmax(x):
    # assumes x is a matrix and we want to take the softmax along each row
    # (which is achieved using axis=-1 and keepdims=True)
    return np.exp(x) / np.sum(np.exp(x), axis=-1, keepdims=True)

def attention(Q, K, V):
    # assumes Q is a matrix of shape (n_q, d_k)
    # assumes K is a matrix of shape (n_k, d_k)
    # assumes v is a matrix of shape (n_k, d_v)
    # output is a matrix of shape (n_q, d_v)
    d_k = K.shape[-1]
    return softmax(Q @ K.T / np.sqrt(d_k)) @ V
&lt;/code&gt;&lt;/pre&gt;
&lt;hr class=&quot;footnotes-sep&quot; /&gt;
&lt;section class=&quot;footnotes&quot;&gt;
&lt;ol class=&quot;footnotes-list&quot;&gt;
&lt;li id=&quot;fn1&quot; class=&quot;footnote-item&quot;&gt;&lt;p&gt;You&#39;ll note that the magnitude of the vectors have an influence on the output of dot product. For example, given 3 vectors, &#92;(a=[1, 1, 1]&#92;), &#92;(b=[1000, 0, 0]&#92;), and &#92;(c=[2, 2, 2]&#92;), our dot product heuristic would tell us that becuase &#92;(a &#92;cdot b &gt; a &#92;cdot c&#92;)  that &#92;(a&#92;) is more similar to &#92;(c&#92;) than &#92;(a&#92;) is to &#92;(b&#92;). This doesn&#39;t seem right, since &#92;(b&#92;) and &#92;(a&#92;) are pointing in the exact same direction, while &#92;(c&#92;) and &#92;(a&#92;) are not. &lt;a href=&quot;https://en.wikipedia.org/wiki/Cosine_similarity&quot;&gt;Cosine similarity&lt;/a&gt; accounts for this normalizing the vectors to unit vectors before taking the dot product, essentially ignoring the magnitudes and only caring about the direction. So why don&#39;t we take the cosine similarity? In a deep learning setting, the magnitude of a vector might actually contain information we care about (and we shouldn&#39;t get rid of it). Also, if we regularize our networks properly, outlier examples like the above should not occur. &lt;a href=&quot;https://jaykmody.com/blog/attention-intuition/#fnref1&quot; class=&quot;footnote-backref&quot;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;li id=&quot;fn2&quot; class=&quot;footnote-item&quot;&gt;&lt;p&gt;Basically, instead of computing each dot product separately:&lt;br /&gt;
&#92;[
&#92;begin{align}
x_1 = &amp;amp; &#92; &#92;boldsymbol{q} &#92;cdot &#92;boldsymbol{k}_1 = [2, 1, 3] &#92;cdot [-1, 2, -1] = -3&#92;&#92;
x_2 = &amp;amp; &#92; &#92;boldsymbol{q} &#92;cdot &#92;boldsymbol{k}_2 = [2, 1, 3] &#92;cdot [1.5, 0, -1] = 0&#92;&#92;
x_3 = &amp;amp; &#92; &#92;boldsymbol{q} &#92;cdot &#92;boldsymbol{k}_3 = [2, 1, 3] &#92;cdot [4, -2, -1] = 3
&#92;end{align}
&#92;]&lt;br /&gt;
You compute it all at once:&lt;br /&gt;
&#92;[
&#92;begin{align}
&#92;boldsymbol{x} &amp;amp; = &#92;boldsymbol{q}{K}^T &#92;&#92;
&amp;amp; = &#92;begin{bmatrix}2 &amp;amp; 1 &amp;amp; 3&#92;end{bmatrix}&#92;begin{bmatrix}-1 &amp;amp; 2 &amp;amp; -1&#92;&#92;1.5 &amp;amp; 0 &amp;amp; -1&#92;&#92;4 &amp;amp; -2 &amp;amp; -1&#92;end{bmatrix}^T&#92;&#92;
&amp;amp; = &#92;begin{bmatrix}2 &amp;amp; 1 &amp;amp; 3&#92;end{bmatrix}&#92;begin{bmatrix}-1 &amp;amp; 1.5 &amp;amp; 4&#92;&#92;2 &amp;amp; 0 &amp;amp; -2&#92;&#92;-1 &amp;amp; -1 &amp;amp; -1&#92;end{bmatrix}&#92;&#92;
&amp;amp; = [-3, 0, 3]&#92;&#92;
&amp;amp; = [x_1, x_2, x_3]
&#92;end{align}
&#92;] &lt;a href=&quot;https://jaykmody.com/blog/attention-intuition/#fnref2&quot; class=&quot;footnote-backref&quot;&gt;↩︎&lt;/a&gt;&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;
</description>
      <pubDate>Sat, 22 Oct 2022 00:00:00 +0000</pubDate>
      <dc:creator>Jay Mody</dc:creator>
      <guid>https://jaykmody.com/blog/attention-intuition/</guid>
    </item>
    <item>
      <title>Computing Distance Matrices with NumPy</title>
      <link>https://jaykmody.com/blog/distance-matrices-with-numpy/</link>
      <description>&lt;h2 id=&quot;background&quot; tabindex=&quot;-1&quot;&gt;Background&lt;/h2&gt;
&lt;p&gt;A &lt;a href=&quot;https://en.wikipedia.org/wiki/Distance_matrix#:~:text=In%20mathematics%2C%20computer%20science%20and,may%20not%20be%20a%20metric.&quot;&gt;distance matrix&lt;/a&gt; is a square matrix that captures the pairwise distances between a set of vectors. More formally:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;Given a set of vectors &#92;(v_1, v_2, ... v_n&#92;) and it&#39;s distance matrix &#92;(&#92;text{dist}&#92;), the element &#92;(&#92;text{dist}_{ij}&#92;) in the matrix would represent the distance between &#92;(v_i&#92;) and &#92;(v_j&#92;). Notice, this means the matrix is symmetric since &#92;(&#92;text{dist}_{ij} = &#92;text{dist}_{ji}&#92;), and the dimensionality (size) of the matrix is &#92;((n, n)&#92;).&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The above definition, however, doesn&#39;t define what &lt;em&gt;distance&lt;/em&gt; means. There are &lt;a href=&quot;https://numerics.mathdotnet.com/Distance.html&quot;&gt;many ways to define and compute the distance between two vectors&lt;/a&gt;, but usually, when speaking of the distance between vectors, we are referring to their &lt;em&gt;euclidean distance&lt;/em&gt;. Euclidean distance is our intuitive notion of what distance is (i.e. shortest line between two points on a map). Mathematically, we can define euclidean distance between two vectors &#92;(u, v&#92;) as,&lt;/p&gt;
&lt;p&gt;&#92;[|| u - v ||_2 = &#92;sqrt{&#92;sum_{k=1}^d (u_k - v_k)^2}&#92;]&lt;/p&gt;
&lt;p&gt;where &#92;(d&#92;) is the dimensionality (size) of the vectors.&lt;/p&gt;
&lt;p&gt;By itself, distance matrixes are already highly useful in all kinds of applications, from math, to computer science, to graph theory, to bio-informatics. Let&#39;s explore one particular application for distance matrices, machine learning.&lt;/p&gt;
&lt;h2 id=&quot;motivating-example%3A-k-nearest-neighbors&quot; tabindex=&quot;-1&quot;&gt;Motivating Example: k-Nearest Neighbors&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://cs231n.github.io/classification/#k---nearest-neighbor-classifier&quot;&gt;k-Nearest Neighbour&lt;/a&gt; (kNN) is a machine learning classification algorithm that utilizes distance matrices under the hood. The idea is simple, we can predict the class of any given data point by looking at the classes of the &#92;(k&#92;) nearest neighboring labelled data points. Whichever class is most common within the neighbors is the class we predict for the data point.&lt;/p&gt;
&lt;p&gt;How do you determine which labelled points are the &amp;quot;nearest&amp;quot;? Well, if we represent each data point as a vector, we can compute their euclidean distance.&lt;/p&gt;
&lt;p&gt;Let&#39;s say instead of just predicting for a single point, you want to predict for multiple points. More formally, you are given &#92;(n&#92;) labelled data points (train data), and &#92;(m&#92;) unlabelled data points (test data, for which you would like to classify). The data points are represented as vectors, of dimensionality &#92;(d&#92;). In order to implement the kNN classifier, you&#39;ll need to compute the distances between all labelled-unlabelled pairs. These distances can be stored in an &#92;((m, n)&#92;) matrix &#92;(&#92;text{dist}&#92;), where &#92;(&#92;text{dist}_{ij}&#92;) represents the distance between the ith unlabelled point and the jth labelled point. If we represent our labelled data points by the &#92;((n, d)&#92;) matrix &#92;(Y&#92;), and our unlabelled data points by the &#92;((m, d)&#92;) matrix &#92;(X&#92;), the distance matrix can be formulated as:&lt;/p&gt;
&lt;p&gt;&#92;[&#92;text{dist}_{ij} = &#92;sqrt{&#92;sum_{k=1}^d (X_{ik} - Y_{jk})^2}&#92;]&lt;/p&gt;
&lt;p&gt;This distance computation is really the meat of the algorithm, and what I&#39;ll be focusing on for this post. Let&#39;s implement it.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; I use the term distance matrix here even though the matrix is no longer square (since we are computing the distances between two sets of vectors and not just one).&lt;/p&gt;
&lt;h2 id=&quot;three-loop&quot; tabindex=&quot;-1&quot;&gt;Three Loop&lt;/h2&gt;
&lt;p&gt;Most simple way to compute our distance matrix is to just loop over all the pairs and elements:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;X # test data (m, d)
X_train # train data (n, d)

m = X.shape[0]
n = X_train.shape[0]
d = X.shape[1]
dists = np.zeros((num_test, num_train)) # distance matrix (m, n)

for i in range(m):
    for j in range(n):
        val = 0
        for k in range(d):
            val += (X[i][k] - X_train[j][k]) ** 2
        dists[i][j] = np.sqrt(val)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;While this works, it&#39;s quite inefficient and doesn&#39;t take advantage of numpy&#39;s efficient vectorized operations. Let&#39;s change that.&lt;/p&gt;
&lt;h2 id=&quot;two-loops&quot; tabindex=&quot;-1&quot;&gt;Two Loops&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;for i in range(m):
    for j in range(n):
        # element-wise subtract, element-wise square, take the sum and sqrt
        dists[i][j] = np.sqrt(np.sum((X[i] - X_train[j]) ** 2))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That wasn&#39;t too bad, we even made it easier to read if you&#39;re asking me, but we can do better.&lt;/p&gt;
&lt;h2 id=&quot;one-loop&quot; tabindex=&quot;-1&quot;&gt;One Loop&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;for i in range(m):
    dists[i, :] = np.sqrt(np.sum((X[i] - X_train) ** 2, axis=1))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;What the hell is going on here?! Ok let&#39;s break it down.&lt;/p&gt;
&lt;p&gt;Firstly, shouldn&#39;t &lt;code&gt;X[i] - X_train&lt;/code&gt; result in an error?  &lt;code&gt;X[i]&lt;/code&gt; has shape &#92;((d)&#92;) while &lt;code&gt;X_train&lt;/code&gt; has shape &#92;((n, d)&#92;). Element-wise operations only work if both parties have the same shape, so what&#39;s happening here?&lt;/p&gt;
&lt;p&gt;Numpy is automatically &lt;a href=&quot;https://numpy.org/doc/stable/user/basics.broadcasting.html&quot;&gt;broadcasting&lt;/a&gt; &lt;code&gt;X[i]&lt;/code&gt; to match the shape of &lt;code&gt;X_train&lt;/code&gt;. You can think of this as stacking &lt;code&gt;X[i]&lt;/code&gt; &#92;(n&#92;) times to produce an &#92;((n, d)&#92;) matrix where each row is just a copy of &lt;code&gt;X[i]&lt;/code&gt;. This way, when performing the subtraction, each row of &lt;code&gt;X_train&lt;/code&gt; is being subtracted by &lt;code&gt;X[i]&lt;/code&gt; (or the other way around, it doesn&#39;t matter since we&#39;ll be taking the square of the result). If you wanted, you can create the &amp;quot;stacked&amp;quot; matrix yourself in numpy using &lt;code&gt;np.tile&lt;/code&gt;, but it would be &lt;a href=&quot;https://gist.github.com/jaymody/9d7dec07300f817ddd40b74b1d648a34&quot;&gt;slower then if you let numpy handle it with broadcasting&lt;/a&gt;. So now we have an &#92;((n, d)&#92;) matrix where each row is &lt;code&gt;X[i] - X_train[j]&lt;/code&gt;, sick.&lt;/p&gt;
&lt;p&gt;The next step is easy,  we perform an element-wise square. Then, we need to take the sum of each row, so we use &lt;code&gt;np.sum&lt;/code&gt; with the argument &lt;code&gt;axis=1&lt;/code&gt; which tells numpy to sum across the first axis (ie the rows). Without the axis argument, &lt;code&gt;np.sum&lt;/code&gt; will take the sum of every element in the matrix and output a single scalar value. The result of the &lt;code&gt;np.sum&lt;/code&gt; with &lt;code&gt;axis=1&lt;/code&gt; gives us a vector of size &#92;(n&#92;).&lt;/p&gt;
&lt;p&gt;Finally, we take the element-wise square root of this vector and store it in &#92;(dists[i]&#92;).&lt;/p&gt;
&lt;p&gt;So here&#39;s a better annotated version of the code that&#39;s much easier to understand:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;for i in range(m):
    # X[i] gets broadcasted (d) -&amp;gt; (n, d)
    # (each row is a copy of X[i])
    diffs = X[i] - X_train

    # element wise square
    squared = diffs ** 2

    # take the sum of each row (n, d) -&amp;gt; (n)
    sums = np.sum(squared, axis=1)

    # take the element-wise square root and store them in dists
    dists[i, :] = np.sqrt(sums)
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;no-loops%3F!&quot; tabindex=&quot;-1&quot;&gt;No Loops?!&lt;/h2&gt;
&lt;p&gt;We can do even better and only use vector/matrix operations, no loops needed. How you ask? Let&#39;s take a closer look at our equation:&lt;/p&gt;
&lt;p&gt;&#92;[&#92;text{dist}_{ij} = &#92;sqrt{&#92;sum_{k=1}^d (x_{ik} - y_{jk})^2}&#92;]&lt;/p&gt;
&lt;p&gt;What happens if we expand out the expression in the sum?&lt;/p&gt;
&lt;p&gt;&#92;[
&#92;text{dist}_{ij} = &#92;sqrt{&#92;sum_{k=1}^d x^2_{ik} - 2x_{ik}y_{jk} + y^2_{jk}}&#92;&#92;
&#92;]&lt;/p&gt;
&lt;p&gt;Interesting, let&#39;s distribute the sum:&lt;/p&gt;
&lt;p&gt;&#92;[
&#92;text{dist}_{ij} = &#92;sqrt{&#92;sum_{k=1}^d x^2_{ik} - 2 &#92;sum_{k=1}^d x_{ik}y_{jk} + &#92;sum_{k=1}^dy^2_{jk}}&#92;&#92;
&#92;]&lt;/p&gt;
&lt;p&gt;You&#39;ll notice that each of these sums are just dot products, so let&#39;s replace the ugly notation and get a much cleaner expression:&lt;/p&gt;
&lt;p&gt;&#92;[
&#92;text{dist}_{ij} = &#92;sqrt{x_i &#92;cdot x_i - 2x_i &#92;cdot y_j + y_j &#92;cdot y_j}&#92;&#92;
&#92;]&lt;/p&gt;
&lt;p&gt;Notice, for all combinations of &#92;(i, j&#92;), the middle term is unique, but the left and right terms are repeated. Imagine fixing either &#92;(i&#92;) or &#92;(j&#92;) and iterate the other variable, you&#39;ll see that &#92;(x_i &#92;cdot x_i&#92;) shows up &#92;(j&#92;) times and &#92;(y_j &#92;cdot y_j&#92;) shows up &#92;(i&#92;) times. So, our challenge is to figure out how to compute all possible &#92;(x_i &#92;cdot x_i&#92;), &#92;(x_i &#92;cdot y_j&#92;), and  &#92;(y_j &#92;cdot y_j&#92;), and then add them together in the right way. All of this without loops. Let&#39;s try it:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;# this has the same affect as taking the dot product of each row with itself
x2 = np.sum(X**2, axis=1) # shape of (m)
y2 = np.sum(X_train**2, axis=1) # shape of (n)

# we can compute all x_i * y_j and store it in a matrix at xy[i][j] by
# taking the matrix multiplication between X and X_train transpose
# if you&#39;re stuggling to understand this, draw out the matrices and
# do the matrix multiplication by hand
# (m, d) x (d, n) -&amp;gt; (m, n)
xy = np.matmul(X, X_train.T)

# each row in xy needs to be added with x2[i]
# each column of xy needs to be added with y2[j]
# to get everything to play well, we&#39;ll need to reshape
# x2 from (m) -&amp;gt; (m, 1), numpy will handle the rest of the broadcasting for us
# see: https://numpy.org/doc/stable/user/basics.broadcasting.html
x2 = x2.reshape(-1, 1)
dists = np.sqrt(x2 - 2*xy + y2) # (m, 1) repeat columnwise + (m, n) + (n) repeat rowwise -&amp;gt; (m, n)
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;-1-loops%3F!!%3F!-%F0%9F%A4%94&quot; tabindex=&quot;-1&quot;&gt;-1 Loops?!!?! 🤔&lt;/h2&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;from sklearn.neighbors import KNeighborsClassifier
&lt;/code&gt;&lt;/pre&gt;
&lt;h2 id=&quot;speed-comparison&quot; tabindex=&quot;-1&quot;&gt;Speed Comparison&lt;/h2&gt;
&lt;p&gt;To test the speed of each implementation, we can run it against a small subset of the cifar-10 dataset as seen in the &lt;a href=&quot;https://github.com/jaymody/cs231n/blob/master/assignment1/knn.ipynb&quot;&gt;cs231n assignment 1 knn notebook&lt;/a&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;Two loop version took 39.707250 seconds
One loop version took 28.705156 seconds
No loop version took 0.218127 seconds
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Clearly, we can see the no loop version is the winner, beating out both the two loop and one loop implementations by orders of magnitudes. Notice, I didn&#39;t include the three loop implementation because that would have taken hours to run! On just &lt;code&gt;10&lt;/code&gt; training and &lt;code&gt;10&lt;/code&gt; test examples, the three loop implementation took  &lt;code&gt;0.5&lt;/code&gt; seconds. For reference, the above time profiles are for &lt;code&gt;5000&lt;/code&gt; training and &lt;code&gt;500&lt;/code&gt; test examples, yikes! +1 for vector operations!&lt;/p&gt;
</description>
      <pubDate>Sun, 04 Apr 2021 00:00:00 +0000</pubDate>
      <dc:creator>Jay Mody</dc:creator>
      <guid>https://jaykmody.com/blog/distance-matrices-with-numpy/</guid>
    </item>
  </channel>
</rss>
