ReaderTube

AI summary

Yellow marks are automatic key passages. They aren’t personal saved highlights. Select a timestamp to follow along with the video.

Andrej Karpathy's lecture builds a small GPT from scratch, starting from an empty file and a character-level tokenizer applied to the tiny Shakespeare dataset. It explains how a decoder-only Transformer works, covering the bigram baseline, self-attention with queries, keys, and values, multi-head attention, residual connections, layer norm, and dropout, and it compares this design with the encoder-decoder model in the original "Attention Is All You Need" paper. The lecture ends by placing this small model in context: it is essentially the pretraining stage of ChatGPT at a much smaller scale, while the fine-tuning and reinforcement learning stages that make ChatGPT an assistant are left for later.

Introduction to ChatGPT and Text Tasks

ChatGPT has taken the world and the AI community by storm. It is a system that lets people interact with an AI and assign it text-based tasks. For example, a user can ask ChatGPT to write a short haiku about why it is important for people to understand AI so they can use it to improve the world and make it more prosperous. When run, the model returned a haiku reading roughly: 'AI knowledge brings prosperity for all to see. Embrace its power.' The result was not bad. The output appeared word by word, moving from left to right, with each word generated sequentially.

ChatGPT Produces Different Outputs for the Same Prompt

The same prompt was run a little earlier and produced a slightly different result: 'AI's power to grow. Ignorance holds us back. Learn. Prosperity weighs.' Both versions were fairly good, but they differed. This shows that ChatGPT is a probabilistic system. For any single prompt, it can produce multiple plausible answers.

Examples of Humorous and Unexpected Prompts

This haiku is just one example of the many experiments people have run with ChatGPT. Many such interactions have been collected on websites that index them, and many are quite humorous. Examples include prompts such as 'Explain HTML to me like I'm a dog,' 'Write release notes for Chess 2,' and 'Write a note about Elon Musk buying Twitter.' Another example asks for a breaking news article about a leaf falling from a tree and a shocking turn of events. The generated article reports that a leaf, previously attached to a branch, detached itself and fell to the ground in the local park. It is very dramatic.

ChatGPT as a Language Model

This is a remarkable system, and it is what is called a language model. It models the sequence of words, characters, or, more generally, tokens. It learns how words tend to follow one another in the English language. From the model's perspective, it is completing a sequence. The user provides the start of a sequence, and the model completes it with the most likely continuation. In that sense, ChatGPT is a language model.

The Transformer Architecture Behind ChatGPT

The focus here is on the components under the hood that make ChatGPT work. The neural network that models the sequence of words comes from the 2017 paper 'Attention Is All You Need,' a landmark AI paper that proposed the Transformer architecture. GPT stands for Generative Pre-trained Transformer, and the Transformer is the neural network that does most of the heavy lifting. Reading the paper, it looks like a fairly ordinary machine translation paper. The authors probably did not fully anticipate the impact the Transformer would have on the field. The architecture they developed for machine translation went on to take over the rest of AI within about five years. With only minor changes, it was copied into a huge number of AI applications in recent years, including the core of ChatGPT.

Building a Smaller Character-Level Model

Fully reproducing ChatGPT is not feasible. It is a serious, production-grade system trained on a large chunk of the internet, with many pre-training and fine-tuning stages, which makes it very complicated. Instead, the goal is to train a Transformer-based language model. In this case, it will be a character-level language model, which is still very educational for understanding how these systems work. Training on a large internet dataset is unnecessary, so a smaller dataset will be used instead.

Tiny Shakespeare Dataset and Generated Output

The dataset chosen is tiny Shakespeare, a concatenation of Shakespeare's works in a single file of about one megabyte. The model will learn how characters follow one another. Given a context of previous characters, the Transformer predicts which character is likely to come next. Trained on Shakespeare, it learns to produce character sequences that resemble Shakespeare and, in the process, models the patterns within the data. After training, the model can generate an effectively endless stream of fake Shakespeare. The output is imperfect and includes some glitches that could not be resolved in the demo. It still generates text character by character, resembling Shakespearean language, with lines such as 'Verily, my lord, the sites have left the again, the king coming with my curses with precious pale.' ChatGPT produces output in a similar way, but at the token level rather than the character level. Tokens are small subword pieces, not whole words, and are closer to word chunks.

The nanoGPT Repository

The full training code has already been written and is available in a GitHub repository called nanoGPT. The repository trains Transformers on any given text. Many ways to train Transformers exist, but this implementation is very simple. It consists of two files of about 300 lines each. One file defines the GPT model, the Transformer, and the other trains it on a given text dataset. Training it on OpenWebText, a fairly large dataset of web pages, reproduces the performance of GPT-2, an early version of OpenAI's GPT from 2017 if memory serves. So far, only the smallest model, with 124 million parameters, has been reproduced. This demonstrates that the codebase is correctly arranged and that the released neural network weights from OpenAI can be loaded. The finished code can be examined in nanoGPT.

Lecture Goal and Prerequisites

The goal of this lecture is to write the nanoGPT repository from scratch. The process starts with an empty file, defines a Transformer piece by piece, trains it on the tiny Shakespeare dataset, and then generates infinite Shakespeare. The same approach can be applied to any arbitrary text dataset. The main aim is to help viewers understand and appreciate how ChatGPT works under the hood. Only proficiency in Python and a basic understanding of calculus and statistics are required. Viewers who have seen the earlier videos on the channel, particularly the 'makemore' series, will benefit. That series introduces the language modeling framework through smaller, simpler neural network language models such as multilayer perceptrons. This lecture focuses on the Transformer neural network itself.

Setting Up the Notebook and Loading the Data

A new Google Colab Jupyter notebook is created so the code can be shared easily. A link to it will appear in the video description so viewers can follow along. The preliminary step downloads the tiny Shakespeare dataset from a URL. The file is about one megabyte. The input text file is opened and read as a single string. The text contains roughly one million characters. Printing the first 1,000 characters shows what would be expected from the start of the tiny Shakespeare dataset.

Building the Character Vocabulary

The text is a sequence of characters in Python. Calling the set constructor on it yields the set of all unique characters in the text. That set is converted to a list to create an ordering, and the list is sorted. The result is every character that occurs in the entire dataset, in sorted order. The number of these characters is the vocabulary size. These are the possible elements of the sequences. The vocabulary contains 65 characters in total, including a space, various special characters, uppercase letters, and lowercase letters. These are the characters the model can see or emit.

Tokenization with a Character-Level Encoder

The next step is to develop a strategy for tokenizing the input text. Tokenizing means converting raw text into a sequence of integers according to a vocabulary of possible elements. Because this is a character-level language model, each individual character is translated into an integer. Encoding a string such as 'hi there' returns a list of integers representing that string, such as 46, 47, and so on. A reverse mapping decodes the list back into the exact original string. The encoder and decoder are a translation to integers and back. The mapping is built by iterating over all the characters and creating a lookup table from each character to an integer and back. To encode a string, each character is translated individually. To decode, the reverse mapping is used and the results are concatenated.

