<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Matheus Oliveira De Souza on Medium]]></title>
        <description><![CDATA[Stories by Matheus Oliveira De Souza on Medium]]></description>
        <link>https://medium.com/@msouza.os?source=rss-a79d034ca14b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1yJ1vHpLv3uG615vC8MlHQ.jpeg</url>
            <title>Stories by Matheus Oliveira De Souza on Medium</title>
            <link>https://medium.com/@msouza.os?source=rss-a79d034ca14b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 18:34:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@msouza.os/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[LLM from scratch with Pytorch]]></title>
            <link>https://medium.com/@msouza.os/llm-from-scratch-with-pytorch-9f21808c6319?source=rss-a79d034ca14b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f21808c6319</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Matheus Oliveira De Souza]]></dc:creator>
            <pubDate>Sun, 19 May 2024 14:07:00 GMT</pubDate>
            <atom:updated>2024-07-24T20:37:48.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*vPRykSHf1nSM7W26WL_dMw.png" /><figcaption>LLM with Pytorch (Image by Author).</figcaption></figure><h3>Introduction</h3><p>Generative models are currently one of the most intriguing fields in AI, more specifically, those <em>text-to-text</em> models that generate text based on an initial user prompt. One famous example is <strong>ChatGPT</strong> by <strong>OpenAI</strong>, which is an <a href="https://arxiv.org/pdf/2203.02155.pdf">Assistant</a> model capable to respond user questions about multiple topics.</p><p>In this paper, we cover LLM, how it works and how to train it from scratch. I’ll try to be clear in all topics of this paper, and I hope most of you could understand and learn something from it 😁.</p><p>If you are going to run all of the code examples, make sure that you have imported the libraries first.</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F</pre><h3>What is a LLM?</h3><p>You might be thinking that LLM are simply models that generate human-like text or something like that, right? Well, you are correctly, actually. In essence, LLM is a Transformer-based model trained on vast text datasets. It learns to understand the meaning of words and text, enabling it to generate human-like text. In practice, LLM functions as a text completion model, attempting to predict the next <em>token</em> in a sequence based on probabilities. Given a sequence of N tokens, what might the next token be?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*P9f389f2rJP6-u8Xuq7weQ.png" /><figcaption>Token classification given a context (Image by Author).</figcaption></figure><h3>Tokenization</h3><p>Before feed into our model some text data, preprocessing is necessary. As you may know, computers can only understand numbers, not raw text like humans do. Therefore, we need to convert our text into a numeric representation.</p><p>A Tokenizer is an algorithm that split raw text into a sequence of words, commonly referred as <em>tokens.</em> Each word will be feed to the model vocabulary which store all words that our model knows.</p><p>For each token stored in the model vocabulary, it will receives an integer representation referred to that token. As a result, each word will then be converted to an integer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*wxywmFV85YBmrpKpDss0WA.png" /><figcaption>Text tokenization (Image by Author).</figcaption></figure><p>There isn’t a strict rule to follow when building your own Tokenizer. There are several techniques for text tokenization. We can tokenize these text in character level, so each character is tokenized separately. We can also tokenize them in word level, splitting our text and retrieve sequences of characters that have some meaning. Keep in mind that your tokenization approach will impact your model’s performance during training. This is because the way you tokenize your text determines how your model will interpret it. So a bad tokenization technique will reflect in a bad understanding of text.</p><p>Instead of building your own tokenizer, you can use libraries to perform this task for you if you don’t want to spend too much time on this step. Two most famous libraries are <a href="https://github.com/openai/tiktoken"><strong>TikToken</strong></a> by OpenAI and <a href="https://github.com/google/sentencepiece"><strong>SentencePiece</strong></a> by Google. You can check their repositories on GitHub for more details.</p><p>A simple tokenizer that tokenizes in character level can be built in the following code below:</p><pre>class Tokenizer:<br><br>    @staticmethod<br>    def create_vocab(dataset):<br>        &quot;&quot;&quot;<br>        Create a vocabulary from a dataset.<br><br>        Args:<br>            dataset (str): Text dataset to be used to create the character vocab.<br><br>        Returns:<br>            Dict[str, int]: Character vocabulary.<br>        &quot;&quot;&quot;<br>        vocab = {<br>            token: index<br>            for index, token in enumerate(sorted(list(set(dataset))))<br>        }<br><br>        # Adding unknown token<br>        vocab[&quot;&lt;unk&gt;&quot;] = len(vocab)<br><br>        return vocab<br><br>    def __init__(self, vocab):<br>        &quot;&quot;&quot;<br>        Initialize the tokenizer.<br><br>        Args:<br>            vocab (Dict[str, int]): Vocabulary.<br>        &quot;&quot;&quot;<br>        self.vocab_encode = {str(k): int(v) for k, v in vocab.items()}<br>        self.vocab_decode = {v: k for k, v in self.vocab_encode.items()}<br><br>    def encode(self, text):<br>        &quot;&quot;&quot;<br>        Encode a text in level character.<br><br>        Args:<br>            text (str): Input text to be encoded.<br><br>        Returns:<br>            List[int]: List with token indices.<br>        &quot;&quot;&quot;<br>        return [self.vocab_encode.get(char, self.vocab_encode[&quot;&lt;unk&gt;&quot;]) for char in text]<br><br>    def decode(self, indices):<br>        &quot;&quot;&quot;<br>        Decode a list of token indices.<br><br>        Args:<br>            indices (List[int]): List of token indices.<br><br>        Returns:<br>            str: The decoded text.<br>        &quot;&quot;&quot;<br>        return &quot;&quot;.join([self.vocab_decode.get(idx, &quot;&lt;unk&gt;&quot;) for idx in indices])</pre><h3>Embedding</h3><p>While we have numeric representations of words and characters in our text, we cannot yet feed them directly into the neural network. Despite computers being able to ‘read’ and ‘understand’ our text, static numbers are not sufficient for capturing their true meanings. Let’s analyze the following words:</p><blockquote>Woman , Fruit , Vehicle, Car , Animal</blockquote><p>These words are different among them, but if we try to see their relationship or similarity in a spacial visualization, we’ll probably see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*T_bxNmQHqVWU7yW2xGiwjg.png" /><figcaption>Word distribution based on their relationship and similarities (Image by Author).</figcaption></figure><p>We can imagine that most of those words are completely different, but <em>Car</em> and <em>Vehicle</em> are quiet similar, because, well.. car is a vehicle. This is why they are near each other. The rest of the words are spreed over the entire space because they don’t have any similarity among them.</p><p>However, this is how we perceive those words. Now, imagine trying to explain this concept to a computer, which only sees a single number for each word. It’s likely impossible for computers to comprehend this task with only a single numeric representation for each word. Hence, we need an alternative representation that can capture the meanings of words more effectively. So here is where the Embedding layers are useful.</p><p>Embedding are vector representations for our tokens, formed from learnable parameters that are adjusted during training to improve the word representation. But how do we convert a number into a vector? Imagine the Embedding layer as a <strong>lookup table</strong> with rows and columns. The rows correspond to the vocabulary size of our model, encompassing all possible tokens that our models could predict during generation. The columns refers to the embedding (vector) size of each token.</p><p>For example, consider the word “person” in our dataset. After tokenization, we got the number “153” to this word. This number will be used as a row-index to our lookup table. When we find the row related to that index, we’ll extract the vector stored there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*ZI-O4-vJZfycVWubAf7egg.png" /><figcaption>Simple illustration of a lookup table of Embedding layer (Image by Author).</figcaption></figure><p>Here, we have a Embedding layer with N rows, each row correspond to a vector representation of a numeric token generated by Tokenizer. The size of each vector can be determined by us. Large vectors can learn and capture more details about words in our dataset, but it is more expensive computationally. On the other hand, small vectors is more cheap to be computed, but for large and complex dataset with a large vocabulary it might perform bad during training. Moreover, our model probably won’t capture important details about the data. The “perfect” size of an Embedding layer will be different for each dataset.</p><p>The interesting thing about Embedding layers is that they’ll learn how to represent those words in a continuous vector space based on the text feed into our neural network. After that, our model can understand the meaning of words in our text. Back to our previous example about the word similarity, if we try to compare two trained vectors, we can use a distance metric to compute how similar each vector is to the other! Normally, the <em>cosine distance</em> is used to solve this problem.</p><h3>Transformers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*PCPPVL4zVCNd-49NmZ8bZg.png" /><figcaption>Transformer architecture.</figcaption></figure><p>As I said before, LLM is a <a href="https://proceedings.neurips.cc/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf"><strong>Transformer</strong></a> based model. This architecture has been built initially to solve language translation problems. It is composed by a <em>Encoder</em> and <em>Decoder</em> block that utilizes an attention mechanism called <em>Scaled Dot-Product Attention</em> that computes the relationship between tokens in a context.</p><p>The Encoder and Decoder block work completely different. Briefly, the Encoder block tries to analyze each word considering the entire text context. On the other hand, the Decoder block mask all future words at <em>t</em> position and uses only the previous words available to analyze the current one. The main block of the entire Transformer that we’ll focus on is the Attention mechanism, called <em>Multi-Head Attention. </em>It is the main key of the entire LLM architecture that we’ll build soon. But first, let’s prepare our data and make it ready to be feed to our model.</p><p>Consider the sentence: <em>“Hi! My name is Matheus.”.</em> First of all, we need to tokenize this text into numeric presentation. To do so, we will need to split the text into a list of words like that:</p><blockquote>[“Hi”, “!”, “ My”, “ name”, “ is”, “ Mat”, “he”, “us”, “.”]</blockquote><p>Well, you might be thinking “why did he split the text that way?”. I just used the <em>cl100k_base</em> tokenizer from <a href="https://tiktokenizer.vercel.app/?model=gpt-4-1106-preview"><strong>TikTokenizer</strong></a> website. After that, we need to convert those strings into a number. The <em>cl100k_base</em> gave to me these tokens:</p><blockquote>[13347, 0, 3092, 836, 374, 7011, 383, 355, 13]</blockquote><p>Each token will be used as an index to our Embedding layer. Let’s assume that the vector representation of our Embedding has 5 parameters only. So, for each number, we’ll replace it by a vector of size 5.</p><blockquote>[[0.5488135 0.71518937 0.60276338 0.54488318 0.4236548 ]<br> [0.64589411 0.43758721 0.891773 0.96366276 0.38344152]<br> [0.79172504 0.52889492 0.56804456 0.92559664 0.07103606]<br> [0.0871293 0.0202184 0.83261985 0.77815675 0.87001215]<br> [0.97861834 0.79915856 0.46147936 0.78052918 0.11827443]<br> [0.63992102 0.14335329 0.94466892 0.52184832 0.41466194]<br> [0.26455561 0.77423369 0.45615033 0.56843395 0.0187898 ]<br> [0.6176355 0.61209572 0.616934 0.94374808 0.6818203 ]<br> [0.3595079 0.43703195 0.6976312 0.06022547 0.66676672]]</blockquote><p>Here we have a vector of size (9,5) where 9 refers to each token in our list above while 5 is the size of the Embedding. This will be the input data to our attention mechanism.</p><h4>Attention mechanism</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*qrGVA8m-XwIp_Fry6dt9Zg.png" /><figcaption>Attention mechanism diagram</figcaption></figure><p>The Attention mechanism is referring to the <em>Scaled Dot-Product Attention.</em> As you can see, we have three data that is used as input to this block, and we call them Query, Key and Value. In our problem that involves text generation, it comes from the same source. We’ll see in practice what they are.</p><p>Each Q, K and V is computed by a linear transformation from our embedded text. Let’s ignore the second block called <em>Multi-Head Attention</em> for now and focus only to first one. We’ll feed our attention block with our embedded text for each linear layer of Query, Key and Value. In this example, each layer will receive a vector of size (9,5) and produce a new vector of size (9,5) as well. So now we have three new representation of our data.</p><p>The first operation we’ll perform is the matrix multiplication between Query and Key. You might be asking “what is Query and Key?”. Roughly speaking, Query is the information you’re trying to looking for and Key is where you will find this information. Imagine you are in a library store and you’re looking for a specific book: this is our Query. The book you’re looking for might be stored in a bookcase: this would be our Key in this context.</p><p>Here, we’re trying to find the relationship among all tokens in our context text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*rSu4nqEITOWN3ANe0sRxlA.png" /><figcaption>Token relationship in a context (Image by Author).</figcaption></figure><p>Both Query and Key are (9,5) vectors. During matrix multiplication, we multiply the columns of one matrix by the rows of another. So we need to make sure that the columns of Query match to the rows of Key. To do this, we need to transpose the Key matrix first, and then, multiply by Query.</p><blockquote><strong>Q = (9,5)</strong></blockquote><blockquote><strong>K = (9,5)</strong></blockquote><blockquote><strong>QK = Q * K.t = (9,9)</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*Dq5yB3rKGqjiwF9fBMDWKA.png" /><figcaption>Attention matrix by Query and Key multiplication (Image by Author).</figcaption></figure><h4>Scaling attention</h4><p>After computing the relationship among tokens, we feed them into a Softmax function that normalizes all values in rows to 0 and 1, where the sum of each row results in 1. But, before this, we need to scale them dividing by <em>sqrt(emb_dim)</em>, where <em>emb_dim</em> is 9 in our example, to avoid extremely values to be passed to Softmax, that occasionally causes <a href="https://en.wikipedia.org/wiki/One-hot"><strong>one-hot</strong></a> vectors. Does that make any sense? Let me show an example.</p><p>Imagine we have a (1,25) tensor with these numbers:</p><blockquote>[[ 1.76405235 0.40015721 0.97873798 2.2408932 1.86755799 -0.97727788<br> 0.95008842 -0.15135721 -0.10321885 0.4105985 0.14404357 1.45427351<br> 0.76103773 0.12167502 0.44386323 0.33367433 1.49407907 -0.20515826<br> 0.3130677 -0.85409574 -2.55298982 0.6536186 0.8644362 -0.74216502<br> 2.26975462]]</blockquote><p>This tensor has a normal distribution, that means that the variance of this distribution is close to 1 and the mean is close to 0 <em>(actually, we need to increase the number of values to see this mean and variance better)</em>, let’s imagine that this tensor is the result of our <strong><em>Q * K.t</em></strong> multiplication. When we apply Softmax, the result of this tensor is:</p><blockquote>[[0.08930983 0.02283322 0.04072317 0.14387608 0.09904925 0.0057591<br> 0.03957302 0.01315369 0.01380237 0.02307288 0.01767414 0.06551851<br> 0.03275635 0.01728319 0.0238533 0.02136456 0.06817911 0.0124647<br> 0.02092881 0.00651406 0.00119133 0.02942009 0.03632461 0.00728556<br> 0.14808906]]</blockquote><p>You can see that the highest number <em>(2.26975462)</em> after the Softmax transformation was converted to 0.14808906 and the lowest number <em>(-2.55298982)</em> became 0.00119133, if you try to sum up all these numbers you will see that it results exactly in one. Now, let’s scale those values by 10 and imagine that our <strong><em>Q * K.t</em></strong> multiplication returned to us this scaled tensor, let’s apply Softmax again and see it results.</p><blockquote>[[3.58702875e-03 4.27970206e-09 1.39366347e-06 4.22307087e-01<br> 1.00984369e-02 4.45952862e-15 1.04648843e-06 1.72272857e-11<br> 2.78791214e-11 4.75072069e-09 3.30465511e-10 1.61950560e-04<br> 1.58014778e-07 2.64229159e-10 6.62561792e-09 2.20131429e-09<br> 2.41132545e-04 1.00591629e-11 1.79138368e-09 1.52848857e-14<br> 6.39821702e-22 5.39737202e-08 4.44376999e-07 4.68135020e-14<br> 5.63601247e-01]]</blockquote><p>Well, as you can see, our well distributed probabilities disappeared now, low values became lower and the highest one became even higher, if we continue increase this scale the highest value will be approximately one whereas the rest of those probabilities will become closer to zero. To avoid this situation, one approach used by <strong>Transformer’s Authors</strong> is to divide the <strong><em>Q * K.t</em></strong> result by the squared root of the embedding dimension, and in this example, the embedding dimension is 25. The reason for do it is because we unsure that our data distribution computed by Queries and Keys will have a variance approximately to one, which avoids the one-hot problem.</p><blockquote><strong>emb_dim = 25</strong></blockquote><blockquote><strong>attention = (Q * K.t) / sqrt(emb_dim)</strong></blockquote><p>Well, back to our example above, we have a (9,5) tensor referent to our text <em>“Hi! My name is Matheus.”.</em> We compute the attention matrix multiplying Query and Key, scale it by 5 <em>(embedding size of our tensor) </em>and then we use it to multiply by Value. It’s the vector representation of the information we were looking for.</p><blockquote><strong>V = (9,5)</strong></blockquote><blockquote><strong>attention = (9,9)</strong></blockquote><blockquote><strong>Out = attention * V = (9,5)</strong></blockquote><h4>Attention Mask</h4><p>Back to our image above that shows the attention matrix of our text <em>“Hi! My name is Matheus.”</em>, we can see that we computed the attention for all tokens. This is an interesting thing about the <em>Attention Mechanism</em> of Transformers because, actually, we are trying to predict every single token in our sequence and not only the last one. So our LLM can predicts with a high confidence the next token of a sequence even if it has less context than the expected.</p><p>But, during the training stage of a LLM, we want to predict the next token given a sequence of tokens as context. To do so, we need to consider just the previous token to predict the next one, right? Well, here’s a problem, because we are not doing it, but only considering the entire text during the final stage of <em>Attention Mechanism</em>, in other words. The entire attention matrix is being used to compute the new representation of our data by <em>attention * V</em>. To solve this problem, we need to hide all consecutive tokens of all samples. We do it just by using a triangular mask and apply it over our attention matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*02UQ-5wbbl9LudEmBOMWPA.png" /><figcaption>Attention masking (Image by Author).</figcaption></figure><p>Let’s implement our <em>Attention Mechanism</em> in <strong>Pytorch</strong> and see it in practice! You can run this block of code on <a href="https://colab.research.google.com/"><strong>Google Colab</strong></a><strong> </strong>if you want to.</p><pre># setting fix seed<br>torch.random.manual_seed(seed=1234)<br><br># data<br>text = &quot;Hi! My name is Matheus.&quot;<br>tokens = [13347, 0, 3092, 836, 374, 7011, 383, 355, 13] # [&quot;Hi&quot;, &quot;!&quot;, &quot; My&quot;, &quot; name&quot;, &quot; is&quot;, &quot; Mat&quot;, &quot;he&quot;, &quot;us&quot;, &quot;.&quot;]<br><br># parameters<br>vocab_size = max(tokens) + 1 # number of classes to predict<br>emb_dim = 5 # size of vector representation of each token<br>context = len(tokens) # context size of model<br><br># layers<br>embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=emb_dim)<br>query = nn.Linear(in_features=emb_dim, out_features=emb_dim, bias=False)<br>key = nn.Linear(in_features=emb_dim, out_features=emb_dim, bias=False)<br>value = nn.Linear(in_features=emb_dim, out_features=emb_dim, bias=False)<br><br># mask filter<br>ones = torch.ones(size=[context, context], dtype=torch.float)<br>mask = torch.tril(input=ones)<br><br># forward pass<br>t_tokens = torch.tensor(data=tokens).unsqueeze(dim=0) # [9] -&gt; [1,9]<br>x = embedding(t_tokens) # [1,9] -&gt; [1,9,50] embedding vectors<br><br>B, T, C = x.size()<br>Q = query(x) # [1,9,50] -&gt; [1,9,50]<br>K = key(x) # [1,9,50] -&gt; [1,9,50]<br>V = value(x) # [1,9,50] -&gt; [1,9,50]<br><br>QK = Q @ K.transpose(-2, -1) * C**-0.5 # [1,9,50] @ [1,50,9] -&gt; [1,9,9] attention matrix<br>attention = QK.masked_fill(mask[:T,:T] == 0, float(&quot;-inf&quot;)) # applying mask<br>attention = F.softmax(input=attention, dim=-1) # [1,9,9] normalizing to 0 and 1 in embedding dimension<br><br>out = attention @ V # [1,9,9] @ [1,9,50] -&gt; [1,9,50]<br><br>print(out.size()) # new data representation</pre><h4>Positional Encoding</h4><p>As all we know, the order of words in any sentence matters a lot. This is because in some cases the final meaning of text might change depending how the words are placed, especially the meaning of some words depending how it is distributed in text.</p><p>In theory, if we change the order of our token sequence, we might see a different representation to that tokens in our text, right? But if you print the <em>x</em> variable first, then, uncomment the line 11 to reverse the entire tokens sequence and print the <em>x</em> variable again, you’ll see that. Even the order of tokens has changed, its meaning is still the same. In other words, the vector representation for each token must be different if we change it orders.</p><p>Positional Encoding tries to solve this problem encoding each token position with a fixed value for each position. It can be made by embedding layer that learns how to encoding each position of our text. This encoding will be summed to our embedding representation of our text, and then, it’ll be feed to our model.</p><pre># setting fix seed<br>torch.random.manual_seed(seed=1234)<br><br># data<br># split : [&quot;Hi&quot;, &quot;!&quot;, &quot; My&quot;, &quot; name&quot;, &quot; is&quot;, &quot; Matheus&quot;, &quot;.&quot;]<br>text = &quot;Hi! My name is Matheus.&quot;<br>tokens = [13347, 0, 3092, 836, 374, 7011, 383, 355, 13]<br><br># parameters<br>vocab_size = max(tokens) + 1 # number of classes to predict<br>emb_dim = 5 # size of vector representation of each token<br>context = len(tokens) # context size of model<br><br># layers<br>pe = nn.Embedding(num_embeddings=context, embedding_dim=emb_dim) # learnable positional encoding<br>embedding = nn.Embedding(num_embeddings=vocab_size, embedding_dim=emb_dim)<br>query = nn.Linear(in_features=emb_dim, out_features=emb_dim, bias=False)<br>key = nn.Linear(in_features=emb_dim, out_features=emb_dim, bias=False)<br>value = nn.Linear(in_features=emb_dim, out_features=emb_dim, bias=False)<br><br># mask filter<br>ones = torch.ones(size=[context, context], dtype=torch.float)<br>mask = torch.tril(input=ones)<br><br># token indices<br>indices = torch.arange(context, dtype=torch.long)<br><br># forward pass<br>t_tokens = torch.tensor(data=tokens).unsqueeze(dim=0) # [9] -&gt; [1,9]<br>x = embedding(t_tokens) # [1,9] -&gt; [1,9,50] embedding vectors<br>x = pe(indices) + x # [1,9,50] + [1,9,50] -&gt; [1,9,50] positional encoding<br><br>B, T, C = x.size()<br>Q = query(x) # [1,9,50] -&gt; [1,9,50]<br>K = key(x) # [1,9,50] -&gt; [1,9,50]<br>V = value(x) # [1,9,50] -&gt; [1,9,50]<br><br>QK = Q @ K.transpose(-2, -1) * C**-0.5 # [1,9,50] @ [1,50,9] -&gt; [1,9,9] attention matrix<br>attention = QK.masked_fill(mask[:T,:T] == 0, float(&quot;-inf&quot;)) # applying mask<br>attention = F.softmax(input=attention, dim=-1) # [1,9,9] normalizing to 0 and 1 in column dimension<br><br>out = attention @ V # [1,9,9] @ [1,9,50] -&gt; [1,9,50]<br><br>print(out.size()) # new data representation</pre><p>If you try to run this code and print the x variable again, you’ll see that when we change the order of our tokens, its meaning changes as well.</p><p>Here, is the final code with both embedding layer and attention block:</p><pre>class Embedding(nn.Module):<br>    def __init__(self, vocab_size, embedding_dim):<br>        &quot;&quot;&quot;<br>        Initialize the Embedding layer with Positional Encoding.<br><br>        Args:<br>            vocab_size (int): Size of the vocabulary.<br>            embedding_dim (int): Dimensionality of the word embeddings.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.embedding = nn.Embedding(vocab_size, embedding_dim)<br>        self.pe = nn.Embedding(vocab_size, embedding_dim)<br><br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        Forward pass of the Embedding layer.<br><br>        Args:<br>            x (torch.Tensor): Input tensor of shape (batch_size, seq_len).<br><br>        Returns:<br>            torch.Tensor: Output tensor of shape (batch_size, seq_len, embedding_dim).<br>        &quot;&quot;&quot;<br>        word_emb = self.embedding(x)<br>        word_pe = self.pe(x)<br>        return word_emb + word_pe<br><br>class AttentionBlock(nn.Module):<br><br>    def __init__(self, embedding_dim, context_size):<br>        &quot;&quot;&quot;<br>        Initialize the AttentionBlock layer.<br><br>        Args:<br>            embedding_dim (int): Dimensionality of the word embeddings.<br>            context_size (int): Size of the context window.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.query = nn.Linear(embedding_dim, embedding_dim, bias=False)<br>        self.key = nn.Linear(embedding_dim, embedding_dim, bias=False)<br>        self.value = nn.Linear(embedding_dim, embedding_dim, bias=False)<br><br>        ones = torch.ones(size=[context_size, context_size], dtype=torch.float)<br>        self.register_buffer(name=&quot;mask&quot;, tensor=torch.tril(input=ones)) # Triangular matrix<br>    <br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        Forward pass of the AttentionBlock layer.<br><br>        Args:<br>            x (torch.Tensor): Input tensor of shape (batch_size, seq_len, embedding_dim).<br><br>        Returns:<br>            torch.Tensor: New embedding representation of shape (batch_size, seq_len, embedding_dim).<br>        &quot;&quot;&quot;<br>        B, T, C = x.size()<br><br>        query = self.query(x)<br>        key = self.key(x)<br>        value = self.value(x)<br><br>        qk = query @ key.transpose(-2, -1) * C**-0.5<br>        attention = qk.masked_fill(self.mask[:T,:T] == 0, float(&quot;-inf&quot;))<br>        attention = F.softmax(input=attention, dim=-1)<br><br>        out = attention @ value<br>        return out</pre><h4>Multi Head Attention</h4><p>Instead of perform a single attention block, we can perform multiple attention blocks in parallel and then concatenate their results. In practice, each Head <em>(attention block)</em> has separated learnable parameters and they will try to find different relevant information about our data simultaneously. It is important to mention that each Head will compute a chunk of the embedding fed to the attention block, and the number of Heads must be divisible by the embedding size.</p><pre>class MultiAttentionBlock(nn.Module):<br><br>    def __init__(self, embedding_dim, num_heads, context_size):<br>        &quot;&quot;&quot;<br>        Initialize the MultiAttentionBlock layer.<br><br>        Args:<br>            embedding_dim (int): Dimensionality of the word embeddings.<br>            num_heads (int): Number of attention heads.<br>            context_size (int): Size of the context window.<br>        &quot;&quot;&quot;<br>        super().__init__()<br><br>        # Checking number of heads<br>        head_dim = embedding_dim // num_heads<br>        assert head_dim * num_heads == embedding_dim, &quot;Embedding dimension must be divisible by number of heads&quot;<br><br>        self.attention = nn.ModuleList(modules=[AttentionBlock(embedding_dim, head_dim, context_size) for _ in range(num_heads)])<br>        self.linear = nn.Linear(in_features=embedding_dim, out_features=embedding_dim)<br>    <br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        Forward pass of the MultiAttentionBlock layer.<br><br>        Args:<br>            x (torch.Tensor): Input tensor of shape (batch_size, seq_len, embedding_dim).<br>        <br>        Returns:<br>            torch.Tensor: New embedding representation of shape (batch_size, seq_len, embedding_dim).<br>        &quot;&quot;&quot;<br>        out = torch.cat(tensors=[attention(x) for attention in self.attention], dim=-1)<br>        x = self.linear(x)<br>        return x</pre><p>To prevent problems like vanishing gradients, we normally apply a skip-connection after the Multi-Head-Attention block. Then, we apply a Batch normalization and feed a Fully-Connected-Neurons to help the model to process the useful information extracted from previous block before feed it again to another Attention block ahead. The Transformer diagram above shows how this workflow works.</p><pre>class FeedForward(nn.Module):<br><br>    def __init__(self, embedding_dim, ff_dim):<br>        &quot;&quot;&quot;<br>        Initialize the feed forward layer.<br><br>        Args:<br>            emb_dim (int) : The dimension of the embedding.<br>            ff_dim (int) : The dimension of the feed forward layer.<br>            dropout_rate (float) : The dropout rate. (default: 0.2)<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.linear_1 = nn.Linear(embedding_dim, ff_dim)<br>        self.relu = nn.ReLU()<br>        self.linear_2 = nn.Linear(ff_dim, embedding_dim)<br><br><br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        Forward pass of the feed forward layer.<br><br>        Args:<br>            x (torch.Tensor) : The input tensor.<br><br>        Returns:<br>            torch.Tensor : The output tensor.<br>        &quot;&quot;&quot;<br>        x = self.linear_1(x)<br>        x = self.relu(x)<br>        x = self.linear_2(x)<br>        return x<br><br>class DecoderLayer(nn.Module):<br><br>    def __init__(self, embedding_dim, head_dim, context_size, ff_dim):<br>        &quot;&quot;&quot;<br>        Initialize the decoder layer.<br><br>        Args:<br>            embedding_dim (int): Dimensionality of the word embeddings.<br>            head_dim (int): Dimensionality of each head.<br>            context_size (int): Size of the context window.<br>            ff_dim (int): Dimensionality of the feed-forward layer.<br>        &quot;&quot;&quot;<br>        super().__init__()<br>        self.attention = MultiAttentionBlock(embedding_dim, head_dim, context_size)<br>        self.feed_forward = FeedForward(embedding_dim, ff_dim)<br>        self.norm_1 = nn.LayerNorm(normalized_shape=embedding_dim)<br>        self.norm_2 = nn.LayerNorm(normalized_shape=embedding_dim)<br><br>    def forward(self, x):<br>        &quot;&quot;&quot;<br>        Forward pass of the decoder layer.<br><br>        Args:<br>            x (torch.Tensor) : The input tensor.<br><br>        Returns:<br>            torch.Tensor : The output tensor.<br>        &quot;&quot;&quot;<br>        x_norm = self.norm_1(x)<br>        attention = self.attention(x_norm)<br>        attention = attention + x<br><br>        attention_norm = self.norm_2(attention)<br>        ff = self.feed_forward(attention_norm)<br>        ff = ff + attention<br><br>        return ff</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rNUNg-5fIq2aeJDgL3867A.png" /><figcaption>Medium Article Generator project (Image by Author).</figcaption></figure><p>Recently, I trained and tested my own LLM using Pytorch. My objective was to develop a <a href="https://github.com/MTxSouza/MediumArticleGenerator"><strong>Medium Article Generator</strong></a>, a model that receives a title and generate text related to that title.</p><p>Train LLM from scratch is hard because the high computational resource. It requires a large GPU memory for training and high RAM memory to load and preprocess large dataset to train it. It is important to mention it requires hours of training because the large number of parameters to be trained and a large text dataset to be used in training.</p><p>I won’t go to full details about the development process but just explain and show important parts about the project.</p><h4>Dataset</h4><p>The dataset used was the <a href="https://www.kaggle.com/datasets/fabiochiusano/medium-articles">Medium Articles</a> from <strong>Kaggle.</strong> It is a public dataset and it has around 190 thousands articles from Medium with a title and an article related to that title. In general, I was not expecting the model to generate text related to every single topic in the world. The dataset used has a limited content about some topics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGo_WlTVi8n7LwvjjMPbrQ.png" /><figcaption>Article topics in dataset (Image by Author).</figcaption></figure><p>I excluded articles with non-utf-8 characters and some based on a length condition, which reduced the number of samples for training.</p><h4>LLM from scratch</h4><p>First, I decided to train it from scratch, training the entire neural net, even its embedding layers for word representations. My tokenize algorithm was based on a simple regex that splits the text following a pattern rule. The regex function divides sequence of characters from punctuation and numbers.</p><p>Then, my approach was to delimited title and article, telling to the model where the title and article starts and ends. After that, I added padding tokens to each article to standardize the length of the data to be feed to the model.</p><p>During data preprocessing, I stored all new tokens into a vocabulary dictionary and create an index to refers to take new token. I limited my vocabulary size to 50K~80K tokens, just to control the number of parameters required to train the embedding layer.</p><p>I used some regularization methods like Dropout layers with rate of 10% and Weight-Decay of 0.0001 to avoid my model to <em>overfitting</em>. It was trained on a RTX 4090 with 24Gb for 15 hours. I used <em>Cross-Entropy</em> loss to predict each token in each position and I used the <em>Accuracy</em> metric to evaluate the quality of my generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YI75cOnWYMNya8qprGPz3g.png" /><figcaption>Loss graph of the LLM trained from scratch (Image by Author).</figcaption></figure><p>During inference, the model could complete the text quiet well but just for a few tokens. During long generations, it started to complete the input text, but then it repeated the same sentence it predicted before infinitely.</p><h4>GPT-2 Pre-Trained Embedding + Decoder</h4><p>I experimented with using the pre-trained Embedding layer of OpenAI’s GPT-2, which contains pre-computed word representations. This reduced training time to just one hour and lowered resource requirements for training the rest of the model.</p><p>To achieve this, I used the Transformer library to load both the tokenizer and embedding from GPT-2. However, I encountered a limitation with the GPT-2 tokenizer, it only includes the <em>&lt;|endoftext|&gt;</em> special token, which solely marks the end of text. Ideally, I would have liked to specify the start of the article as well and potentially add padding to standardize article lengths.</p><p>Given this constraint, my approach with GPT-2 involved simply concatenating the title and article. I then used the <em>&lt;|endoftext|&gt;</em> token to pad the text, even though this approach of not specifying the start and end of text sections may seem unconventional. Surprisingly, it yielded positive results. While I tested other tokenizers and embeddings like <strong>BERT</strong>, <strong>T5</strong>, and <strong>RoBERTa</strong>, GPT-2 achieved the best performance and fastest training times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_Bnv_6ublEGTTem017Isg.png" /><figcaption>Loss graph of the LLM trained with GPT-2 pre-trained embedding layer (Image by Author).</figcaption></figure><blockquote>The final mode results and its text generation performance can be found in my <a href="https://github.com/MTxSouza/MediumArticleGenerator"><strong>GitHub repository</strong></a>.</blockquote><h3>Final considerations</h3><p>In this exploration, we delved into the inner workings LLM and demonstrated the process of building one from scratch. My personal project served as a practical example, showcasing the results achievable with limited hardware and a focused dataset. While achieving peak performance wasn’t possible under these constraints, the project yielded valuable insights and improvements.</p><p>The project highlighted the impact of hardware and dataset size on LLM performance. It served as a valuable learning experience, allowing me to explore the trade-offs involved in LLM development.</p><p>For those interested in further exploration, <a href="https://medium.com/u/ac9d9a35533e">Andrej Karpathy</a>’s video on building LLMs from scratch provides excellent material:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FkCc8FmEb1nY%3Fstart%3D4677%26feature%3Doembed%26start%3D4677&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DkCc8FmEb1nY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkCc8FmEb1nY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d73ef57c6a9e0e032942165eda7e558/href">https://medium.com/media/6d73ef57c6a9e0e032942165eda7e558/href</a></iframe><p>In conclusion, this exploration provided a practical introduction to LLM and the considerations involved in their development.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f21808c6319" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>