Let's build GPT: from scratch, in code, spelled out.
Introduction and Motivation
Hi everyone. So by now you have probably heard of ChatGPT. It has taken the world and the AI community by storm, and it is a system that allows you to interact with an AI and give it text-based tasks.
So, for example, we can ask ChatGPT to write us a small haiku about how important it is that people understand AI, and then they can use it to improve the world and make it more prosperous. So when we run this: "AI knowledge brings prosperity for all to see, embrace its power." Okay, not bad.
And so you could see that ChatGPT went from left to right and generated all these words sort of sequentially. Now, I asked it the exact same prompt a little bit earlier, and it generated a slightly different outcome: "AI's power to grow, ignorance holds us back, learn prosperity waits." So pretty good in both cases, and slightly different.
So you can see that ChatGPT is a probabilistic system, and for any one prompt, it can give us multiple answers. Now, this is just one example of a problem; people have come up with many, many examples, and there are entire websites that index interactions with ChatGPT. And so many of them are quite humorous: Explain HTML to me like I'm a dog, Write release notes for Chess 2, Write a note about Elon Musk buying Twitter, and so on.
So as an example, please write a breaking news article about a leaf falling from a tree: "In a shocking turn of events, a leaf has fallen from a tree in the local park. Witnesses report that the leaf, which was previously attached to a branch, detached itself and fell to the ground." Very dramatic!
So you can see that this is a pretty remarkable system, and it is what we call a language model, because it models the sequence of words, or characters, or tokens more generally, and it knows how words follow each other in the English language.
And so from its perspective, what it is doing is it is completing the sequence. I give it the start of a sequence, and it completes the sequence with the outcome. So it's a language model in that sense.
Now, I would like to focus on the under-the-hood components of what makes ChatGPT work. So what is the neural network under the hood that models the sequence of these words? And that comes from this paper called Attention Is All You Need in 2017—a landmark paper in AI that produced and proposed the Transformer architecture.
So GPT is short for Generatively Pre-trained Transformer. So the Transformer is the neural net that actually does all the heavy lifting under the hood; it comes from this paper in 2017.
Now, if you read this paper, this reads like a pretty random machine translation paper. And that's because I think the authors didn't fully anticipate the impact that the Transformer would have on the field. This architecture that they produced in the context of machine translation in their case actually ended up taking over the rest of AI in the next 5 years after.
And so this architecture, with minor changes, was copy-pasted into a huge amount of applications in AI in more recent years, and that includes the core of ChatGPT.
Now, what I'd like to do now is I'd like to build out something like ChatGPT. But we're not going to be able to, of course, reproduce ChatGPT — this is a very serious production-grade system. It is trained on a good chunk of the internet, and then there's a lot of pre-training and fine-tuning stages to it, and so it's very complicated.
What I'd like to focus on is just to train a Transformer-based language model, and in our case, it's going to be a character-level language model. I still think that is very educational with respect to how these systems work.
So I don't want to train on a chunk of the internet; we need a smaller dataset. In this case, I propose that we work with my favorite toy dataset: it's called tiny Shakespeare. And what it is, is basically a concatenation of all of the works of Shakespeare, to my understanding. So this is all of Shakespeare in a single file; this file is about 1 megabyte, and it's just all of Shakespeare.
And what we are going to do now is we're going to basically model how these characters follow each other. So, for example, given a chunk of these characters like this, given some context of characters in the past, the Transformer neural network will look at the characters that I've highlighted and is going to predict that 'g' is likely to come next in the sequence. And it's going to do that because we're going to train that Transformer on Shakespeare, and it's just going to try to produce character sequences that look like this, and in that process is going to model all the patterns inside this data.
Once we've trained the system — I'd just like to give you a preview — we can generate infinite Shakespeare. And of course, it's a fake thing that looks kind of like Shakespeare:
Apologies for there's some Jank that I'm not able to resolve in here, but you can see how this is going character by character, and it's kind of like predicting Shakespeare-like language: "Verily my Lord, the sights have left the... again the king coming with my curses with precious pale..." And then Tranio says something else, etc.
And this is just coming out of the Transformer in a very similar manner as it would come out in ChatGPT. In our case, character by character; in ChatGPT, it's coming out on the token-by-token level. And tokens are these sort of like little subword pieces, so they're not word-level, they're kind of like word-chunk-level.
Now, I've already written this entire code to train these Transformers, and it is in a GitHub repository that you can find, and it's called nanoGPT. nanoGPT is a repository that you can find in my GitHub, and it's a repository for training Transformers on any given text. And what I think is interesting about it — because there's many ways to train Transformers — is this is a very simple implementation: it's just two files of 300 lines of code each.
One file defines the GPT model (the Transformer), and one file trains it on some given text dataset. And here I'm showing that if you train it on an open web text dataset, which is a fairly large dataset of web pages, then I reproduce the performance of GPT-2. So GPT-2 is an early version of OpenAI's GPT from 2019, if I recall correctly. And I've only so far reproduced the smallest 124-million parameter model, but basically this is just proving that the codebase is correctly arranged, and I'm able to load the neural network weights that OpenAI has released later.
So you can take a look at the finished code here in nanoGPT. But what I would like to do in this lecture is I would like to basically write this repository from scratch. So we're going to begin with an empty file, and we're going to define a Transformer piece by piece. We're going to train it on the tiny Shakespeare dataset, and we'll see how we can then generate infinite Shakespeare.
And of course, this can copy-paste to any arbitrary text dataset that you like, but my goal really here is to just make you understand and appreciate how under the hood ChatGPT works. And really all that's required is a proficiency in Python and some basic understanding of calculus and statistics. And it would help if you also saw my previous videos on the same YouTube channel, in particular my Make More series, where I define smaller and...
simpler neural network language models, uh, multi-perceptrons and so on. It really introduces the language modeling framework, and then, uh, here in this video, we're going to focus on the Transformer neural network itself.
Okay, so I created a new Google Colab Jupyter notebook here, and this will allow me to easily share this code that we're going to develop together with you so you can follow along. This will be in the video description later.
Now here, I've just
done some preliminaries. I downloaded the dataset, the tiny Shakespeare dataset, at this URL, and you can see that it's about a 1-megabyte file. Then here, I open the input.txt file and just read in all
Data Preparation and Tokenization
the text of the string, and we see that we are working with 1 million characters roughly. The first 1,000 characters, if we just print them out, are basically what you would expect. This is the first 1,000 characters of the tiny Shakespeare dataset, roughly up to here. So far so good.
Next, we're going to take this text— and the text is a sequence of characters in Python—so when I call the set constructor on it, I'm just going to get the set of all the characters that occur in this text, and then I call list on that to create a list of those characters instead of just a set, so that I have an ordering, an arbitrary ordering, and then I sort that. So basically, we get just all the characters that occur in the entire dataset, and they're sorted. Now, the number of them is going to be our vocabulary size. These are the possible elements of our sequences, and we see that when I print the characters here, there's 65 of them in total: there's a space character, then all kinds of special characters, and then capitals and lowercase letters. So that's our vocabulary, and that's the sort of possible characters that the model can see or emit.
Okay, so next, we would like to develop some strategy to tokenize the input text. Now, when people say tokenize, they mean convert the raw text as a string to some sequence of integers according to some vocabulary of possible elements. As an example, here we are going to be building a character-level language model, so we're simply going to be translating individual characters into integers.
So let me show you a chunk of code that sort of does that for us. We're building both the encoder and the decoder, and let me just talk through what's happening here. When we encode an arbitrary text like "hi there", we're going to receive a list of integers that represents that string—for example, [46, 47], etc. And then we also have the reverse mapping, so we can take this list and decode it to get back the exact same string. So it's really just like a translation to integers and back for an arbitrary string, and for us, it is done on a character level.
Now, the way this was achieved is we just iterate over all the characters here and create a lookup table from the character to the integer and vice versa. Then, to encode some string, we simply translate all the characters individually, and to decode it back, we use the reverse mapping and concatenate all of it.
Now, this is only one of many possible encodings or many possible tokenizers, and it's a very simple one, but there's many other schemas that people have come up with in practice. For example, Google uses SentencePiece. SentencePiece will also encode text into integers, but in a different schema and using a different vocabulary. SentencePiece is a subword-level tokenizer, and what that means is that you're not encoding entire words, but you're not also encoding individual characters; it's a subword-unit level, and that's usually what's adopted in practice.
For example, also OpenAI has this library called tiktoken that uses a byte-pair encoding tokenizer, and that's what GPT uses. You can also just encode words—like "Hello World"—into a list of integers. As an example, I'm using the tiktoken library here, getting the encoding for gpt2. Instead of just having 65 possible characters or tokens, they have 50,000 tokens, and so when they encode the exact same string "hi there", we only get a list of three integers. But those integers are not between 0 and 64; they are between 0 and 50,256.
Basically, you can trade off the codebook size and the sequence lengths. You can have very long sequences of integers with very small vocabularies, or we can have short sequences of integers with very large vocabularies. Typically, people use these subword encodings in practice, but I'd like to keep our tokenizer very simple. So we're using a character-level tokenizer, and that means that we have very small codebooks, we have very simple encode and decode functions, but we do get very long sequences as a result. That's the level we're going to stick with for this lecture because it's the simplest thing.
Okay, so now that we have an encoder and a decoder—effectively a tokenizer—we can tokenize the entire training set of Shakespeare. Here's a chunk of code that does that, and I'm going to start to use the PyTorch library, and specifically torch.tensor from PyTorch. We're going to take all of the text in tiny Shakespeare, encode it, and then wrap it into a torch.tensor to get the data tensor.
Here's what the data tensor looks like when I look at just the first 1,000 characters or elements of it. We see that we have a massive sequence of integers, and this sequence of integers here is basically an identical translation of the first 10,000 characters here. I believe, for example, that 0 is a newline character, and maybe 1 is a space—not 100% sure. But from now on, the entire dataset of text is re-represented; it's just stretched out as a single, very large sequence of integers.
Let me do one more thing before we move on here. I'd like to separate out our dataset into a train and a validation split. In particular, we're going to take the first 90% of the data set and consider that to be the training data for the Transformer, and we're going to withhold the last 10% at the end of it to be the validation data. This will help us understand to what extent our model is overfitting. We're going to basically hide and keep the validation data on the side, because we don't want just a perfect memorization of this exact Shakespeare text; we want a neural network that creates Shakespeare-like text, and so it should be fairly likely for it to produce the actual stowed-away, true Shakespeare text. We're going to use this to get a sense of the overfitting.
Okay, so now we would
like to start plugging these text sequences or integer sequences into the Transformer so that it can train and learn those patterns. Now, the important thing to realize is we're never going to actually feed entire text into a Transformer all at once. That would be computationally very expensive and prohibitive. So when we actually train a Transformer on a lot of these datasets, we only work with chunks of the dataset. When we train the Transformer, we basically sample random little chunks out of the training set and train on just chunks at a time. These chunks have some kind of length, a maximum length. Now, the maximum length typically—at least in the code I usually write—is called block size. You can find it under different names like context length or something.
Like that, let's start with the block size of just eight, and let me look at the first train data characters, the first block size plus one characters. I'll explain why plus one in a second. So this is the first nine characters in the sequence in the training set. Now, what I'd like to point out is that when you sample a chunk of data like this—so say these nine characters out of the training set—this actually has multiple examples packed into it. And that's because all of these characters follow each other. So what this thing is going to say when we plug it into a Transformer is we're going to simultaneously train it to make a prediction at every one of these positions.
Now, in a chunk of nine characters, there are actually eight individual examples packed in there. So there's the example that when 18, 47 likely comes next; in a context of 18 and 47, 56 comes next; in a context of 18, 47, 56, 57 can come next, and so on. So that's the eight individual examples. Let me actually spell it out with code.
Here's a chunk of code to illustrate:
-
xare the inputs to the Transformer, which will just be the first block size characters. -
ywill be the next block size characters, so it's offset by one, becauseyare the targets for each position in the input.
And then here I'm iterating over all the block size of eight, and the context is always all the characters in x up to T and including T, and the target is always the $t$-th character, but in the targets array y. So let me just run this, and basically it spells out what I said in words: these are the eight examples hidden in a chunk of nine characters that we sampled from the training set.
I want to mention one more thing: we train on all the eight examples here with context between 1 all the way up to a context of block size, and we train on that not just for computational reasons—because we happen to have the sequence already or something like that. It's not just done for efficiency; it's also done to make the Transformer network get used to seeing contexts all the way from as little as 1 all the way to block size. And we'd like the Transformer to be used to seeing everything in between, and that's going to be useful later during inference. Because while we're sampling, we can start the sampling generation with as little as one character of context, and the Transformer knows how to predict the next character with a context of just one. And so then it can predict everything up to block size, and after block size we have to start truncating because the Transformer will never receive more than block size inputs when it's predicting the next character.
Okay, so we've looked at the time dimension of the tensors that are going to be feeding into the Transformer. There's one more dimension to care about, and that is the batch dimension. As we're sampling these chunks of text, every time we feed them into a Transformer, we're going to have many batches of multiple chunks of text that are all stacked up in a single tensor. And that's just done for efficiency, so that we can keep the GPUs busy because they are very good at parallel processing of data. We just want to process multiple chunks all at the same time, but those chunks are processed completely independently—they don't talk to each other, and so on.
So let me basically just generalize this and introduce a batch dimension. Here's a chunk of code; let me just run it and then I'm going to explain what it does. Here, because we're going to start sampling random locations in the data set to pull chunks from, I am setting the seed in the random number generator so that the numbers I see here are going to be the same numbers you see later if you try to reproduce this. Now, the batch size here is how many independent sequences we are processing every forward/backward pass of the Transformer. The block size, as I explained, is the maximum context length to make those predictions.
So let's say batch_size = 4, block_size = 8. Here's how we get a batch for any arbitrary split: if the split is a training split, then we're going to look at train_data, otherwise at valid_data. That gives us the data array, and then when I generate random positions to grab a chunk out of, I actually generate batch-size number of random offsets. Because this is 4, ix is going to be four numbers that are randomly generated between 0 and len(data) - block_size—it's just random offsets into the training set. And then x's, as I explained, are the first block size characters starting at i. The y's are offset by one of that, so just add + 1. Then we're going to get those chunks for every one of the integers i in ix and use a torch.stack to take all those one-dimensional tensors, and we're going to stack them up as rows so they all become a row in a $4 \times 8$ tensor.
So here's where I'm printing: when I sample a batch xb and yb, the inputs to the Transformer now—the input x—is the $4 \times 8$ tensor (four rows of eight columns), and each one of these is a chunk of the training set.
The Bigram Model and Loss Function
And then the targets here are in the associated array y, and they will come into the Transformer all the way at the end to create the loss function. They will give us the correct answer for every single position inside x, and these are the four independent rows.
So spelled out as we did before, this $4 \times 8$ array contains a total of 32 examples, and they are completely independent as far as the Transformer is concerned. When the input is 24, the target is 43 (or rather, 43 here in the y array). When the input is 24, 43, the target is 58. When the input is 24, 43, 58, the target is 5, etc. So you can sort of see this spelled out: these are the 32 independent examples packed into a single batch of the input x, and then the desired targets are in y.
And so now this integer tensor of x is going to feed into the Transformer, and that Transformer is going to simultaneously process all these examples and then look up the correct integers to predict in every one of these positions in the tensor y.
Okay, so now that we have our batch of input that we'd like to feed into a Transformer, let's start basically feeding this into neural networks.
We're going to start off with the simplest possible neural network, which in the case of language modeling in my opinion is the Bigram language model. We've covered the Bigram language model in my Make More series in a lot of depth, so here I'm going to sort of go faster and let's just implement a PyTorch module directly that implements the Bigram language model.
So I'm importing the PyTorch nn module for reproducibility, and then here I'm constructing a BigramLanguageModel which is a subclass of nn.Module. And then I'm calling it, and I'm passing it the inputs and the targets, and I'm just printing. Now when the inputs and targets come here, you see that I'm just taking the inputs x here—which I rename to idx—and I'm...
just passing them into this token embedding table. So what's going on here is that here in the constructor we are creating a token embedding table, and it is of size vocab_size by vocab_size — and we're using an nn.Embedding, which is a very thin wrapper around basically a tensor of shape vocab_size by vocab_size. And what's happening here is that when we pass idx here, every single integer in our input is going to refer to this embedding table, and it's going to pluck out a row of that embedding table corresponding to its index. So 24 here will go into the embedding table and we'll pluck out the 24th row, and then 43 will go here and pluck out the 43rd row, etc.
And then PyTorch is going to arrange all of this into a Batch by Time by Channel tensor. In this case, batch is 4, time is 8, and C, which is the channels, is the vocab size, or 65. So we're just going to pluck out all those rows, arrange them in a $B \times T \times C$, and now we're going to interpret this as the logits, which are basically the scores for the next character in the sequence. And so what's happening here is we are predicting what comes next based on just the individual identity of a single token. And you can do that because, um, I mean currently the tokens are not talking to each other, and they're not seeing any context except for they're just seeing themselves. So, "I'm a file, I'm a token number five," and then I can actually make pretty decent predictions about what comes next just by knowing that I'm token five, because some characters follow other characters in typical scenarios.
We saw a lot of this in a lot more depth in the Make More series. And here, if I just run this, then we currently get the predictions, the scores, the logits for every one of the $4 \times 8$ positions.
Now that we've made predictions about what comes next, we'd like to evaluate the loss function. And so in the Make More series, we saw that a good way to measure a loss or like a quality of the predictions is to use the negative log likelihood loss, which is also implemented in PyTorch under the name cross entropy.
So what we'd like to do here is loss = F.cross_entropy on the predictions and the targets. And so this measures the quality of the logits with respect to the targets. In other words, we have the identity of the next character, so how well are we predicting the next character based on the logits? Intuitively, the correct dimension of logits corresponding to whatever the target is should have a very high number, and all the other dimensions should be a very low number.
Right now, the issue is that this won't actually... this is what we want, we want to basically output the logits and the loss, this is what we want, but unfortunately this won't actually run; we get an error message. But intuitively, we want to measure this.
When we go to the PyTorch cross entropy documentation here, we're trying to call the cross entropy in its functional form, so that means we don't have to create like a module for it. But here, when we go to the documentation, you have to look into the details of how PyTorch expects these inputs. Basically the issue here is PyTorch expects, if you have multi-dimensional input — which we do, because we have a $B \times T \times C$ tensor — then it actually really wants the channels to be the second dimension here. So, basically it wants a $B \times C \times T$ instead of a $B \times T \times C$. And so it's just the details of how PyTorch treats these kinds of inputs.
So we don't actually want to deal with that, and what we're going to do instead is we need to basically reshape our logits. Here's what I like to do: I like to take basically give names to the dimensions, so logits.shape is $B \times T \times C$, and unpack those numbers. And then let's say that logits = logits.view and we want it to be a $(B \times T) \times C$, so just a two-dimensional array, right?
So we're going to take all of these positions here and we're going to stretch them out into a one-dimensional sequence and preserve the channel dimension as the second dimension. So we're just kind of like stretching out the array so it's two- dimensional, and in that case it's going to better conform to what PyTorch expects in its dimensions.
Now we have to do the same to targets, because currently targets are of shape $B \times T$, and we want it to be just $B \times T$ (onedimensional). Now alternatively, you could always still just do -1 because PyTorch will guess what this should be if you want to lay it out, but let me just be explicit and say B * T. Once we've reshaped this, it will match the cross entropy case, and then we should be able to evaluate our loss.
Okay, let's run that now, and we can check the loss. So currently we see that the loss is 4.87. Now because our vocabulary has 65 possible elements, we can actually guess at what the loss should be. In particular, as we covered with negative log likelihood in a lot of detail, we are expecting $\log$ or $\ln$ of $1 / 65$, and the negative of that — so we're expecting the loss to be about 4.17. But we're getting 4.87, and so that's telling us that the initial predictions are not super diffuse; they've got a little bit of entropy and so we're guessing wrong. But yes, we are able to evaluate the loss okay.
Now that we can evaluate the quality of the model on some data, we'd like to also be able to generate from the model. So let's do the generation now. I'm going to go again a little bit faster here because I covered all this already in previous videos.
So here's a generate function for the model. We take some... we take the same kind of input idx here, and basically this is the current context of some characters in a batch — so it's also $B \times T$. And the job of generate is to basically take this $B \times T$ and extend it to be $B \times (T + 1)$, $T + 2$, $T + 3$. So it just basically continues the generation in all the batch dimensions and the time dimension. So that's its job, and it will do that for max_new_tokens.
You can see here on the bottom, whatever is predicted is concatenated on top of the previous idx along the first dimension (which is the time dimension) to create a $B \times (T + 1)$, so that becomes a new idx. So the job of generate is to take a $B \times T$ and make it $B \times (T + 1)$, $T + 2$, $T + 3$, however many we want (max_new_tokens). This is the generation from the model.
Now inside the generation, what are we doing? We're taking the current indices, we're getting the predictions — so we get those in the logits, and then the loss here is going to be ignored because we're not using that and we have no ground truth targets that we're going to be comparing with. Then once we get the logits, we are only focusing on the last step. So instead of a $B \times T \times C$, we're going to pluck out the -1 (the last element in the time dimension), because those are the predictions for what comes next. That gives us the logits, which we then convert to probabilities via softmax, and then we use torch.multinomial to sample from those probabilities. We ask PyTorch to give us one sample, and so idx_next will become a $B \times 1$, because in each one of the batch dimensions we're going to have a single prediction for what comes next. This num_samples = 1 will make this be a 1, and then we're going to take those integers that come from the sampling process according to the probability.
distribution given here, and those integers got just concatenated on top of the current sort of running stream of integers, and this gives us $B \times T + 1$. Then we can return that. Now, one thing here is you see how I'm calling self of idx, which will end up going to the forward function? I'm not providing any targets. So currently, this would give an error because targets is sort of not given. So targets has to be optional. So targets is none by default. And then if targets is none, then there's no loss to create. So it's just loss is none. But else, all of this happens and we can create a loss. This will make it so if we have the targets, we provide them and get a loss; if we have no targets, we'll just get the logits. So this here will generate from the model, and let's take that for a ride now.
Oops. So I have another code chunk here which will generate from the model. Okay, this is kind of crazy, so maybe let me break this down. These are the idx, right? I'm creating a batch, the size will be just one. So I'm creating a little $1 \times 1$ tensor, and it's holding a zero. And the data type is integer. So zero is going to be how we kick off the generation. And remember that zero is the element standing for a newline character. So it's kind of like a reasonable thing to feed in as the very first character in a sequence to be the newline. So it's going to be idx, which we're going to feed in here. Then we're going to ask for $100$ tokens, and then.generate() will continue that. Now, because.generate() works on the level of batches, we then have to index into the zero-th row to basically unplug the single batch dimension that exists. And that gives us a time step, just a one-dimensional array of all the indices, which we will convert to a simple Python list from a PyTorch tensor, so that that can feed into our decode function and convert those integers into text.
So let me bring this back. We're generating $100$ tokens. Let's run it. And here's the generation that we achieved. So obviously, it's garbage. And the reason it's garbage is because this is a totally random model. So next up, we're going to want to train this model. Now, one more thing I wanted to point out here is this function is written to be general, but it's kind of like ridiculous right now because we're feeding in all this, we're building out this context, and we're concatenating it all, and we're always feeding it all into the model. But that's kind of ridiculous because this is just a simple bigram model. So to make, for example, this prediction about $k$, we only needed this $w$. But actually, what we fed into the model is we fed the entire sequence, and then we only looked at the very last piece and predicted $k$. The only reason I'm writing it in this way is because right now this is a bigram model, but I'd like to keep this function fixed, and I'd like it to work later when our characters actually basically look further in the history. Right now the history is not used, so this looks silly, but eventually the history will be used, and so that's why we want to do it this way. So just a quick comment on that.
Now we see that this is random. So let's train the model so it becomes a bit less random. Okay, let's now train the model. First, what I'm going to do is I'm going to create a PyTorch optimization object. So here we are using the optimizer AdamW. Now, in the MakeMore series, we've only ever used Stochastic Gradient Descent, the simplest possible optimizer, which you can get using optim.SGD instead. But I want to use Adam, which is a much more advanced and popular optimizer. It works extremely well. A typical good setting for the learning rate is roughly $3 \times 10^{-4}$, but for very, very small networks like is the case here, you can get away with much, much higher learning rates, like $1e^{-3}$ or even higher probably. Let me create the optimizer object, which will basically take the gradients and update the parameters using the gradients.
And then here, our batch size up above was only four. So let me actually use something bigger, let's say $32$. And then for some number of steps, we are sampling a new batch of data, evaluating the loss, zeroing out all the gradients from the previous step, getting the gradients for all the parameters, and then using those gradients to update our parameters. A typical training loop, as we saw in the MakeMore series. So let me now run this for, say, $100$ iterations, and let's see what kind of losses we're going to get. So we started around $4.7$, and now we're getting down to like $4.6$, $4.5$, etc. So the optimization is definitely happening.
But let's sort of try to increase the number of iterations and only print at the end, because we probably want to train for longer. Okay, so we're down to $3.6$ roughly... roughly down to $3$. This is the most janky optimization. Okay, it's working. Let's just do $10,000$. And then from here, we want to copy this and hopefully that we're going to get something reasonable. Of course, it's not going to be Shakespeare from a bigram model, but at least we see that the loss is improving, and hopefully we're expecting something a bit more reasonable. Okay, so we're down at about $2.5$-ish. Let's see what we get. Okay! Dramatic improvements, certainly on what we had here. So let me just increase the number of tokens. Okay, we see that we're starting to get something at least like reasonable-ish. Certainly not Shakespeare, but the model is making progress. So that is the simplest possible model.
Now, what I'd like to do is... obviously this is a very simple model, because the tokens are not talking to each other. Given the previous context of whatever was generated, we're only looking at the very last character to make the predictions about what comes next.
Implementing Self-Attention
So now these tokens have to start talking to each other and figuring out what is in the context so that they can make better predictions for what comes next. And this is how we're going to kick off the Transformer.
Okay, next, I took the code that we developed in this Jupyter notebook and I converted it to be a script. And I'm doing this because I just want to simplify our intermediate work into just the final product that we have at this point. In the top here, I put all the hyperparameters that we defined—I introduced a few, and I'm going to speak to that in a little bit. Otherwise, a lot of this should be recognizable: reproducibility, read data, get the encoder and the decoder, create the train/test splits, use the kind of like data loader that gets a batch of the inputs and targets (this is new and I'll talk about it in a second). Now, this is the bigram language model that we developed, and it can forward and give us the logits and loss, and it can generate. And then here we are creating the optimizer, and this is the training loop. So everything here should look pretty familiar.
Now, some of the small things that I added:
- Number one, I added the ability to run on a GPU if you have it. So if you have a GPU, then this will use CUDA instead of just CPU, and everything will be a lot faster. Now, when device becomes cuda, then we need to make sure that when we load the data, we move it to the device; when we create the model, we want to move the model parameters to the device. As an example here, we have the nn.Embedding table, and it's got...
weight inside it which stores the sort of lookup table. So that would be moved to the GPU so that all the calculations here happen on the GPU, and they can be a lot faster. And then finally here, when I'm creating the context that feeds in to generate, I have to make sure that I create it on device. Number two, what I introduced is the fact that here in the training loop, I was just printing the loss.item() inside the training loop. But this is a very noisy measurement of the current loss, because every batch will be more or less lucky. And so what I want to do usually, I have an estimate loss function, and the estimate loss basically then averages up the loss over multiple batches. So in particular, we're going to iterate eval_iters times, and we're going to basically get our loss, and then we're going to get the average loss for both splits. And so this will be a lot less noisy. So here when we call the estimate_loss, we're going to report the pretty accurate train and validation loss.
Now when we come back up, you'll notice a few things. Here I'm setting the model to evaluation phase, and down here I'm resetting it back to training phase. Now right now, for our model as is, this doesn't actually do anything, because the only thing inside this model is this nn.Embedding, and this network would behave the same in both evaluation mode and training mode. We have no dropout layers, we have no batchnorm layers, etc. But it is a good practice to think through what mode your neural network is in, [40:4] because some layers will have different behavior at inference time or training time.
And there's also this context manager torch.no_grad(), and this is just telling PyTorch that everything that happens inside this function, we will not call.backward() on. And so PyTorch can be a lot more efficient with its memory use because it doesn't have to store all the intermediate variables, since we're never going to call backward. And so it can be a lot more memory efficient in that way. So it's also a good practice to tell PyTorch when we don't intend to do backpropagation.
So right now this script is about 120 lines of code, and that's kind of our starter code. I'm calling it bigram.py, and I'm going to release it later. Now running this script gives us output in the terminal, and it looks something like this. As I ran this code, it was giving me the train loss and val loss, and we see that we converge to somewhere around 2.5 with the bigram model. [40:4] And then here's the sample that we produced at the end. [40:7] And so we have everything packaged up in the script, [40:9] and we're in a good position now to iterate on this.
Okay, so we are almost ready to start writing our very first self-attention block for processing these tokens. Now before we actually get there, I want to get you used to a mathematical trick that is used in self-attention inside a Transformer, and is really at the heart of an efficient implementation of self-attention. And so I want to work with this toy example to just get you used to this operation, and then it's going to make it much more clear once we actually get to it in the script again.
So let's create a B, T, C where B, T, and C are just 4, 8, and 2 in the toy example. These are basically channels, and we have batches, and we have the time component, and we have information at each point in the sequence. [41:1] Now what we would like to do is, [41:3] we have up to eight tokens here in a batch, [41:7] and these eight tokens are currently not talking to each other. And we would like them to talk to each other; we'd like to couple them. And in particular, we want to couple them in a very specific way:
- The token at the fifth location, for example, should not communicate with tokens in the sixth, seventh, and eighth locations, because those are future tokens in the sequence.
- The token on the fifth location should only talk to the one in the fourth, third, second, and first. So information only flows from previous context to the current timestep, and we cannot get any information from the future because we are about to try to predict the future.
So what is the easiest way for tokens to communicate? The easiest way, I would say, is if we're a fifth token and I'd like to communicate with my past, the simplest way we can do that is to just do an average of all the preceding elements. [42:6] So for example, if I'm the fifth token, [42:8] I would like to take the channels that make up the information at my step, but then also the channels from the fourth step, third step, second step, and the first step. I'd like to average those up, and then that would become sort of like a feature vector that summarizes me in the context of my history.
Now, of course, just doing a sum or an average is an extremely weak form of interaction. This communication is extremely lossy; we've lost a ton of information about the spatial arrangements of all those tokens. But that's okay for now, we'll see how we can bring that information back later. For now, what we would like to do is, for every single batch element independently, for every $t$-th token in that sequence, we'd like to now calculate the average of all the vectors in all the previous tokens and also at this token.
So let's write that out. I have a small snippet here, [43:1] and instead of just fumbling around, let me just copy-paste it and talk through it. [43:7] In other words, we're going to create xbow — and bow is short for bag of words, because bag of words is a term that people use when you are just averaging up things. So this is just a bag of words; basically, there's a word stored on every one of these eight locations, and we're doing a bag of words, we're just averaging.
In the beginning, we're going to say that it's just initialized at zero, and then I'm doing a for loop here — so we're not being efficient yet, that's coming. But for now, we're just iterating over all the batch dimensions independently, iterating over time, and then the previous tokens are at this batch dimension, and everything up to and including the $t$-th token. Okay, so when we slice out x in this way, x_prev becomes of shape however many $t$ elements there were in the past, and then of course C. [44:2] So all the two-dimensional information from these little tokens, [44:6] that's the previous chunk of tokens from my current sequence. And then I'm just doing the average or the mean over the zero dimension, so I'm averaging out the time here, and I'm just going to get a little C-one-dimensional vector, which I'm going to store in xbow.
So I can run this, and this is not going to be very informative, because let's see: this is x[0] (so this is the zeroth batch element), and then xbow[0]. Now you see how at the first location here, the two are equal, and that's because we're just doing an average of this one token. But here, this one is now an average of these two, and now this one is an average of these three, and so on. And this last one is the average of all of these elements. [45:1] So a vertical average, just averaging up all the tokens, now gives this outcome here.
[45:7] So this is all well and good, but this is very inefficient. Now the trick is that we can be very, very efficient about doing this using matrix multiplication. So that's the mathematical trick, and let me show you.
what I mean. Let's work with a toy example here. Let me run it and I'll explain. I have a simple Matrix here that is a 3x3 of all ones, a matrix B of just random numbers and it's a 3x2, and a matrix C which will be 3x3 multiplied by 3x2, which will give out a 3x2. So here we're just using, um, matrix multiplication, so a multiplied by b gives us c.
Okay, so how are these numbers in C, um, achieved, right? This number in the top left is the first row of a dot product with the first column of b. And since all the row of a right now is all just ones, then the dot product here with this column of b is just going to do a sum of this column. So $2 + 6 + 6$ is $14$. The element here in the output of C is also the first column here—the first row of a multiplied now with the second column of b. So $7 + 4 + 5$ is $16$.
Now you see that there are repeating elements here. So this $14$ again is because this row is again all ones and it's multiplying the first column of b, so we get $14$, and this one is... and so on. So this last number here is the last row dot product with the last column.
Now the trick here is the following: this is just a boring number of, um... it's just a boring array of all ones, but PyTorch has this function called tril, which is short for a triangular something like that, and you can wrap it in torch.ones and it will just return the lower triangular portion of this.
Okay, so now it will basically zero out, um, these guys here, so we just get the lower triangular part. Well, what happens if we do that? So now we'll have a like this and b like this. And now what are we getting here in C? Well, what is this number? This is the first row times the first column, and because this is zeros, uh, these elements here are now ignored, so we just get a $2$.
And then this number here is the first row times the second column, and because these are zeros they get ignored, and it's just $7$. This $7$ multiplies this one. But look what happened here: because this is $1$ and then zeros, what ended up happening is we're just plucking out the row of this row of b, and that's what we got.
Now here we have $1, 1, 0$. So here $1, 1, 0$ dot product with these two columns will now give us $2 + 6$, which is $8$, and $7 + 4$, which is $11$. And because this is $1, 1, 1$, we ended up with the addition of all of them.
And so basically, depending on how many ones and zeros we have here, we are basically doing a sum currently of a variable number of these rows, and that gets deposited into C. So currently we're doing sums because these are ones, but we can also do average, right? And you can start to see how we could do average of the rows of b sort of in an incremental fashion. Because we don't have to... we can basically normalize these rows so that they sum to one, and then we're going to get an average.
So if we took a and then we did a = a / torch.sum(a, dim=1, keepdim=True), so therefore the broadcasting will work out. So if I rerun this, you see now that these rows now sum to one. So this row is $1$, this row is $0.5, 0.5, 0$, and here we get $1/3$.
And now when we do a @ b, what are we getting here? We are just getting the first row. First row here, now we are getting the average of the first two rows, okay? So $2$ and $6$ average is $4$, and $4$ and $7$ average is $5.5$. And on the bottom here, we are now getting the average of these three rows, so the average of all elements of b are now deposited here.
And so you can see that by manipulating these, uh, elements of this multiplying matrix and then multiplying it with any given matrix, we can do these averages in this incremental fashion because we just get... um, and we can manipulate that based on the elements of a. Okay, so that's very convenient.
So let's swing back up here and see how we can vectorize this and make it much more efficient using what we've learned. In particular, we are going to produce an array a, but here I'm going to call it wei short for weights, but this is our a. And this is how much of every row we want to average up, and it's going to be an average because you can see that these rows sum to one. So this is our a, and then our b in this example of course is x.
What's going to happen here now is that we are going to have an x_b, and this x_b is going to be wei @ x. So let's think this through: wei is $T \times T$ and this is matrix multiplying in PyTorch: a $B \times T \times T$ by $T \times C$, and it's giving us a different... what shape? PyTorch will come here and it will see that these shapes are not the same, so it will create a batch dimension here, and this is a batched matrix multiply.
And so it will apply this matrix multiplication in all the batch elements in parallel and individually. And then for each batch element, there will be a $T \times T$ multiplying $T \times C$, exactly as we had below. So this will now create $B \times T \times C$, and x_b will now become identical to x_b_2.
So we can see that torch.allclose(x_b, x_b_2) should be true now. So this kind of like convinces us that these are in fact the same.
If I just print x_b... okay, we're not going to be able to just stare it down, but, um, let me try x_b basically just at the zeroth element and x_b_2 at the zeroth element, so just the first batch. And we should see that this and that should be identical, which they are, right?
So what happened here? The trick is we were able to use batched matrix multiply to do this aggregation really, and it's a weighted aggregation. And the weights are specified in this $T \times T$ array, and we're basically doing weighted sums. And these weighted sums are according to the weights inside here; they take on sort of this triangular form. And so that means that a token at the $t$-th dimension will only get sort of information from the tokens preceding it. So that's exactly what we want.
Finally, I would like to rewrite it in one more way and we're going to see why that's useful. This is the third version, and it's also identical to the first and second, but let me talk through it: it uses softmax.
tril here is this matrix lower triangular ones. wei begins as all zeros, okay? So if I just print wei in the beginning, it's all zero. Then I used masked_fill. So what this is doing is wei.masked_fill — it's all zeros, and I'm saying for all the elements where tril is equal-equal $0$, make them be negative infinity.
So all the elements where tril is $0$ will become negative infinity now. So this is what we get. And then the final line here is softmax.
So if I take a softmax along every single... so dim is negative one, so along every single row if I do softmax, what is that going to do? Well, softmax is also like a normalization operation, right? And so, spoiler alert, you get the exact same matrix.
Let me bring back the softmax, and recall that in softmax we're going to exponentiate every single one of these and then we're going to divide by the sum. And so if we exponentiate every single element here, we're going to get a $1$, and here we're going to get basically $0, 0, 0, 0$ everywhere else. And then when we normalize, we just get $1$.
Here we're going to get $1, 1$ and then zeros, and then softmax will again divide and this will give us $0.5, 0.5$, and so on. And so this is also the same.
way to produce this mask. Now, the reason that this is a bit more interesting, and the reason we're going to end up using it in self-attention, is that these weights here begin with zero. You can think of this as an interaction strength or an affinity. Basically, it's telling us how much of each token from the past do we want to aggregate and average up.
And then this line is saying tokens from the past cannot communicate. By setting them to negative infinity, we're saying that we will not aggregate anything from those tokens. And so basically, this then goes through softmax and through the weighted—this is the aggregation through matrix multiplication.
What this is now—you can think of these zeros as currently just set by us to be zero, but a quick preview is that these affinities between the tokens are not going to be just constant at zero. They're going to be data-dependent. These tokens are going to start looking at each other, and some tokens will find other tokens more or less interesting. Depending on what their values are, they're going to find each other interesting to different amounts, and I'm going to call those affinities, I think.
And then here we are saying the future cannot communicate with the past; we're going to clamp them. And then when we normalize and sum, we're going to aggregate their values depending on how interesting they find each other. So that's the preview for self-attention.
Basically, long story short from this entire section:
- You can do weighted aggregations of your past elements by using matrix multiplication of a lower triangular fashion.
- The elements here in the lower triangular part are telling you how much of each element fuses into this position.
So we're going to use this trick now to develop the self-attention block.
First, let's get some quick preliminaries out of the way. The thing I'm kind of bothered by is that you see how we're passing in vocab_size into the constructor? There's no need to do that, because vocab_size is already defined up top as a global variable, so there's no need to pass this stuff around.
Next, I want to create a level of indirection here where we don't directly go from the embedding to the logits, but instead we go through this intermediate phase because we're going to start making that bigger. Let me introduce a new variable, n_embd, which is short for number of embedding dimensions. n_embd here will be, say, 32. (That was a suggestion from GitHub Copilot, by the way; it also suggested 32, which is a good number.) So this is an embedding table with only 32-dimensional embeddings.
Then here, this is not going to give us logits directly; instead, this is going to give us token embeddings, that's what I'm going to call it. And to go from the token embeddings to the logits, we're going to need a linear layer. Let's call it self.lm_head (short for language modeling head), which is nn.Linear from n_embd up to vocab_size.
Then when we swing over here, we're actually going to get the logits by exactly what the Copilot says. We have to be careful here because this C and this C are not equal—this is n_embd (C) and this is vocab_size. So let's just say that n_embd = C. This just creates one spurious layer of interaction through a linear layer, but this should basically run. We see that this runs; and while this currently looks kind of spurious, we're going to build on top of this now.
Next up: so far we've taken these indices and we've encoded them based on the identity of the tokens inside idx. The next thing that people very often do is that we're not just encoding the identity of these tokens, but also their position. So we're going to have a second position embedding table here: self.position_embedding_table is an nn.Embedding of block_size by n_embd. Each position from 0 to block_size - 1 will also get its own embedding vector.
First let me decode B, T from idx.shape. Then here we're also going to have pos_emb, which is the positional embedding. These are basically just integers from 0 to T - 1, and all of those integers get embedded through the table to create a T x C tensor. Then here, x will be the addition of the token embeddings with the positional embeddings. The broadcasting note will work out: (B x T x C) + (T x C) gets right-aligned, a new dimension of 1 gets added, and it gets broadcasted across the batch.
At this point, x holds not just the token identities, but the positions at which these tokens occur. This is currently not that useful because, of course, we just have a simple Bigram model, so it doesn't matter if you're in the fifth position or the second position—it's all translation-invariant at this stage, so this information currently wouldn't help. But as we work on the self-attention block, we'll see that this starts to matter.
Okay, so now we reach the crux of self-attention. This is probably the most important part of this video to understand. We're going to implement a small self-attention for a single individual head, as they're called.
We start off with where we were, so all of this code is familiar. Right now I'm working with an example where I changed the number of channels from 2 to 32, so we have a 4 x 8 arrangement of tokens, and the information in each token is currently 32-dimensional, but we're just working with random numbers now.
We saw here that the code as we had it before does a simple average of all the past tokens and the current token—so previous information and current information are just being mixed together in an average. That's what this code currently achieves by creating this lower triangular structure, which allows us to mask out this matrix that we create. We mask it out and then we normalize it.
Currently, when we initialize the affinities between all the different tokens (or nodes, I'm going to use those terms interchangeably) to be zero, we see that it gives us a structure where every single row has uniform numbers. That's what makes the matrix multiplication perform a simple average.
Now, we don't actually want this to be all uniform, because different tokens will find different other tokens more or less interesting, and we want that to be data-dependent. For example, if I'm a vowel, maybe I'm looking for consonants in my past, and maybe I want to know what those consonants are, and I want that information to flow to me. So I want to gather information from the past, but I want to do it in a data-dependent way. This is the problem that self-attention solves.
Now, the way self-attention solves this is the following: every single node or every single token at each position will emit two vectors:
- It will emit a query.
- It will emit a key.
The query vector, roughly speaking, represents: "What am I looking for?" And the key vector, roughly speaking, represents: "[what do I contain?]"
Do I contain? And then the way we get affinities between these tokens now in a sequence is by basically doing a dot product between the keys and the queries. So my query dot-products with all the keys of all the other tokens, and that dot product now becomes wei (weights). And so if the key and the query are sort of aligned, they will interact to a very high amount. Then I will get to learn more about that specific token as opposed to any other token in the sequence.
So let's implement this. Now we're going to implement a single, what's called head of self-attention. So this is just one head. There's a hyperparameter involved with these heads, which is the head size. And then here I'm initializing linear modules, and I'm using bias=false. So these are just going to apply a matrix multiply with some fixed weights. Now let me produce a key and query, k and q, by forwarding these modules on X. So the size of this will now become B by T by 16, because that is the head size, and the same here: B by T by 16, with 16 being the head size.
So you see here that when I forward this linear layer on top of my X, all the tokens in all the positions in the (B, T) arrangement—all of them in parallel and independently—produce a key and a query. So no communication has happened yet, but the communication comes now: all the queries will dot-product with all the keys. So basically what we want is wei, or the affinities between these, to be q multiplying k transposed. But we have to be careful; we can't just matrix multiply this directly, we actually need to transpose K. And we have to be careful because these have the batch dimension. So in particular, we want to transpose the last two dimensions: dimension 1 and dimension -2 (so -2 and -1). And so this matrix multiplication now will basically do the following: (B by T by 16) matrix multiplied by (B by 16 by T) to give us (B by T by T).
Right, so for every row of the batch B, we're now going to have a T x T matrix giving us the affinities, and these are now the wei. So they're not zeros anymore; they are now coming from this dot product between the keys and the queries. So this can now run. I can run this, and the weighted aggregation now is performed in a data-dependent manner between the keys and queries of these nodes.
Just inspecting what happened here, the wei takes on this form. And you see that before, wei was just a constant, so it was applied in the same way to all the batch elements. But now, every single batch element will have a different sort of wei, because every single batch element contains different tokens at different positions. And so this is now data-dependent.
When we look at just the zeroth row, for example, in the input, these are the weights that came out. And so you can see now that they're not just exactly uniform. And in particular, as an example here, for the last row—this was the 8th token, and the 8th token knows what content it has, and it knows what position it's in. And now the 8th token, based on that, creates a query: "Hey, I'm looking for this kind of stuff. I'm a vowel, I'm on the 8th position, I'm looking for any consonant at positions up to 4." And then all the nodes get to emit keys, and maybe one of the channels could be "I am a consonant, and I am in a position up to 4." And that key would have a high number in that specific channel, and that's how the query and the key, when they dot-product, they can find each other and create a high affinity.
And when they have a high affinity—say, this token was pretty interesting to this 8th token—then through the softmax, I will end up aggregating a lot of its information into my position, and so I'll get to learn a lot about it.
Now, we're looking at wei after this has already happened. Let me erase this operation as well; let me erase the masking and the softmax, just to show you the under-the-hood internals and how that works. Without the masking and the softmax, wei comes out like this: these are the outputs of the dot products. These are the raw outputs, and they take on values from negative 2 to positive 2, etc. So that's the raw interactions and raw affinities between all the nodes.
But now, if I'm the 5th node, I will not want to aggregate anything from the 6th node, 7th node, and 8th node. So actually, we use the upper triangular masking so those are not allowed to communicate. And now we actually want to have a nice distribution—we don't want to aggregate -0.11 of this node, that's crazy! So instead, we exponentiate and normalize, and now we get a nice distribution that sums to one. And this is telling us now, in a data-dependent manner, how much of the information to aggregate from any of these tokens in the past.
So that's wei. It's not zeros anymore, but it's calculated in this way.
Now, there's one more part to a single self-attention head, and that is that when we do the aggregation, we don't actually aggregate the tokens directly; we produce one more value here, and we call that the value (v). In the same way that we produced k (key) and q (query), we're also going to create a value v. And then here we don't aggregate X; we calculate a v, which is just achieved by propagating a linear layer on top of X again, and then we output wei multiplied by V. So V is the elements that we aggregate—or the vectors that we aggregate—instead of the raw X.
And now, of course, this will make it so that the output here of this single head will be 16-dimensional, because that is the head size. So you can think of X as kind of like private information to this token, if you think about it that way. X is kind of private to this token: I am a 5th token at some position, I have some identity, and my information is kept in vector X. And now, for the purposes of the single head, here's what I'm interested in, here's what I have, and if you find me interesting, here's what I will communicate to you—and that's stored in V. And so V is the thing that gets aggregated for the purposes of this single head between the different nodes.
And that's basically the self-attention mechanism, this is what it does.
There are a few notes that I would like to make about attention:
- Attention is a communication mechanism. You can really think about it as a communication mechanism where you have a number of nodes in a directed graph, where basically you have edges pointed between nodes like this. Every node has some vector of information, and it gets to aggregate information via a weighted sum from all of the nodes that point to it. And this is done in a data-dependent manner, depending on whatever data is actually stored.
- Now, our graph doesn't look like an arbitrary graph; our graph has a different structure. We have eight nodes because the block size is eight, and there's always eight tokens. The first node is only pointed to by itself; the second node is pointed to by the first node and itself; all the way up to the eighth node, which is pointed to by all the previous nodes and itself. And so that's the structure that our directed graph happens to have in an autoregressive setting.
of scenario like language modeling. But in principle, attention can be applied to any arbitrary directed graph, and it's just a communication mechanism between the nodes.
The second note is that there is no notion of space, so attention simply acts over a set of vectors in this graph. By default, these nodes have no idea where they are positioned in space, and that's why we need to encode them positionally and sort of give them some information anchored to a specific position so that they know where they are.
This is different than, for example, convolution. If you run a convolution operation over some input, there is a very specific layout of information in space, and the convolutional filters act in space. It's not like attention; in attention, you just have a set of vectors out there in space that communicate. If you want them to have a notion of space, you need to specifically add it—which is what we did when we calculated the relative positional encodings and added that information to the vectors.
The next thing that I hope is very clear is that the elements across the batch dimension—which are independent examples—never talk to each other; they are always processed independently. This is a batched matrix multiply that applies a matrix multiplication in parallel across the batch dimension. So maybe it would be more accurate to say that in this analogy of a directed graph, because the batch size is four, we really have four separate pools of eight nodes, and those eight nodes only talk to each other. In total, there are 32 nodes being processed, but you can look at it as four separate pools of eight.
The next note is that here, in the case of language modeling, we have a specific structure of directed graph where future tokens will not communicate with past tokens. But this doesn't necessarily have to be the constraint in the general case. In fact, in many cases, you may want to have all of the nodes talk to each other fully. As an example, if you're doing sentiment analysis with a Transformer, you might have a number of tokens and want them to fully interact because later you are predicting the sentiment of the sentence, so it's okay for these nodes to talk to each other. In those cases, you will use an encoder block of self-attention. All that means is that you will delete the line of code that restricts communication, allowing all nodes to completely talk to each other.
What we're implementing here is sometimes called a decoder block. It's called a decoder because it decodes language and has this autoregressive format where you have to mask with a triangular matrix so that future nodes never talk to the past (since that would give away the answer). In encoder blocks, you delete the mask and allow all nodes to talk; in decoder blocks, the mask is always present to maintain this triangular structure. But both are allowed, and attention doesn't care—it supports arbitrary connectivity between nodes.
The next thing I wanted to comment on: you keep hearing me say attention, self-attention, etc. There is actually also something called cross attention. What is the difference?
This attention is self-attention because the keys, queries, and values are all coming from the same source, $X$. The same source $X$ produces keys, queries, and values, so these nodes are self-attending.
But in principle, attention is much more general. For example, in encoder-decoder Transformers, you can have a case where the queries are produced from $X$, but the keys and values come from a whole separate external source—sometimes from encoder blocks that encode some context we'd like to condition on. Here, we are just producing queries and reading off information from the side. So cross attention is used when there is a separate source of nodes we'd like to pull information from into our nodes, whereas self-attention is used when we just have nodes that want to look at and talk to each other. This attention here happens to be self-attention, but in principle, attention is a lot more general.
Okay, and the last note at this stage: if we look at the Attention Is All You Need paper, we've already implemented attention. Given query, key, and value, we've multiplied the query and key, applied softmax, and aggregated the values. There is one more thing we're missing, which is dividing by $\frac{1}{\sqrt{d_k}}$, where $d_k$ is the head size. Why do they do this? They call it scaled attention, and it's an important normalization.
The problem is: if you have unit Gaussian inputs (zero mean, unit variance) for keys and queries, and you do it naively, the variance of your weights will be on the order of the head size (which in our case is 16). But if you multiply by $\frac{1}{\sqrt{\text{head size}}}$, the variance of the weights will be one, so it will be preserved.
Why is this important? You'll notice that these weights feed into the softmax function, so it's really important—especially at initialization—that they be fairly diffuse. In our case, we happened to have fairly diffuse numbers. But because of softmax, if the weights take on very positive or very negative numbers, softmax will converge towards one-hot vectors.
I can illustrate that here: say we apply softmax to a tensor of values very close to zero, we get a diffuse output. But the moment I take the exact same thing and start sharpening it—making the numbers bigger by multiplying them by eight, for instance—you'll see that softmax starts to sharpen towards the maximum. Basically, we don't want these values to be too extreme, especially at initialization, otherwise softmax will be way too peaky, and every node will just aggregate information from a single other node. That's not what we want, so scaling is used just to control the variance at initialization.
Okay, having said all that, let's take our self-attention knowledge for a spin. Here in the code, I created this Head module, which implements a single head of self-attention. You give it a head size, and it creates the key, query, and value linear layers (typically, people don't use biases in these). Now, here I am creating this trill variable. Trill is not a parameter of the module—in PyTorch naming conventions, this is called a buffer. It's not a parameter, and you have to assign it to the module using register_buffer.
So that creates the lower triangular matrix, and we're given the input X. This should look very familiar now: we calculate the keys, the queries, we calculate the attention scores inside, and we normalize it, so we're using scaled attention here. Then we make sure that the future doesn't communicate with the past, so this makes it a decoder block, followed by softmax, and then we aggregate the values and output.
Then here in the language model, I'm creating a head in the constructor and I'm calling it self-attention head. The head size I'm going to keep as the same and embed just for now. And then here, once we've encoded the information with the token embeddings and the position embeddings, we're simply going to feed it into the self-attention head, and then the output of that is going to go into the decoder language modeling head and create the logits. So this is sort of the simplest way to plug in a self-attention component into our network right now.
I had to make one more change, which is that here in generate, we have to make sure that our idx that we feed into the model—because now we're using positional embeddings—can never have more than block_size coming in. Because if idx is more than block_size, then our position embedding table is going to run out of scope, since it only has embeddings for up to block_size. And so therefore, I added some code here to crop the context that we're going to feed into self, so that we never pass in more than block_size elements.
So those are the changes, and let's now train the network! Okay, so I also came up to the script here and I decreased the learning rate, because the self-attention can't tolerate very, very high learning rates. And then I also increased the number of iterations because the learning rate is lower. Then I trained it, and previously we were only able to get up to 2.5, and now we are down to 2.4. So we definitely see a little bit of an improvement from 2.5 to 2.4 roughly, but the text is still not amazing. So clearly the self-attention head is doing some useful communication, but we still have a long way to go.
Okay, so now we've implemented the scaled dot-product attention. Now next up, in the Attention Is All You Need paper, there's something called multi-head attention. What is multi-head attention? It's just applying multiple attentions in parallel and concatenating their results. They have a little diagram here—I don't know if this is super clear—it's really just multiple attentions in parallel. So let's implement that, it's fairly straightforward.
If we want a multi-head attention, then we want multiple heads of self-attention running in parallel. In PyTorch, we can do this by simply creating multiple heads—however many heads you want—and then defining the head size of each. Then we run all of them in parallel into a list and simply concatenate all of the outputs. We're concatenating over the channel dimension.
The way this looks now is, we don't have just a single attention that has a head size of 32—because remember, n_embd is 32. Instead of having one communication channel, we now have four communication channels in parallel, and each one of these communication channels typically will be smaller correspondingly. Because we have four communication channels, we want 8-dimensional self-attention, and so from each communication channel we're going to get 8-dimensional vectors, and then we have four of them, and that concatenates to give us 32, which is the original n_embed.
And so this is kind of similar to—if you're familiar with convolutions—this is kind of like a group convolution, because basically instead of having one large convolution, we do convolution in groups. And that's multi-headed self-attention. So then here we just use sa_heads (self-attention heads) instead.
Now I actually ran it, and scrolling down, I ran the same thing and we now get this down to 2.28 roughly. The output generation is still not amazing, but clearly the validation loss is improving, because we were at 2.4 just now. So it helps to have multiple communication channels, because obviously these tokens have a lot to talk about: they want to find the consonants, the vowels, they want to find the vowels just from certain positions, they want to find any kinds of different things. And so it helps to create multiple independent channels of communication, gather lots of different types of data, and then decode the output.
Now going back to the paper for a second, of course I didn't explain this figure in full detail, but we are starting to see some components of what we've already implemented: we have the positional encodings, the token encodings that add, we have the masked multi-headed attention implemented. Now here's another multi-headed attention, which is a cross-attention to an encoder, which we aren't going to implement in this case—I'm going to come back to that later. But I want you to notice that there's a feedforward part here, and then this is grouped into a block that gets repeated again and again.
Now the feedforward part here is just a simple multi-layer perceptron (MLP). So the position-wise feedforward networks is just a simple little MLP. I want to start basically in a similar fashion, also adding computation into the network, and this computation is on a per-node level. I've already implemented it, and you can see the diff highlighted on the left here when I've added or changed things.
Now before, we had the multi-headed self-attention that did the communication, but we went way too fast to calculate the logits. So the tokens looked at each other, but didn't really have a lot of time to think on what they found from the other tokens. And so what I've implemented here is a little feedforward single layer, and this little layer is just a linear followed by a ReLU nonlinearity, and that's it! It's just a little layer, and then I call it feed_forward and embed.
And then this feedforward is just called sequentially right after the self-attention: so we self-attend, then we feed forward. And you'll notice that the feedforward here, when it's applying linear, this is on a per-token level—all the tokens do this independently. So the self-attention is the communication, and then once they've gathered all the data, now they need to think on that data individually, and that's what feedforward is doing, and that's why I've added it here.
Now when I train this, the validation loss actually continues to go down, now to 2.24, which is down from 2.28. The outputs still look kind of terrible, but at least we've improved the situation. And so as a preview, we're going to now start to intersperse the communication with the computation, and that's also what the Transformer does when it has blocks that communicate and then compute, and it groups them and replicates them.
Okay, so let me show you what we'd like to do. We'd like to do something like this: we have a block, and this block is basically this part here except for the cross-attention. Now the block basically intersperses communication and then computation. The communication is done using multi-headed self-attention, and then the computation is done using a feedforward network on all the tokens independently. Now what I've added here also is, you'll notice this takes the number of embeddings in the embedding dimension.
and the number of heads that we would like, which is kind of like group size in group convolution. I'm saying that the number of heads we'd like is four. And so because this is 32, we calculate that the number of heads should be four, and the head size should be eight, so that everything sort of works out channel-wise. So this is typically how the Transformer structures the sizes. The head size will become eight, and then this is how we want to intersperse them. And then here I'm trying to create blocks, which is just a sequential application of block after block, so that we're interspersing communication and feed-forward many, many times, and then finally we decode.
Now, I actually tried to run this, and the problem is this doesn't actually give
Building the Transformer Block
a very good answer and a very good result. The reason for that is we're starting to get a pretty deep neural net, and deep neural nets suffer from optimization issues. I think that's what we're starting to run into, so we need one more idea that we can borrow from the Transformer paper to resolve those difficulties.
Now, there are two optimizations that dramatically help with the depth of these networks and make sure that the networks remain optimizable. Let's talk about the first one. The first one in this diagram—you see this arrow here, and this arrow, and this arrow— those are skip connections, or sometimes called residual connections. They come from the paper Deep Residual Learning for Image Recognition from about 2015, which introduced the concept.
Now, what this basically means is you transform data, but then you have a skip connection with addition from the previous features. The way I like to visualize it, that I prefer, is the following: computation happens from top to bottom, and basically you have this residual pathway, and you are free to fork off from the residual pathway, perform some computation, and then project back to the residual pathway via addition. So you go from the inputs to the targets only via plus, plus, plus, plus.
The reason this is useful is because during backpropagation— remember from our micrograd video earlier— addition distributes gradients equally to both of its branches that fed as the input. And so the supervision or the gradients from the loss basically hop through every addition node all the way to the input, and then also fork off into the residual blocks. But basically you have this gradient superhighway that goes directly from the supervision all the way to the input unimpeded.
And these residual blocks are usually initialized in the beginning so that they contribute very, very little, if anything, to the residual pathway. They are initialized that way, so in the beginning they are almost sort of not there, but then during optimization they come online over time and they start to contribute. At least at initialization, you can go directly from supervision to input; the gradient is unimpeded and just flows, and then the blocks over time kick in. That dramatically helps with optimization.
So let's implement this. Coming back to our block here, basically what we want to do is: x = x + self.attention(x) and x = x + self.feed_forward(x). This is $x$, and then we fork off and do some communication and come back, and we fork off and do some computation and come back. Those are residual connections.
Swinging back up here, we also have to introduce this projection: nn.Linear. This is going to be after we concatenate this— this is the multi-head embed. This is the output of the self-attention itself, but then we actually want to apply the projection, and that's the result. The projection is just a linear transformation of the outcome of this layer, so that's the projection back into the residual pathway. And then here in the feed-forward, it's going to be the same thing. I could have a self.out_projection here as well, but let me just simplify it and couple it inside the same sequential container. So this is the projection layer going back into the residual pathway, and well, that's it!
Now we can train this. I implemented one more small change. When you look into the paper again, you see that the dimensionality of input and output is 512 for them, and they're saying that the inner layer here in the feed-forward has a dimensionality of 2048, so there's a multiplier of four. The inner layer of the feed-forward network should be multiplied by four in terms of channel sizes. So I came here and I multiplied 4 * embed here for the feed-forward, and then from 4 * embed coming back down to embed when we go back to the projection— adding a bit of computation here and growing that layer that is in the residual block on the side of the residual pathway.
And then I train this, and we actually get down all the way to 2.08 validation loss. We also see that the network is starting to get big enough that our train loss is getting ahead of validation loss, so we're starting to see a little bit of overfitting. Our generations here are still not amazing, but at least you see that we can see like, "is here this now... grief syn..." Like, this starts to almost look like English! So yeah, we're starting to really get there.
Okay, and the second innovation that is very helpful for optimizing very deep neural networks is right here: we have this addition, that's the residual part, but this Norm is referring to something called LayerNorm. LayerNorm is implemented in PyTorch; it's a paper that came out a while back here. LayerNorm is very, very similar to BatchNorm. Remember back to our Make More series, part 3, where we implemented batch normalization. Batch normalization basically just made sure that across the batch dimension, any individual neuron had a unit Gaussian distribution— so it was zero mean and unit standard deviation output.
What I did here is I'm copy-pasting the BatchNorm1D that we developed in our Make More series. You see here we can initialize, for example, this module, and we can have a batch of 32, 100-dimensional vectors feeding through the batch norm layer. What this does is it guarantees that when we look at just the zeroth column, it's zero mean, one standard deviation, so it's normalizing every single column of this input. Now, the rows are not going to be normalized by default because we're just normalizing columns.
So let's now implement LayerNorm. It's very complicated, look: we come here, we change this from zero to one, so we don't normalize the columns, we normalize the rows! And now we've implemented LayerNorm. So now the columns are not going to be normalized, but the rows are going to be normalized for every individual example— its 100-dimensional vector is normalized in this way. And because our computation now does not span across examples, we can delete all of this buffers stuff, because we can always apply this operation and don't need to maintain any running buffers. So we don't need the buffers, there's no distinction between training and test time, and we don't need these running...
buffers, we do keep gamma and beta. We don't need the momentum, and we don't care if it's training or not. And this is now a layer norm, which normalizes the rows instead of the columns. This here is basically identical to that there.
So let's now implement layer norm in our Transformer. Before I incorporate the layer norm, I just wanted to note that, as I said, very few details about the Transformer have changed in the last five years, but this is actually something that slightly departs from the original paper. You see that the add and norm is applied after the transformation, but now it is a bit more common to apply the layer norm before the transformation. So there's a reshuffling of the layer norms — this is called the Pre-LN formulation, and that's the one we're going to implement as well. A slight deviation from the original paper!
Basically, we need two layer norms: layer_norm1 is nn.LayerNorm, and we tell it the embedding dimension. Then we need the second layer norm. Here, the layer norms are applied immediately on x: self.layer_norm1 applied on x, and self.layer_norm2 applied on x before it goes into self-attention and feed-forward. The size of the layer norm here is n_embd, so 32.
When the layer norm is normalizing our features, the mean and the variance are taken over 32 numbers, so the batch and the time act as batch dimensions—both of them. This is kind of like a per-token transformation that just normalizes the features and makes them have unit mean and unit variance at initialization. But of course, because these layer norms inside have these gamma and beta training parameters, the layer norm will eventually create outputs that might not be unit Gaussian, but the optimization will determine that.
So for now, this is incorporating the layer norms, and let's train them on. Okay, I let it run, and we see that we get down to 2.06, which is better than the previous 2.08 — so a slight improvement by adding the layer norms. And I'd expect that they help even more if we had a bigger and deeper network.
One more thing I forgot to add is that there should be a layer norm here also, typically at the end of the Transformer and right before the final linear layer that decodes into vocabulary. So I added that as well. At this stage, we actually have a pretty complete Transformer according to the original paper,
Scaling Up and Final Architecture
and it's a decoder-only Transformer. I'll talk about that in a second, but at this stage the major pieces are in place, so we can try to scale this up and see how well we can push this number.
In order to scale up the model, I had to perform some cosmetic changes here to make it nicer. I introduced this variable called n_layer, which just specifies how many layers of the blocks we're going to have. I created a bunch of blocks, and we have a new variable for the number of heads as well. I pulled out the layer norm here, so this is identical.
One thing that I did briefly change is I added a Dropout. Dropout is something that you can add right before the residual connection, right before the connection back into the residual pathway. So we can drop out as a layer here, we can drop out here at the end of multi-headed attention as well, and we can also drop out here when we calculate the affinities and after the softmax, we can drop out some of those. So we can randomly prevent some of the nodes from communicating.
Dropout comes from this paper from 2014 or so, and basically it takes your neural net and, randomly every forward-backward pass, shuts off some subset of neurons— so randomly drops them to zero and trains without them. What this does effectively is, because the mask of what's being dropped out is changed every single forward-backward pass, it ends up training an ensemble of sub-networks. Then at test time, everything is fully enabled, and kind of all of those sub-networks are merged into a single ensemble, if you want to think about it that way. I would read the paper to get the full detail; for now, we're just going to stay on the level of: this is a regularization technique, and I added it because I'm about to scale up the model quite a bit and I was concerned about overfitting.
So now when we scroll up to the top, we'll see that I changed a number of hyperparameters here about our neural net. I made the batch size much larger—now it's 64. I changed the block size to be 256 (previously it was just eight characters of context, now it is 256 characters of context to predict the 257th). I brought down the learning rate a little bit because the neural net is now much bigger. The embedding dimension is now 384, and there are 6 heads (so 384 / 6 means that every head is 64-dimensional as a standard). Then there are going to be 6 layers of that, and the dropout will be at 0.2 (so every forward-backward pass, 20% of all these intermediate calculations are disabled and dropped to zero).
And then I already trained this and ran it, so... drum roll! How well does it perform? Let me just scroll up here. We get a validation loss of 1.48, which is actually quite a bit of an improvement on what we had before, which I think was 2.07. So it went from 2.07 all the way down to 1.48 just by scaling up this neural net with the code that we have!
And this of course ran for a lot longer; this maybe trained for, I want to say, about 15 minutes on my A100 GPU—so that's a pretty beefy GPU. If you don't have a GPU, you're not going to be able to reproduce this; on a CPU, this would be... I would not run this on a CPU or MacBook or something like that, you'll have to break down the number of layers and the embedding dimension and so on. But in about 15 minutes, we can get this kind of a result.
And I'm printing some of the Shakespeare here, but what I did also is I printed 10,000 characters—so a lot more—and I wrote them to a file. Here we see some of the outputs, and it's a lot more recognizable as the input text file. The input text file, just for reference, looked like this (there's always like someone speaking in this manner), and our predictions now take on that form, except of course they're nonsensical when you actually read them:
Is every crimp tap be a house oh those prepation we give heed um you know oho sent me you mighty Lord anyway...
So you can read through this; it's nonsensical of course, but this is just a Transformer trained on a character level for 1 million characters that come from Shakespeare. It sort of blabbers on in Shakespeare-like manner, but it doesn't, of course, make sense at this scale, but I think still a pretty good demonstration of what's possible.
So now I think that kind of concludes the programming section of this video. We basically did a pretty good job of implementing this Transformer, but the picture doesn't exactly match up to what we've done. So what's going on with all these additional parts here? Let me finish explaining this architecture and why it looks so funky. Basically, what's happening here is what we implemented here is a decoder-only Transformer—so there's no component here, this part is called the encoder and
There's no cross-attention block here. Our block only has a self-attention and a feed-forward layer, so it is missing this third in-between piece. This piece does cross-attention, so we don't have it, and we don't have the encoder — we just have the decoder. The reason we have a decoder-only architecture is because we are just generating text, and it's unconditioned on anything. We're just blabbering on according to a given dataset. What makes it a decoder is that we are using the triangular mask in our transformer, so it has this autoregressive property where we can just go and sample from it. The fact that it's using the triangular mask to mask out the attention makes it a decoder, and it can be used for language modeling.
Now, the reason that the original paper had an encoder-decoder architecture is because it is a machine translation paper, so it is concerned with a different setting. In particular, it expects some tokens that encode, say, for example, French, and then it is expecting to decode the translation in English. Typically, these here are special tokens, so you are expected to read in this and condition on it, and then you start off the generation with a special token called start.
So this is a special new token that you introduce and always place in the beginning, and then the network is expected to output neural networks are awesome and then a special end token to finish the generation. This part here will be decoded exactly as we've done it — neural networks are awesome will be identical to what we did. But unlike what we did, they want to condition the generation on some additional information, and in that case, this additional information is the French sentence that they should be translating.
So what they do now is they bring in the encoder. Now, the encoder reads this part here, so we're only going to take the French part, and we're going to create tokens from it exactly as we've seen in our video, and we're going to put a transformer on it. But there's going to be no triangular mask, and so all the tokens are allowed to talk to each other as much as they want, and they're just encoding whatever the content of this French sentence is.
Once they've encoded it, it basically comes out at the top here, and then what happens here is, in our decoder which does the language modeling, there's an additional connection here to the outputs of the encoder. And that is brought in through cross-attention. The queries are still generated from $X$, but now the keys and the values are coming from the side — the keys and the values are coming from the top, generated by the nodes that came outside of the encoder. Those top keys and values feed in on the side into every single block of the decoder.
And so that's why there's an additional cross-attention, and really what it's doing is it's conditioning the decoding not just on the past of this current decoding, but also on having seen the fully encoded French prompt, sort of. And so it's an encoder-decoder model, which is why we have those two transformers, an additional block, and so on. We did not do this because we have nothing to encode, there's no conditioning. We just have a text file and we just want to imitate it, and that's why we are using a decoder-only transformer, exactly as done in GPT.
Okay, so now I wanted to do a very brief walkthrough of nanoGPT, which you can find in my GitHub. nanoGPT is basically two files of interest: train.py and model.py. train.py is all the boilerplate code for training the network. It is basically all the stuff that we had here — it's the training loop. It's just that it's a lot more complicated because we're saving and loading checkpoints and pre-trained weights, decaying the learning rate, compiling the model, and using distributed training across multiple nodes or GPUs. So train.py gets a little bit more hairy and complicated, with more options, etc.
But model.py should look very, very similar to what we've done here. In fact, the model is almost identical. First here, we have the causal self-attention block, and all of this should look very, very recognizable to you. We're producing queries, keys, values; we're doing dot products; we're masking, applying softmaxes, optionally dropping out, and here we are pulling the values.
What is different here is that in our code, I have separated out the multi-headed attention into just a single individual head, and then here I have multiple heads and I explicitly concatenate them. Whereas here, all of it is implemented in a batched manner inside a single causal self-attention, and so we don't just have a $B$, $T$, and $C$ dimension, we also end up with a fourth dimension, which is the heads. So it just gets a lot more hairy because we have four-dimensional array tensors now, but it is equivalent mathematically. The exact same thing is happening as what we have, it's just it's a bit more efficient because all the heads are now treated as a batch dimension as well.
Then we have the multi-layer perceptron. It's using the GELU nonlinearity, which is defined here (except instead of ReLU), and this is done just because OpenAI used it and I want to be able to load their checkpoints. The blocks of the transformer are identical to communicate in the compute phase, as we saw, and then the GPT will be identical. We have the position encodings, token encodings, the blocks, the layer norm at the end, the final linear layer, and this should look all very recognizable.
There's a bit more here because I'm loading checkpoints and stuff like that. I'm separating out the parameters into those that should be weight-decayed and those that shouldn't. But the generate function should also be very, very similar. A few details are different, but you should definitely be able to look at this file and be able to understand the pieces now.
So let's now bring things back to ChatGPT. What would it look like if we wanted to train ChatGPT ourselves, and how does it relate to what we learned today? Well, to train a ChatGPT, there are roughly two stages: first is the pre-training stage, and then the fine-tuning stage.
In the pre-training stage, we are training on a large chunk of the internet and just trying to get a first decoder-only transformer to babble text. So it's very, very similar to what we've done ourselves, except we've done a tiny little baby pre-training step.
And so in our case, this is how you print a number of parameters: I printed it and it's about 10 million. So this transformer that I created here to create a little Shakespeare transformer was about 10 million parameters. Our dataset is roughly 1 million characters, so roughly 1 million tokens. But you have to remember that OpenAI's vocabulary is different — they're not on the character level; they use these subword chunks of words, and so they have a vocabulary of roughly 50,000 elements.
And so their sequences are a bit more condensed. Our dataset, the Shakespeare dataset, would probably be around 300,000 tokens in the OpenAI vocabulary roughly. So we trained about a 10-million-parameter model on roughly 300,000 tokens. Now, when you go to the GPT-3 paper and you look at the transformers that they trained, they trained a number of transformers of different sizes, but the biggest transformer here has 175 billion parameters — so ours is again...
10 million. They used this number of layers in the Transformer. This is the n_embd, this is the number of heads, and this is the head size. And then this is the batch size — so ours was 65, and the learning rate is similar.
Now, when they train this Transformer, they trained on 300 billion tokens. So again, remember ours is about 300,000, so this is about a millionfold increase. And this number would not even be that large by today's standards; you'd be going up to 1 trillion and above. So they are training a significantly larger model on a good chunk of the internet, and that is the pre-training stage.
But otherwise, these hyperparameters should be fairly recognizable to you, and the architecture is actually nearly identical to what we implemented ourselves. But of course, it's a massive infrastructure challenge to train this. You're talking about typically thousands of GPUs having to talk to each other to train models of this size. So that's just the pre-training stage.
Now, after you complete the pre-training stage, you don't get something that responds to your questions with answers and is helpful, etc. You get a document completer, right? So it babbles, but it doesn't babble Shakespeare; it babbles internet. It will create arbitrary news articles and documents, and it will try to complete documents because that's what it's trained for—it's trying to complete the sequence.
So when you give it a question, it might just potentially give you more questions. It will follow with more questions; it will do whatever it looks like some close document would do in the training data on the internet. And so who knows, you're getting kind of undefined behavior. It might answer questions with other questions, it might ignore your question, it might just try to complete some news article. It's totally untuned, as we say.
So the second, fine-tuning stage is to actually align it to be an assistant. This chatGPT blog post from OpenAI talks a little bit about how this stage is achieved. There are roughly three steps to this stage:
- They start to collect training data that looks specifically like what an assistant would do. These are documents with a format where the question is on top and the answer is below. They have a large number of these, but probably not on the scale of the internet — this is probably on the order of maybe thousands of examples. They fine-tune the model to only focus on documents that look like that, slowly aligning it so it expects a question at the top and expects to complete the answer. These very large models are very sample-efficient during fine-tuning, so this actually works.
- You let the model respond, and different raters look at the responses and rank them based on which one is better. They use that to train a reward model using a different network to predict how desirable any candidate response is.
- Once they have a reward model, they run PPO (Proximal Policy Optimization), which is a form of policy gradient reinforcement learning optimizer, to fine-tune the sampling policy so the answers chatGPT generates are expected to score a high reward according to the reward model.
So basically, there's a whole aligning or fine-tuning stage with multiple steps that takes the model from being a document completer to a question-answerer. That's a whole separate stage, and a lot of this data is not available publicly; it's internal to OpenAI, making it much harder to replicate.
That's roughly what gives you a chatGPT, and nanoGPT focuses on the pre-training stage. And that's everything that I wanted to cover today. We trained a decoder-only Transformer following this famous 2017 paper, Attention Is All You Need. That's basically a GPT. We trained it on Tiny Shakespeare and got sensible results.
All of the training code is roughly 200 lines of code. I will be releasing this code base so it comes with all the Git log commits along the way as we built it up. In addition to this code, I'm going to release the Google Colab notebook, and I hope that gave you a sense of how you can train models like gpt3. They are architecturally identical to what we have, but somewhere between 10,000 and 1 million times bigger depending on how you count.
So that's all I have for now. We did not talk about any of the fine-tuning stages that would typically go on top of this. If you're interested in something that's not just language modeling, but you want to perform tasks, align it in a specific way, detect sentiment, or basically anything where you don't want just a document completer, you have to complete further stages of fine-tuning. That could be simple supervised fine-tuning or something more fancy like chatGPT, where we train a reward model and do rounds of PPO.
There's a lot more that can be done on top of it, but we're starting to hit the two-hour mark, so I'm going to finish here. I hope you enjoyed the lecture, and yeah, go forth and transform! See you later.