Other Tokenization Schemes

This character-level encoding is only one of many possible tokenizers, and it is a very simple one. Other schemes exist in practice. Google uses SentencePiece, which also encodes text into integers, but with a different scheme and vocabulary. SentencePiece is a subword tokenizer, meaning it encodes neither entire words nor individual characters, but subword units. This approach is usually what is adopted in practice. OpenAI has a library called tiktoken that uses a byte pair encoding tokenizer. GPT models use it. Words can also be encoded, so that 'hello world' becomes a list of integers.

Trading Off Vocabulary Size and Sequence Length

As an example, the tiktoken library is used to get the encoding for GPT-2. Instead of 65 possible characters or tokens, GPT-2 uses a vocabulary of 50,000 tokens. Encoding the same string 'hi there' yields only three integers. Those integers, however, are not between 0 and 64. They fall between 0 and 50,256. This shows that the codebook size and the sequence length can be traded off. A very small vocabulary can produce very long sequences of integers, while a larger vocabulary produces shorter ones.

Character-Level Tokenization Trade-Off

Subword encodings, such as the byte pair encoding used by OpenAI's tiktoken library for GPT models, are the common choice in practice. They strike a balance: a tokenizer can encode text into fairly short integer sequences using a large vocabulary, or into very long sequences using a small one. For example, GPT-2's encoding uses about 50,257 tokens, so the string 'hello world' becomes a list of only three integers, each between 0 and 50,256. A character-level tokenizer instead uses a vocabulary of 65 characters, which means a small codebook and simple encode and decode functions, but much longer sequences. This lecture keeps the tokenizer simple and uses character-level tokenization because it is the most straightforward approach.

Encoding the Full Dataset as a Tensor

With an encoder and decoder in place, the full Tiny Shakespeare training text can be tokenized. The text is encoded and wrapped in a torch.tensor from the PyTorch library to form the data tensor. Looking at the first 1,000 elements shows a long sequence of integers that is a direct translation of the first 1,000 characters of the text. In this mapping, zero probably represents the newline character and one may represent a space, though this is not certain. From this point on, the entire dataset is represented as one very long sequence of integers.

Splitting Data into Training and Validation Sets

The dataset is then split into a training set and a validation set. The first 90% of the data serves as training data for the Transformer, and the final 10% is held back as validation data. The validation split shows how much the model overfits. The goal is not perfect memorization of this exact Shakespeare text. Instead, the aim is a neural network that generates Shakespeare-like text, so it should be fairly likely to produce passages similar to the hidden, true Shakespeare text. The validation data is kept aside to measure overfitting.

Sampling Chunks and Block Size

A Transformer never processes the entire text at once, because that would be computationally expensive and prohibitive. Instead, training uses chunks of the dataset. Random chunks of a set maximum length are sampled from the training set, and that length is called the block size, also known as the context length in many implementations. The example starts with a block size of 8. The first block size plus one characters, which is nine characters, are taken from the training set. The extra character is needed for the targets, as explained below.

Eight Training Examples in One Chunk

A chunk of nine characters contains multiple training examples, because the characters follow one another in sequence. When the chunk is fed into a Transformer, the model makes a prediction at every position at the same time. A chunk of nine characters therefore holds eight individual examples. For instance, given the context 18, the next token is 47. Given 18 and 47, the next token is 56. Given 18, 47, and 56, the next token is 57, and so on. Code can make this explicit. The input x is the first block size characters, and the target y is the same sequence offset by one, so each position in x has its correct next character in y. Each position t uses all characters in x up to and including t as its context, and the target is the character at position t in y. Running this code prints the eight examples hidden in the nine sampled characters.

Training on All Context Lengths

All eight examples are used for training, with context lengths ranging from one character up to the full block size. This is not only for computational convenience, since the sequence is already available. It also teaches the Transformer to handle every context length from 1 to block size. This matters during inference. Sampling can begin with as little as one character of context, and the Transformer can predict the next character from that single character. It can then predict with longer contexts up to the block size. Once the text exceeds the block size, the context must be truncated, because the Transformer never receives more than block size inputs when predicting the next character.

Adding a Batch Dimension

Along with the time dimension, the tensors fed into a Transformer have a batch dimension. Many chunks of text are stacked into a single tensor and processed together. This is done for efficiency, because GPUs are very good at parallel processing and stay busy when handling multiple chunks at once. The chunks are processed independently and do not interact with one another.

Sampling Batches of Random Chunks

The batch size is the number of independent sequences processed in each forward and backward pass of the Transformer. The block size is the maximum context length used for predictions. In the example, the batch size is 4 and the block size is 8. The random number generator's seed is set so the numbers match when the code is reproduced. A get_batch function selects data from the training split or the validation split. It generates batch size random offsets between zero and the length of the data minus the block size. For each offset, x is the first block size characters starting at that position, and y is the same chunk shifted by one. The chunks are stacked into rows with torch.stack, which produces a 4 by 8 tensor for both x and y.

Batch Inputs and Targets

The sampled batch contains a 4 by 8 input tensor xb, made of four rows of eight characters. Each row is a chunk of the training set. The targets yb are aligned with these inputs and are used in the loss function to provide the correct answer at every position in xb. The 4 by 8 array contains 32 examples, which are completely independent from the Transformer's perspective. For example, when the input is 24, the target is 43. When the input is 24, 43, the target is 58. When the input is 24, 43, 58, the target is 5. When the input ends with 52, 58, 1, the target is 58. The integer tensor x feeds into the Transformer, which processes all these examples at once and looks up the correct next integer at every position in the target tensor y.

The Bigram Language Model

The simplest neural network for language modeling is the bigram language model. This model was covered in depth in the makemore series, so this section moves faster. A PyTorch module implements the bigram model directly. It is a subclass of nn.Module, and it takes the inputs and targets as arguments. The input indices, named idx, are passed into a token embedding table created in the constructor. The table has size vocab_size by vocab_size and is built with nn.Embedding, a thin wrapper around a tensor of that shape. Each integer in the input refers to a row in this table and plucks out the row at its index. For example, the integer 24 selects row 24, and the integer 43 selects row 43.

Predicting from a Single Token's Identity

PyTorch arranges the selected rows into a tensor with dimensions batch by time by channel. Here the batch size is 4, the time dimension is 8, and the channel dimension is the vocabulary size of 65. These values are interpreted as logits, which are scores for the next character in the sequence. The model therefore predicts what comes next based only on the identity of the current token. The tokens do not yet communicate or see any context beyond themselves. Even so, the model can make fairly decent predictions. Knowing that the token is number five is enough, because certain characters commonly follow others in typical text. This idea was explored in much more depth in the makemore series.

Computing the cross-entropy loss

With the predictions in place, the next step is to evaluate the loss. The make more series showed that a good way to measure the quality of predictions is the negative log likelihood loss, which PyTorch implements under the name cross entropy. The loss is computed as cross entropy between the logits and the targets, which measures how well the logits match the target characters. In other words, given the identity of the next character, the question is how well the model predicts it from the logits. Intuitively, the logit at the correct position for the target should be very high, and all the other positions should be very low. Running this call directly produces an error, so the inputs must first be reshaped. PyTorch's functional cross entropy expects multi-dimensional input with the channel dimension second, meaning a B×C×T tensor rather than the B×T×C tensor the model currently produces. Instead of adjusting the layout to match, the logits can be reshaped. The shape is unpacked into B, T, and C, and the logits are viewed as a two-dimensional array of size (B·T)×C. All the positions are stretched into a single sequence while the channel dimension is preserved as the second dimension. The targets, which have shape B×T, are flattened the same way into a one-dimensional array of length B·T. Using -1 would also work, since PyTorch can infer the size, but stating B·T explicitly is clearer. After reshaping, the cross entropy call matches what PyTorch expects, and the loss can be evaluated. The initial loss is 4.87. With 65 possible vocabulary elements, the expected loss for uniform predictions can be calculated as the negative log of 1/65, which is about 4.17. The observed value of 4.87 is higher than that, which indicates that the initial predictions are not very diffuse. They carry some confidence and are therefore wrong in places. Even so, the loss can be evaluated, so the model's quality on data can now be measured.

Generating text from the model

With the loss in place, the next goal is generating text from the model. This section moves faster because the same ideas were covered in earlier videos. The generate function takes an index tensor idx of shape B×T, which holds the current context of characters in a batch. Its job is to extend that tensor to B×(T+1), then B×(T+2), and so on, continuing the generation in both the batch and time dimensions for max_new_tokens steps. Each generation step works as follows. The model is called on the current indices to obtain the logits. No targets are given, so no loss is computed. Only the last time step is used, since that position holds the prediction for what comes next. Taking the last element along the time dimension turns the B×T×C logits into a B×C array. Softmax converts these logits into probabilities, and torch.multinomial samples one value from each batch row, producing a B×1 tensor. The sampled integers are then concatenated onto the running sequence along the time dimension, which yields a B×(T+1) tensor that is returned. The forward function needs one change for this to work. When generate calls self(idx) without targets, an error would occur, so targets defaults to None. When targets is None, no loss is created and only the logits are returned. When targets are provided, the loss is computed as well. To test the generation, a one-by-one tensor holding zero is created with an integer data type. Zero serves as the starting character because it represents the newline character, which is a reasonable first character to feed into the sequence. The generate function is called for 100 new tokens. Its output is a batch, so the single batch dimension is indexed out to get a one-dimensional array of indices. That array is converted to a plain Python list and passed to the decode function to turn the integers into text. The result is garbage, which is expected because the model is completely random at this point. The generate function is written in a general way, but it is wasteful for this bigram model. It feeds in and concatenates the entire context on every step, even though only the last character matters for predicting the next one. For example, predicting the character after K only needs the W before it. The function is kept this way on purpose, because later models will use the history of characters, and the function should work unchanged then.

Training the model with Adam

The randomly initialized model is trained next so that its output becomes less random. A PyTorch optimizer object is created first. The make more series used only stochastic gradient descent, the simplest optimizer, which is available as SGD. Adam is used here instead because it is more advanced and popular, and it works extremely well. A typical learning rate for Adam is roughly 3e-4. Very small networks like this one can tolerate much higher learning rates, such as 1e-3 or even higher. The optimizer takes the gradients and updates the parameters with them. The batch size was only 4 earlier, so it is increased to 32. The training loop follows the standard pattern from the make more series. For a fixed number of steps, a new batch of data is sampled, the loss is evaluated, the gradients from the previous step are zeroed out, the gradients for all parameters are computed, and the parameters are updated. A first run of 100 iterations shows the loss falling from about 4.7 to around 4.5 and lower, so the optimization is clearly working. To train for longer, the number of iterations is increased while printing only at the end. The loss drops to about 3.6, then to roughly 3, which is a rough optimization but a working one. Next, the run is extended to 10,000 iterations. The loss reaches about 2.5, and the generated text shows dramatic improvement over the earlier output. Increasing the number of generated tokens shows that the output is starting to look somewhat reasonable. It is certainly not Shakespeare from a bigram model, but the model is clearly making progress. This is the simplest possible model. Because the tokens do not communicate with each other, each prediction uses only the very last character of the previous context. The next step is to let the tokens talk to each other so that they can work out what is in the context and make better predictions.

Introducing Token Communication for the Transformer

Tokens need a way to use the context that precedes them. Earlier, the model predicted each next token from only the last token, so the tokens never interacted. Letting tokens communicate with one another, so each can draw on what came before it, is how the Transformer begins. Before building that mechanism, the code developed in the Jupyter notebook is converted into a standalone script. The goal is to consolidate the intermediate work into a single final product.

Structure of the Training Script

The script places all the hyperparameters at the top. Some of them are new, and they are explained shortly. Much of the rest will look familiar from the notebook. It sets up reproducibility, reads the data, and builds the encoder and decoder. It then creates the train and validation splits and a data loader that returns batches of inputs and targets. The data loader is new and is covered in more detail later. The script also defines the bigram language model, which can run a forward pass that returns logits and loss and can generate text. It then creates the optimizer and runs the training loop.

Running the Model on a GPU

The script can now run on a GPU when one is available. If a GPU is present, the device is set to CUDA instead of CPU, which makes training considerably faster. When the device is CUDA, the data must be moved to that device as it is loaded. The model parameters must also be moved to the device when the model is created. For example, the embedding table stores its weights in a lookup table, and those weights are moved to the GPU so that all calculations run there. Finally, the context used for generation must also be created on the same device.

Estimating Loss More Accurately

Printing the loss from each individual batch inside the training loop gives a noisy measurement, because every batch is more or less favorable. To address this, the script includes an estimate_loss function. It runs the model over eval_iters batches and averages the loss for both the training and validation splits. The result is a much less noisy and more accurate report of training and validation loss.

Evaluation Mode and Disabling Gradients

Before estimating the loss, the model is set to evaluation mode, and afterward it is switched back to training mode. For this particular model, the switch has no effect. The only component is an nn.Embedding layer, which behaves the same in both modes, and the model has no dropout or batch norm layers. Still, it is good practice to track which mode a network is in, because some layers behave differently during inference and training. The torch.no_grad context manager tells PyTorch that nothing inside the function will have backward called on it. Because backpropagation will never run there, PyTorch does not need to store intermediate variables, which makes memory use more efficient. Disabling gradients when backpropagation is not intended is also a recommended practice.

Script Length and Output

The script is about 120 lines and serves as the starter code. It will be released later. When it runs, it prints the training loss and validation loss to the terminal. With the bigram model, both losses converge to roughly 2.5. The script then prints a sample of generated text. Everything is now packaged in one script, which provides a solid base for further iteration.

A Toy Example for Self-Attention

The next step is a mathematical trick at the heart of an efficient implementation of self-attention. It is first practiced on a toy example before it is applied in the script. The example uses a tensor of shape B, T, C, with batch size 4, time steps 8, and channels 2. Each batch contains eight tokens that do not yet communicate, and the goal is to let them communicate in a specific way. A token at position 5 should not communicate with tokens at positions 6, 7, or 8, because those are future tokens. It should only receive information from positions 4, 3, 2, and 1, along with its own. Information flows only from previous context to the current time step, since the model must not see the future it is trying to predict.

Averaging Past Tokens

The simplest way for a token to communicate with its past is to average all the preceding elements, including itself. For the fifth token, the channels of that token are combined with the channels of the fourth, third, second, and first tokens, and their average becomes a feature vector that summarizes the token in the context of its history. This kind of sum or average is an extremely weak form of interaction. It is very lossy, because it discards much of the information about the spatial arrangement of the tokens. That loss is acceptable for now, and the information will be brought back later. For the moment, the goal is to compute, for every batch element independently and every time step, the average of all vectors up to and including that token.

Bag-of-Words Averaging with a Loop

The averaging operation is called a bag of words, a term used when things are simply averaged together. The code creates xbow, which is initialized to zeros. For now, a loop iterates over each batch element independently and over each time step. At each step, the previous tokens, from the start of the sequence through the current token, are sliced out of x. This slice has shape time elements by channels, and its mean over the time dimension yields a one-dimensional vector that is stored in xbow. The output confirms the pattern. The first location equals the original token because it averages only one token. Each later location averages one more token than the last, and the final location averages all of them. This loop is inefficient, but a more efficient method is coming.

Matrix Multiplication as Weighted Summation

The same result can be computed much more efficiently with matrix multiplication. A toy example uses a 3 by 3 matrix a of all ones, a 3 by 2 matrix b of random numbers, and their product c, which is 3 by 2. Each element of c is a dot product of a row of a with a column of b. Because every row of a is all ones, each element is simply the sum of a column of b. For example, the top-left element is 2 + 6 + 6, which equals 14, and the top-right element is 7 + 4 + 5, which equals 16. Torch provides a function called tril, short for triangular, which wrapped in torch.ones returns the lower triangular portion of a matrix. This zeros out the upper part of a, leaving a lower triangular matrix. When the product is taken with this matrix, each row of the result sums only the rows of b that are permitted by the ones in that row. The first row keeps only the first row of b. The second row sums the first two rows, and the third row sums all three. Depending on how many ones and zeros each row contains, the result is a sum over a variable number of rows of b.

Normalizing Rows to Compute Averages

The results so far are sums because the ones in the matrix are not normalized. Averages can be obtained by normalizing each row so that it sums to one. Doing this incrementally lets the rows of b be averaged in the same matrix multiplication. The next step is to sum a along dimension one with keepdim set to true, which provides the normalization needed to turn the sums into averages.

Normalizing rows to compute averages

Because the broadcasting works out, rerunning the code shows that each row of the matrix now sums to one. The first row is 1, the second row is 0.5 and 0.5 with a zero in the remaining position, and the third row places 1/3 in each of its three entries. When B is multiplied by this matrix, the first output row is just the first row of B. The second output row is the average of the first two rows of B: the average of 2 and 6 is 4, and the average of 4 and 7 is 5.5. The bottom output row is the average of all three rows of B. By manipulating the elements of this multiplying matrix, and then multiplying it with any matrix, these averages can be computed in an incremental fashion. The weights are set based on the elements of a, which makes this approach very convenient.

Vectorizing the averages with a weight matrix

To make this more efficient, the code returns to the earlier setup and vectorizes it. An array called wei, short for weights, holds how much of each row should be averaged in. Because the rows sum to one, the operation computes an average. In this example, B is x. The next step is to multiply wei with x using matrix multiplication. The shapes of the two tensors do not match, so PyTorch creates a batch dimension and performs a batched matrix multiply. This applies the matrix multiplication to all batch elements in parallel and individually. For each batch element, a T by T matrix multiplies a T by C matrix, producing a B by T by C result. The output, xbow2, becomes identical to xbow.

Verifying the two versions match

To confirm that the two computations agree, torch.allclose of xbow and xbow2 should return true. Comparing the full printed tensors by eye is impractical, so the zeroth batch element of each is printed instead, and they are identical. The key point is that batched matrix multiplication performs a weighted aggregation, with the weights specified in the T by T array. These weighted sums follow a triangular form, so a token at position t only receives information from the tokens at or before position t. This is exactly the behavior that is wanted.

A softmax-based formulation of the mask

A third version produces the same result using softmax. The tril matrix is the lower triangular matrix of ones, and wei begins as a matrix of all zeros. Calling masked_fill sets every element where tril equals zero to negative infinity. Applying softmax along the last dimension normalizes each row. Exponentiating negative infinity gives zero, so the normalized rows match the averaging matrix: the first row is one followed by zeros, the next row is 0.5 and 0.5 followed by zeros, and so on. This formulation is more useful for self-attention because the weights start at zero and can be interpreted as interaction strengths, or affinities, that determine how much of each past token to aggregate. Future tokens are excluded by setting their entries to negative infinity, so they cannot communicate with the past.

Affinities as a preview of self-attention

The zeros in wei act as interaction strengths. They are set to zero by hand here, but in self-attention they will not stay constant. Instead, they will be data-dependent. Tokens will start looking at each other, and some tokens will find others more or less interesting depending on their values. Each pair of tokens will find each other interesting to a different degree, and these affinities, which I think of as the key quantity, are then normalized and used to aggregate values. The future is still clamped, so it cannot communicate with the past. This is the preview of self-attention.

Summary of weighted aggregation

The main takeaway from this section is that weighted aggregations of past elements can be computed with matrix multiplication using a lower triangular structure. The entries in the lower triangular part indicate how much each element contributes to a given position. This trick will be used to develop the self-attention block.

Preliminary cleanup and an output projection

First, some preliminaries. The constructor currently passes vocab_size as an argument, but this is unnecessary because vocab_size is already defined at the top as a global variable. Next, rather than having the token embedding table produce logits directly, an intermediate stage is introduced, since that stage will grow larger. A new variable n_embd, short for number of embedding dimensions, is set to 32. GitHub Copilot suggested this value, and it also suggested 32 as a good number. The embedding table therefore produces 32-dimensional token embeddings. To get from token embeddings to logits, a linear layer is needed. self.lm_head, short for language modeling head, is an nn.Linear from n_embd to vocab_size. The logits come out of this layer. Because n_embd and C are not equal in general, n_embd is set equal to C. This adds one simple layer of interaction through a linear layer, and the code runs.

Adding position embeddings

So far, the model encodes each token by its identity. It is also common to encode each token's position, so a second table is added. self.position_embedding_table is an embedding of block_size by n_embd, so each position from zero to block_size minus one gets its own embedding vector. In the forward pass, B and T are decoded from idx.shape. Positional embeddings are created from integers from 0 to T minus 1, which are embedded through the table to produce a T by C tensor. The result, named x, is the sum of the token embeddings and the positional embeddings. Broadcasting works here: B by T by C plus T by C right-aligns the shapes, adds a new dimension of one, and broadcasts across the batch. At this point, x holds both the token identities and the positions at which they occur. This does not help much yet, because a simple bigram model is translation invariant at this stage, so the position of a token makes no difference. That will change as the self-attention block is built.

Starting self-attention from uniform averaging

Self-attention is the most important part to understand, so the code now implements a small self-attention for a single head. The example changes the number of channels from 2 to 32, giving a 4 by 8 arrangement of tokens, where each token is 32-dimensional and currently filled with random numbers. The existing code computes a simple average of all past tokens and the current token, so previous and current information are mixed together. It does this by creating a lower triangular structure that masks the matrix, and then normalizing it. When the affinities between all tokens, or nodes, are initialized to zero, every row of wei contains uniform numbers, and the matrix multiply produces a simple average. However, the weights should not be uniform. Different tokens find different other tokens more or less interesting, and this should depend on the data. For example, if a token is a vowel, it may be looking for consonants in its past and want to know what those consonants are, so that information should flow to it. Gathering information from the past in a data-dependent way is the problem that self-attention solves.

Queries and keys for data-dependent affinities

Self-attention solves this by having every token at each position emit two vectors: a query and a key. Roughly speaking, the query represents what a token is looking for, and the key represents what a token contains. The affinities between tokens in a sequence are obtained by taking a dot product of queries and keys. We basically just do a dot product.

Computing Affinities Between Queries and Keys

Data-dependent communication between tokens works by comparing what each token is looking for with what every other token contains. Each token emits a query vector, which roughly describes what it is looking for, and a key vector, which roughly describes what it contains. The affinity between two tokens is computed as the dot product of one token's query with the other tokens' keys. When a query and a key are aligned, their dot product is high, so the two tokens interact strongly, and the token that issued the query learns more about that specific token than about any other token in the sequence.

Implementing a Single Self-Attention Head

The implementation starts with a single head of self-attention. The head has one hyperparameter, the head size, which is set to 16 in this example. Three linear modules are initialized with bias set to false, so each one applies a matrix multiplication with fixed weights and no bias term. The key and query are produced by forwarding the input X through their respective linear modules. With input of shape B by T by C, the resulting keys and queries have shape B by T by 16, where 16 is the head size. Every token in every position across the batch dimension produces its key and query in parallel and independently. At this stage no communication between tokens has occurred yet. Communication begins when the queries interact with the keys.

Computing the Attention Weights Through Batched Matrix Multiplication

The affinities between tokens are computed as the query multiplied by the key. The keys cannot be multiplied directly, so they must be transposed. Because the batch dimension is present, the transpose applies to the last two dimensions, dimension 1 and dimension -2, rather than to the whole tensor. The resulting matrix multiplication takes B by T by 16 queries and B by 16 by T keys and produces a B by T by T output. For each batch element, this yields a T-by-T matrix of affinities. These values are not zeros. They come from the dot products between keys and queries, so the weights are computed from the data itself.

Data-Dependent Weights and an Example

The weighted aggregation is a function of the keys and queries of the nodes, so it depends on the data. Previously, the weights were a constant buffer applied identically to every batch element. Now each batch element has its own weights, because each one contains different tokens at different positions. Inspecting the zeroth row of the input shows weights that are not uniform. For the last row, which corresponds to the eighth token, the token knows its own content and its position. Based on that, it creates a query that roughly says it is looking for a certain kind of content. For example, a token that is a vowel at position five might look for any consonant at positions up to four. Every node emits keys, and one channel of a key could indicate that the node is a consonant located at a position up to four. That key would carry a high value in that channel, so the query and key would find each other and produce a high affinity. When a high affinity forms, the softmax aggregates a large share of that token's information into the querying position, so the position learns a lot from it.

Masking and Softmax Internals

To show the internal mechanics, the masking and softmax are removed so the raw outputs of the dot products can be inspected. Without masking and softmax, these raw outputs take values from roughly negative two to positive two. They represent the raw interactions and affinities between all the nodes. A fifth node, however, should not aggregate information from the sixth, seventh, or eighth nodes, because those are in its future. The upper triangular mask prevents those connections. Next, the values are exponentiated and normalized. Aggregating a raw weight of negative 0.11 from a node would be problematic, so the exponentiation and normalization produce a distribution that sums to one. This distribution determines, in a data-dependent way, how much information to aggregate from each past token. The weights are no longer zeros, and they are calculated through this process.

Values as the Aggregated Content

A single self-attention head has one more component. When the aggregation happens, the model does not aggregate the raw tokens X directly. Instead, it produces a value vector. In the same way that keys and queries are produced, a value is computed by passing X through another linear layer. The output of the head is the weight matrix multiplied by V. V is therefore the set of vectors that get aggregated, in place of the raw X. The output of this single head is 16-dimensional, matching the head size. X can be thought of as private information belonging to each token. A fifth token has an identity, and its information is kept in the vector X. For the purposes of a single head, the token computes what it is interested in, which is the query, and what it has, which is the key. If another token finds it interesting, the information it communicates is stored in V. V is the quantity that gets aggregated between the different nodes. This is the basic self-attention mechanism.

Attention as a Communication Mechanism

Attention is a communication mechanism. It can be understood as a directed graph of nodes, where edges point between nodes. Each node holds a vector of information and aggregates information through a weighted sum from all the nodes that point to it. This aggregation is data-dependent, so it depends on the data stored at each node at a given point in time. In the language-modeling setting, the graph has a specific structure. With a block size of eight, there are always eight tokens. The first node is pointed to only by itself. The second node is pointed to by the first node and by itself, continuing up to the eighth node, which is pointed to by all the previous nodes and itself. This is the structure of the directed graph in autoregressive settings such as language modeling. In principle, however, attention can be applied to any arbitrary directed graph, since it is simply a communication mechanism between nodes.

Positional Information and the Absence of Spatial Structure

Attention has no inherent notion of space. It acts over a set of vectors, and by default the nodes have no information about where they sit in the sequence. For this reason, positional information must be encoded and anchored to specific positions so that each node knows where it is. This differs from convolution. A convolution operates over input with a specific spatial layout, and its filters act in space. Attention treats its inputs as a set of vectors that communicate with one another. If the nodes are meant to have a notion of space, that information must be added explicitly. In this implementation, that was done by computing relative positional encodings and adding them to the vectors.

Independence Across the Batch Dimension

Elements across the batch dimension are independent examples and never communicate with one another. They are processed independently, and the batched matrix multiplication applies the matrix multiplication in parallel across the batch dimension. A more accurate picture of the directed-graph analogy is that, with a batch size of four, there are four separate pools of eight nodes. Within each pool, the eight nodes communicate only with each other. In total, 32 nodes are processed, organized as four separate groups of eight.

Encoder and Decoder Blocks

In language modeling, the directed graph has a structure in which future tokens do not communicate with past tokens. This constraint is not required in general. In many cases, all the nodes should communicate fully with one another. For example, in sentiment analysis with a Transformer, all tokens may need to talk to each other fully, because the sentiment of the sentence is predicted afterward. Such cases use an encoder block of self-attention. An encoder block is created by deleting the line of code that masks future tokens, which allows all nodes to communicate completely. The implementation here is a decoder block. It is called a decoder because it decodes language in an autoregressive format. Future nodes must be masked with the triangular matrix so that they never communicate with past nodes, since that would reveal the answer. Encoder blocks allow all nodes to talk, while decoder blocks keep the triangular structure. Both are permitted, because attention supports arbitrary connectivity between nodes.

Cross-Attention Compared With Self-Attention

This attention is self-attention because the keys, queries, and values all come from the same source, X. The nodes attend to themselves and to each other. Attention is more general than this. In an encoder-decoder Transformer, the queries may be produced from X, while the keys and values come from a separate external source. That source is often the output of encoder blocks that encode a context to condition on. The keys and values then come from a different set of nodes on the side, and the current nodes only produce queries and read information from that side source. Cross-attention is used when a separate set of nodes is a source of information to pull into the current nodes. Self-attention is used when the nodes simply look at and communicate with each other. The attention in this example is self-attention, but attention in general is far more flexible.

Connection to the Attention Is All You Need Paper

The last note at this stage concerns the paper 'Attention Is All You Need', which the discussion turns to next.

Scaling attention by head size

Attention is already implemented: given queries, keys, and values, the query and key are multiplied, the result is passed through softmax, and the values are aggregated. One component is still missing. The scores are multiplied by one over the square root of the head size, where the head size is denoted d_k. The Attention Is All You Need paper calls this scaled attention, and it is an important normalization step.

Controlling variance at initialization

Suppose the inputs have zero mean and unit variance, so the keys and queries are unit Gaussian. Without scaling, the variance of the raw attention scores is on the order of the head size, which is 16 in this example. Multiplying by one over the square root of the head size brings the variance back to one, so it is preserved. This matters because the attention weights feed into softmax. At initialization especially, the weights should be fairly diffuse.

How extreme values sharpen softmax

If the weights contain very large positive and very large negative numbers, softmax converges toward one-hot vectors. Applying softmax to values close to zero produces a diffuse output. Multiplying the same values by eight makes softmax sharpen toward the largest entry. Extreme values make softmax too peaky, especially at initialization, so each node aggregates information from a single other node. That is not the goal. The scaling is used to control the variance at initialization.

Implementing a single self-attention head

The head module implements a single head of self-attention and takes a head size as input. It creates linear layers for the key, query, and value. Biases are typically omitted, and these linear projections apply to all nodes. The lower triangular matrix, tril, is not a parameter of the module. In PyTorch naming conventions it is a buffer, so it is assigned to the module with register_buffer. The forward pass takes the input x, computes keys and queries, calculates attention scores, normalizes them with scaled attention, and masks out future positions so that information flows only from the past. This makes the module a decoder block. Softmax is then applied, and the values are aggregated to produce the output.

Plugging attention into the language model

The language model creates a self-attention head in its constructor, called self attention head, and keeps the head size equal to the embedding size for now. Once the token and position embeddings encode the information, they feed into the self-attention head. Its output then goes into the language modeling head, which produces the logits. This is the simplest way to add a self-attention component to the network. The generate function also needs a change. Because position embeddings exist only up to block size, the index passed into the model must never exceed block size, or the position embedding table runs out of range. Code is added to crop the context so that no more than block size elements are passed in.

Training with self-attention

The learning rate is lowered because self-attention cannot tolerate very high learning rates. The number of iterations is increased to compensate for the lower rate. Validation loss improves from about 2.5 to about 2.4. The generated text is still not very good, but the self-attention head clearly performs useful communication, and there is still a long way to go.

Multi-head attention

Multi-head attention applies multiple attention heads in parallel and concatenates their results. In PyTorch, this is done by creating several heads, each with a specified head size, running them in parallel in a list, and concatenating all outputs over the channel dimension. Instead of one communication channel with a head size of 32, which matches the embedding size, the model uses four communication channels in parallel, each with a head size of eight. Their eight-dimensional outputs concatenate to 32, the original embedding size. This resembles a group convolution. Instead of one large convolution, the work is divided into groups.

Results and why multiple communication channels help

After switching to multiple heads, the validation loss drops to about 2.28. The generated output is still not impressive, but the validation loss clearly improves from 2.4. Multiple communication channels help because tokens have many different things to look for, such as consonants, vowels, or specific patterns from certain positions. Independent channels let the model gather different types of data and then decode the output.

Connecting the implementation to the Transformer architecture

The architecture figure in the paper shows components that are already implemented, including the positional encodings, the token encodings that are added together, and the masked multi-head attention. Another multi-head attention block performs cross-attention to an encoder. That part is not implemented in this project and will be covered later. The figure also includes a feed-forward part, grouped into a block that repeats many times. The position-wise feed-forward network is a simple multi-layer perceptron.

Adding per-token computation with a feed-forward layer

Before this change, the self-attention layers handled communication, but the tokens moved to the logits too quickly and had little time to process what they had found from other tokens. The feed-forward layer addresses this. It is a single layer consisting of a linear transformation followed by a ReLU nonlinearity. It runs right after self-attention, and it operates on a per-token level, so each token processes independently. Self-attention handles communication, and the feed-forward layer lets each token think on the data it has gathered.

Feed-forward results and the path to blocks

With the feed-forward layer added, validation loss continues to fall, reaching about 2.24 from 2.28. The output still looks poor, but the situation is improving. The next step interleaves communication with computation, as the Transformer does with blocks that communicate and then compute, grouped and replicated.

Building Transformer blocks

A block consists of communication followed by computation. Communication uses multi-head self-attention, and computation uses a feed-forward network applied to all tokens independently. The block takes the number of embeddings and the number of heads as inputs. With 32 embeddings and four heads, the head size is eight, which keeps the channel dimensions consistent. This is how the Transformer typically structures its sizes. Blocks are then created by applying them sequentially, so that communication and feed-forward computation are interspersed many times before the final decoding.

Optimization problems in deep networks

Running the stacked blocks does not produce very good results. The network is becoming deep, and deep neural networks suffer from optimization issues. Starting to run into those issues is a sign that another idea from the Transformer paper is needed. Two optimizations dramatically help with the depth of these networks and keep them optimizable.

Skip connections

The first optimization is shown by the arrows in the diagram. These are skip connections, sometimes called residual connections. The next part explains how they work.

Residual connections

Residual connections, also called skip connections, come from the 2015 paper Deep Residual Learning for Image Recognition, which introduced the concept. Data is transformed by a block, and the result is then added to the features that entered the block, so the original features carry forward through a skip connection combined by addition. A preferred way to visualize this has computation flowing from top to bottom. A residual pathway runs down the side, and the network can fork off from that pathway to perform some computation before projecting back onto it through addition. Inputs therefore travel to the targets through a sequence of additions.

Why residual connections help gradients

This design is useful during backpropagation. As covered in the micrograd video, addition distributes gradients equally to each of its inputs. The gradient from the loss therefore hops through every addition node all the way back to the input while also forking into the residual blocks. The result is a gradient superhighway that runs directly from the supervision to the input, unimpeded.

Residual blocks start with little influence

The residual blocks are usually initialized so that they contribute very little, if anything, to the residual pathway. At initialization they are almost not there. During optimization they gradually come online and begin contributing. Because the gradient path from the supervision to the input is unobstructed at initialization, the blocks can be phased in over time without blocking optimization. This dramatically helps optimization.

Adding residual connections to the block

To implement this, the block computes x plus self-attention applied to x, and then x plus the feedforward network applied to that result. Each step forks off from the residual pathway, performs some communication or computation, and returns to the pathway.

Projection layers

A projection layer is also needed. After the heads are concatenated, the output of multi-headed self-attention passes through an nn.Linear projection, a linear transformation that maps the result back into the residual pathway. The feedforward network receives the same treatment, with its own projection layer returning to the residual pathway. A projection for self-attention could be added in the same way, but it is simplified here by placing the feedforward network and its projection inside the same sequential container.

Widening the feedforward layer and early results

The paper uses 512 dimensions for the input and output, and its inner feedforward layer has 2048 dimensions, a multiplier of four. To match this, the inner layer of the feedforward network is multiplied by four in channel size. The feedforward uses four times n_embed, and the projection returns it to n_embed. This adds computation and grows the layer on the residual side. Training with these changes brings validation loss down to 2.08. The network is also becoming large enough that training loss runs ahead of validation loss, a sign of slight overfitting. Generated text is still not amazing, but it starts to look like English.

Layer norm and its relation to batch norm

The second innovation, also very helpful for optimizing very deep neural networks, is layer norm, which appears in the Add and Norm step. Layer norm is implemented in PyTorch and comes from a paper published earlier. It is very similar to batch norm. In the makemore series, batch normalization ensured that, across the batch dimension, each individual neuron had a unit Gaussian distribution, with zero mean and unit standard deviation.

Implementing layer norm from batch norm

The batch norm implementation from makemore is copied over. A module can be initialized and fed a batch of 32 vectors with 100 dimensions. Batch norm guarantees that each column, such as the zeroth column, has zero mean and unit standard deviation, so every column of the input is normalized. Rows are not normalized by default because only columns are. To implement layer norm, the normalization dimension is changed from zero to one. The columns are then no longer normalized, but the rows are, so each individual example's 100-dimensional vector is normalized.

Removing running buffers

Because the computation no longer spans across examples, the buffers can be deleted. The operation can always be applied to a single example, so running statistics are unnecessary. There is no distinction between training and test time, and no momentum is needed. Gamma and beta remain as learnable parameters. The resulting layer norm normalizes rows instead of columns.

Pre-norm placement in the Transformer

Few details of the Transformer have changed in the last five years, but one placement departs from the original paper. In the original, Add and Norm is applied after the transformation. It has become more common to apply layer norm before the transformation, which is called the pre-norm formulation. This is the version implemented here. Two layer norms are therefore needed, and they are applied directly to x: one before self-attention and one before the feedforward network.

Dimensions and behavior of the layer norms

Each layer norm is sized to the embedding dimension, which is 32 here. The mean and variance are computed over those 32 numbers, so the batch and time dimensions both act as batch dimensions. This makes the layer norm a per-token transformation that normalizes the features to unit mean and unit standard deviation at initialization. Because the layer norms contain gamma and beta training parameters, their outputs may not stay unit Gaussian. Optimization determines what the outputs become.

Training results and the final layer norm

Training with the layer norms reaches a validation loss of 2.06, a slight improvement over 2.08. The gains would likely be larger with bigger and deeper networks. A layer norm is also typically placed at the end of the Transformer, right before the final linear layer that decodes into the vocabulary, and it is added here. At this stage the Transformer is fairly complete according to the original paper. It is a decoder-only Transformer, a point discussed shortly, and the major pieces are in place, so the model can be scaled up.

Scaling up the model

Several cosmetic changes make the code cleaner for scaling. A variable called n_layer specifies how many blocks to create, and a number of heads variable is added. The layer norm is pulled out into its own place, and the structure is otherwise identical. One notable new addition is dropout.

Where dropout is applied

Dropout can be added right before each residual connection returns to the residual pathway. It can be applied at the end of the multi-headed attention and when computing affinities after the softmax. In the attention step, some of these values can be dropped out, which randomly prevents some nodes from communicating.

How dropout works

Dropout comes from a paper from around 2014. During each forward and backward pass, it randomly shuts off a subset of neurons by setting them to zero, and training proceeds without them. Because the dropped-out mask changes on every pass, it effectively trains an ensemble of subnetworks. At test time everything is enabled, which merges those subnetworks into a single ensemble. The full details are in the original paper. Here dropout is treated as a regularization technique, added because the model is about to be scaled up considerably and overfitting is a concern.

Updated hyperparameters

Several hyperparameters change with the larger model. The batch size increases to 64. The block size rises to 256, so the model uses 256 characters of context to predict the 257th, up from eight characters. The learning rate is reduced slightly because the network is much bigger. The embedding dimension is 384 with six heads, so each head is 64-dimensional, which is standard. There are six layers, and dropout is set to 0.2, meaning that on each forward and backward pass 20 percent of intermediate calculations are disabled and set to zero.

Results of the scaled model

The scaled model reaches a validation loss of 1.48, a substantial improvement from 2.07. This gain comes from scaling up the network with the existing code. Training ran much longer, likely about 15 minutes on an A100 GPU. Reproducing this on a CPU, or on a laptop such as a MacBook, would not be practical. The number of layers and the embedding dimension would need to be reduced. Even so, in about 15 minutes this kind of result is achievable. Samples of Shakespeare-style text are printed next.

Printing Longer Generated Samples

Beyond the snippet shown earlier, a longer sample of about 10,000 characters was also generated and written to a file. Its output is much more recognizable as the input text, which is a file of Shakespeare. The original input has a consistent pattern of someone speaking in a particular manner, and the model's predictions now take on that same form. However, the text is nonsensical when read closely, with lines like "every crimp tap be a house" and "Oho sent me you mighty Lord." This is expected, because the model is a Transformer trained at the character level on about 1 million characters from Shakespeare. It produces Shakespeare-like babble, but it does not make sense at this scale. Even so, it is a good demonstration of what is possible.

Decoder-Only Versus Encoder-Decoder Architecture

This concludes the programming section. The implementation of the Transformer works, but the architecture diagram from the original paper looks different from what was built, so it is worth explaining why. The model implemented here is a decoder-only Transformer. It has no encoder, and its blocks contain only self-attention and feed-forward layers. The middle cross-attention block, which attends to encoder outputs, is missing. The decoder-only design fits this task because the model simply generates text unconditionally, continuing a given dataset without any input to condition on. What makes it a decoder is the triangular mask applied in attention. That mask gives the model its autoregressive property, allowing it to sample from it one token at a time. This makes it suitable for language modeling. The original paper had an encoder-decoder architecture because it was a machine translation paper. Its setting is different: it reads a source sentence, such as French, and decodes a translation, such as English. The decoder starts generation from a special start token and ends with an end token. The decoding part works just as implemented here, but the output is conditioned on the French sentence. The encoder reads the French sentence, creates tokens from it, and runs a Transformer over them without a triangular mask, so all tokens can attend to each other freely. The encoder's outputs feed into every block of the decoder through a cross-attention layer. Queries still come from the decoder, while keys and values come from the encoder. This lets the decoding depend both on what has been generated so far and on the fully encoded French input. That is why the encoder-decoder model has the extra components. Since this project has nothing to encode and only imitates a text file, it uses a decoder-only Transformer, as GPT does.

Walking Through the nanoGPT Codebase

nanoGPT, available on GitHub, is a small codebase with two main files. The first, train.py, contains the boilerplate for training the network. It includes the training loop from this project, but it is more complex because it saves and loads checkpoints and pretrained weights, decays the learning rate, compiles the model, and supports distributed training across multiple nodes or GPUs. The second file, model.py, is very similar to the code built in this video, and the model is almost identical. The causal self-attention block in model.py follows the same steps: producing queries, keys, and values, computing dot products, masking, applying softmax, optionally applying dropout, and aggregating the values. The main difference is that the multi-head attention is batched. Instead of separate single heads that are concatenated explicitly, all heads are handled inside one causal self-attention module. This adds a fourth dimension for heads, so the tensors become four-dimensional. The math is equivalent, but it is more efficient because the heads are treated as an extra batch dimension. The multilayer perceptron uses the GELU nonlinearity instead of ReLU. This choice was made because OpenAI used GELU, and using it allows nanoGPT to load their checkpoints. The Transformer blocks are identical to the ones built here. The GPT module likewise matches: position and token embeddings, the blocks, a final layer norm, and a final linear layer. There is some extra code for loading checkpoints and separating parameters into those that should receive weight decay and those that should not. The generate function is also very similar. A few details differ, but a viewer should be able to read these files and understand the pieces.

Pretraining Stage of ChatGPT

To bring this back to ChatGPT, training one involves roughly two stages. The first is pretraining, and the second is fine-tuning. In pretraining, a decoder-only Transformer is trained on a large chunk of the internet so that it learns to babble text. This is similar to what was done here, except on a much smaller scale. The small model built in this project has about 10 million parameters, and it was trained on a dataset of roughly 1 million characters. OpenAI uses a different vocabulary. Rather than individual characters, it uses subword chunks, with a vocabulary of roughly 50,000 elements. Its sequences are therefore more condensed. The Shakespeare dataset would be around 300,000 tokens in OpenAI's vocabulary. So a model with about 10 million parameters was trained on roughly 300,000 tokens. The GPT-3 paper trained Transformers of several sizes, and the largest has 175 billion parameters. The hyperparameters, including the number of layers, the number of heads, the head size, the batch size, and the learning rate, are recognizable and similar to those used here. GPT-3 was trained on 300 billion tokens, which is roughly a millionfold increase over the Shakespeare dataset. By today's standards, even that is not especially large, since training runs now go to a trillion tokens and beyond. The architecture is nearly identical to what was implemented here, but training at this scale is a major infrastructure challenge. It typically requires thousands of GPUs communicating with each other. After pretraining, the model does not answer questions helpfully. It becomes a document completer. It babbles, but instead of Shakespeare, it babbles internet text, producing arbitrary news articles and documents. Since it is trained to complete sequences, a question may simply be followed by more questions, or the model may ignore the question and continue some related document it saw in training. The resulting behavior is essentially undefined.

Fine-Tuning Stage to Create an Assistant

The second stage, fine-tuning, aligns the model to behave as an assistant. OpenAI's ChatGPT blog post describes this stage, which involves roughly three steps. First, training data is collected that looks specifically like what an assistant would produce. These are documents formatted with a question at the top and an answer below. The number of these examples is probably in the thousands rather than on the order of the internet. The model is then fine-tuned to focus only on documents that look like this. Over time, it learns to expect a question at the top and to complete an answer. Very large models are sample efficient during fine-tuning, so this approach works. This description covers only the first step, which is the fine-tuning itself.

Reward Model and Reinforcement Learning Stage

The second step begins once the model can respond to questions. The model generates several responses, and human raters rank them by preference, indicating which response is better than another. These rankings are used to train a separate reward model, a different neural network that predicts how desirable any candidate response is. Once the reward model exists, PPO (Proximal Policy Optimization), a form of policy gradient reinforcement learning, fine-tunes the sampling policy. The goal is for the answers ChatGPT generates to be expected to score highly under the reward model. This alignment or fine-tuning stage has multiple steps, and it is what turns the model from a document completer into a question answerer. Much of the data used here is not publicly available. It is internal to OpenAI, which makes this stage much harder to replicate. Taken together, these stages produce something like ChatGPT, while nanoGPT focuses only on the pre-training stage. The lecture then summarizes what was built. The model is a decoder-only Transformer, following the 2017 paper "Attention Is All You Need," which makes it essentially a GPT. It was trained on Tiny Shakespeare and produced sensible results. The full training code is roughly 200 lines. The codebase will be released along with its git log commits, showing how it was built step by step, and the Google Colab notebook will also be released. The architecture is basically identical to models like GPT-3, which are somewhere between 10,000 and 1 million times larger, depending on how you count. The lecture did not cover the fine-tuning stages that typically follow pre-training. Those stages are needed whenever the goal goes beyond language modeling, such as performing tasks, aligning behavior in a specific way, or detecting sentiment. Any time the model should do more than complete documents, further fine-tuning is required. This can be simple supervised fine-tuning, or more involved approaches like those used in ChatGPT, which train a reward model and then run rounds of PPO to align the model with it. A great deal more can be built on top of this foundation. The lecture closes at roughly the two-hour mark.

Turn your watchlist into a reading routine

Bring your YouTube videos together, read summaries with key passages marked, and explore the full transcript. Save your own highlights with Pro.

Start with 5 free batteries. Each covers up to 30 minutes of a new summary.

New summaries depend on video availability and demand; processing may take time or require retry.