ReaderTube

AI summary

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

Deep learning ideas, and the transformer architecture behind ChatGPT in particular, are explained here from the ground up. GPT stands for Generative Pretrained Transformer, and the model works by predicting the next token in a passage, then repeatedly sampling and appending tokens to generate longer text, with a system prompt and extra training turning that predictor into a chatbot. The chapter walks through the core mechanics: text is split into tokens and mapped to high-dimensional embedding vectors, which attention and feed-forward blocks progressively enrich with context, and a final unembedding matrix and softmax produce a probability distribution over possible next tokens, with temperature controlling how random the choice is. It ends by setting up the attention mechanism as the next step, after reviewing the foundations of machine learning, weighted sums, matrix multiplication, and softmax.

What GPT Stands For

The initials GPT stand for Generative Pretrained Transformer. The first word is straightforward: these are bots that generate new text. Pretrained refers to the model's process of learning from a massive amount of data, and the prefix suggests that the model can be fine-tuned on specific tasks with additional training. The last word is the real key. A transformer is a specific kind of neural network, a machine learning model, and it is the core invention underlying the current boom in AI. The explanation that follows is visually driven and walks step by step through what actually happens inside a transformer, following the data as it flows through the network.

Transformers Across Applications

Many different kinds of models can be built using transformers. Some take in audio and produce a transcript. Others work in the other direction, producing synthetic speech from text. Tools that took the world by storm in 2022, such as DALL-E and Midjourney, take in a text description and produce an image, and they are also based on transformers. Even when the generated image fails to capture what a pi creature is supposed to look like, it is remarkable that this kind of thing is even remotely possible.

Next-Word Prediction Models

The original transformer, introduced by Google in 2017, was designed to translate text from one language into another. The variant covered here, which underlies tools like ChatGPT, is trained to take in a piece of text, perhaps accompanied by surrounding images or sound, and produce a prediction for what comes next in the passage. That prediction takes the form of a probability distribution over many possible chunks of text that might follow.

Generating Text by Repeated Sampling

Predicting the next word may seem like a very different goal from generating new text. But once a prediction model like this exists, a simple way to produce a longer passage is to give it an initial snippet, have it take a random sample from the distribution it just generated, append that sample to the text, and then run the whole process again on the new, longer text. It may not feel intuitive that this should work. In one demonstration, GPT-2 running on a laptop repeatedly predicts and samples the next chunk of text to continue a story from seed text, and the resulting story does not make much sense. Swapping in API calls to GPT-3, which is the same basic model but much bigger, produces a sensible story that even seems to infer that a pi creature would live in a land of math and computation. This repeated prediction and sampling is essentially what happens when someone interacts with ChatGPT or other large language models, which produce one word at a time. Being able to see the underlying distribution behind each newly chosen word would be a welcome feature.

Tokens and Vector Embeddings

A high-level preview of how data flows through a transformer comes first, with each step explored in more detail later. When a chatbot generates a word, the input is first broken into small pieces called tokens. For text, tokens tend to be words, pieces of words, or other common character combinations. For images or sound, tokens could be small patches of the image or small chunks of the sound. Each token is then associated with a vector, a list of numbers meant to encode the meaning of that piece. If these vectors are viewed as coordinates in a very high dimensional space, words with similar meanings tend to land on vectors that are close to each other.

Attention and Feed-Forward Blocks

The sequence of vectors then passes through an attention block, which allows the vectors to talk to each other and pass information back and forth to update their values. For example, the word model means something different in a machine learning model than in a fashion model. The attention block determines which words in context are relevant to updating the meanings of which other words, and how those meanings should be updated. Meaning here is entirely encoded in the entries of the vectors. Next, the vectors pass through a different operation, known as a multi-layer perceptron or a feed-forward layer depending on the source. In this step the vectors do not talk to each other; they all go through the same operation in parallel. This block is harder to interpret, but it can be understood as something like asking a long list of questions about each vector and then updating the vectors based on the answers. Both kinds of blocks consist largely of matrix multiplications, and understanding how to read the underlying matrices is the main task ahead. Some normalization steps occur in between, which this high-level preview glosses over.

Repeated Layers and the Final Prediction

After this, the process essentially repeats, alternating between attention blocks and multi-layer perceptron blocks. The hope is that by the very end of the network, all the essential meaning of the passage has been baked into the last vector in the sequence. A specific operation on that last vector produces a probability distribution over all possible tokens, meaning all the small chunks of text that might come next.

From Next-Token Prediction to a Chatbot

Once a tool predicts what comes next given a snippet of text, it can be fed a little seed text and repeatedly predict, sample from the distribution, append the sample, and repeat. Before ChatGPT, early demos of GPT-3 worked this way: they autocompleted stories and essays from an initial snippet. Turning such a tool into a chatbot starts with a bit of text that establishes the setting, a user interacting with a helpful AI assistant, which is called the system prompt. The user's initial question then serves as the first piece of dialogue, and the model predicts what such a helpful assistant would say in response. Making this work well requires an added step of training, which is discussed later.

Chapter Roadmap and Series Context

This chapter expands on what happens at the very beginning and the very end of the network, and it reviews background knowledge that would have been second nature to any machine learning engineer by the time transformers arrived. Readers already comfortable with that background may skip ahead to the next chapter, which focuses on attention blocks, generally considered the heart of the transformer. Later material covers the multi-layer perceptron blocks, how training works, and other details skipped up to that point. This chapter is part of a mini-series on deep learning. Earlier entries are not required, and the chapters can be followed out of order. Still, before diving into transformers specifically, it is worth making sure the basic premise and structure of deep learning are clear.

Machine Learning and Tunable Parameters

Deep learning is one approach to machine learning, which describes any model whose behavior is determined using data. Consider a function that takes in an image and produces a label describing it, the next-word prediction task described above, or any other task that requires intuition and pattern recognition. Earlier AI efforts tried to explicitly define in code a procedure for each such task. Machine learning takes a different path: a very flexible structure with tunable parameters, like a bunch of knobs and dials, is set up, and many examples of the desired output for a given input are used to tweak those parameters until the model mimics the behavior. Even the simplest form, linear regression, follows this pattern. With inputs and outputs that are single numbers, such as a house's square footage and its price, the goal is to find a line of best fit for predicting future prices. That line is described by two continuous parameters, the slope and the y-intercept, and linear regression determines those parameters to closely match the data.

Scaling Deep Learning Models

Deep learning models are far more complicated than linear regression. GPT-3, for example, has 175 billion parameters rather than two. It is not a given that such a giant model can be built without grossly overfitting the training data or becoming intractable to train. Still, deep learning describes a class of models that over the last couple of decades have proven to scale remarkably well. What unifies them is that they all use the same training algorithm, backpropagation, which was covered in earlier chapters. For this algorithm to work well at scale, these models have to follow a specific format. Knowing that format helps explain many of the choices in how a transformer processes language, choices that might otherwise seem arbitrary.

Required Format: Arrays, Layers, and Weights

First, whatever kind of model is being built, its input has to be formatted as an array of real numbers. This could be a simple list of numbers or a two-dimensional array, and very often the arrays are higher dimensional, in which case the general term is tensor. Input data is progressively transformed through many distinct layers, and each layer is again structured as some kind of array of real numbers, until a final layer is reached and treated as the output. In the text model, the final layer is a list of numbers representing the probability distribution over all possible next tokens. In deep learning, the model parameters are almost always called weights, because the only way these parameters interact with the data being processed is through weighted sums. Non-linear functions are sprinkled throughout, but they do not depend on parameters. Typically, these weighted sums are not written out explicitly but are packaged together as various...

Weighted Sums in Matrix Form

Each layer of the network is an array of real numbers, and the final layer produces the output. In a text-processing model, that output is a list of numbers giving the probability distribution over all possible next tokens. In deep learning, the model's parameters are almost always called weights, because the only way these parameters interact with the data being processed is through weighted sums. Non-linear functions appear throughout the network as well, but they do not depend on any parameters. Weighted sums are usually packaged together as components of a matrix-vector product rather than written out individually. This is the same computation, since each component of the output in a matrix-vector product is a weighted sum. Thinking in terms of matrices filled with tunable parameters that transform vectors drawn from the data is often conceptually cleaner.

The Weight Count in GPT-3

The 175 billion weights in GPT-3 are organized into just under 28,000 distinct matrices. These matrices fall into eight categories, and each category can be examined in turn to understand what that type of matrix does. Referencing GPT-3's specific numbers makes it possible to count exactly where the 175 billion weights come from. Although larger and more capable models exist today, GPT-3 holds a special place as the first large language model to capture the world's attention beyond machine learning communities. Companies also tend to keep the specific numbers for more modern networks much more closely guarded.

Matrix-Vector Multiplication Throughout the Model

Nearly all of the actual computation inside a tool like ChatGPT is matrix-vector multiplication. Because there is a risk of getting lost among billions of numbers, it helps to draw a sharp distinction between two things. The first is the weights of the model, which are always colored blue or red in visualizations. The second is the data being processed, which is always colored gray.

Weights Versus Data

The weights are the model's actual brains. They are learned during training and determine how the model behaves. The data being processed simply encodes the specific input fed into the model for a given run, such as an example snippet of text.

Breaking Input into Tokens

The first step in the text-processing example is to break the input into small chunks and convert those chunks into vectors. These chunks are called tokens, and they may be pieces of words or punctuation. In this chapter and the next, it is simpler to pretend that the input is split cleanly into words. Humans think in words, so this makes it much easier to reference small examples and clarify each step.

The Vocabulary and the Embedding Matrix

The model has a predefined vocabulary, which is a list of all possible words, perhaps 50,000 of them. The first matrix encountered in the process is the embedding matrix, which has a single column for each word in the vocabulary. Each column determines the vector that its word turns into in this first step. The matrix is labeled W_E. Like every matrix in the model, its values start out random and are learned from data. Turning words into vectors was common practice in machine learning long before transformers, and it sets the foundation for everything that follows.

Words as Points in High-Dimensional Space

Word embeddings are often described geometrically, as points in a high-dimensional space. A list of three numbers can be visualized as coordinates in 3D space, but word embeddings are far higher dimensional. In GPT-3, each embedding has 12,288 dimensions. Working in a space with many distinct directions matters for the model's behavior.

Projecting Embeddings and Semantic Directions

Because high-dimensional embeddings cannot be displayed directly, a three-dimensional slice is chosen and the word vectors are projected onto it, much like projecting points from a 3D space onto a 2D slice. As a model adjusts its weights during training to determine how words are embedded, it tends to settle on embeddings in which directions in the space carry a kind of semantic meaning. In a simple word-to-vector model, the words whose embeddings are closest to that of tower all share very similar tower-like associations. This simple model is not a transformer, but it illustrates the idea that directions in the space can carry semantic meaning.

Analogies in Embedding Space

A classic example is that the difference between the vectors for woman and man is very similar to the difference between king and queen. If someone did not know the word for a female monarch, it could be found by starting at king, adding the woman-minus-man direction, and searching for the embedding closest to that point. This works only approximately. The true embedding of queen sits a bit farther away than this suggests, probably because the word queen is used in training data in ways that go beyond being a feminine version of king. Family relations illustrate the idea more clearly. The model appears to have found it advantageous during training to choose embeddings in which one direction encodes gender information.

Gender and Nationality Directions

Another example is that taking the embedding of Italy, subtracting the embedding of Germany, and adding the result to the embedding of Hitler produces a vector very close to the embedding of Mussolini. The model seems to have learned to associate some directions with Italian-ness and others with leaders of the Axis powers in World War II.

Surprising Nearest Neighbors

In some models, taking the difference between Germany and Japan and adding it to sushi lands very close to bratwurst, which is one of the more striking examples of this effect. Searching for nearest neighbors also shows that cat is close to both beast and monster.

The Dot Product as a Measure of Alignment

The dot product of two vectors measures how well they align. Computationally, a dot product multiplies corresponding components and adds the results, which suits a network built largely on weighted sums. Geometrically, the dot product is positive when vectors point in similar directions, zero when they are perpendicular, and negative when they point in opposite directions.

Testing a Plurality Direction

Suppose a hypothesis is that the embedding of cats minus cat represents a plurality direction in the space. To test it, this vector can be dotted with the embeddings of various singular nouns and compared with the dot products for the corresponding plural nouns. The plural nouns consistently give higher values, indicating that they align more closely with this direction. Dot products with the embeddings of the words one, two, three, and so on produce increasing values, which means the degree of plurality the model assigns to a word can be measured quantitatively. The specifics of how words are embedded are learned from data.

Counting the Embedding Matrix Weights

The embedding matrix, whose columns determine what happens to each word, is the first set of weights in the model. Using GPT-3's numbers, the vocabulary size is 50,257. Technically, this vocabulary consists of tokens rather than words. The embedding dimension is 12,288. Multiplying these gives about 617 million weights. This count goes into a running tally that should reach 175 billion by the end.

Vectors That Absorb Context

With transformers, the vectors in the embedding space should not be thought of only as representing individual words. These vectors also encode the position of each word, which is discussed later. More importantly, they have the capacity to absorb context. A vector that begins as the embedding of king, for example, may be progressively adjusted by the blocks in the network. By the end, it points in a much more specific direction that encodes that this is a king who lived in Scotland, who gained his post by murdering the previous king, and who is being described in Shakespearean language.

Meaning Shaped by Surroundings

The meaning of a word is clearly shaped by its surroundings, sometimes including context from far away. A model that predicts the next word must therefore be able to incorporate context efficiently. In the very first step, when the array of vectors is created from the input text, each vector is simply taken from the embedding matrix. Initially, each one can only encode the meaning of a single word, with no input from its surroundings. The primary goal of the network is to enable each vector to absorb a meaning that is much richer and more specific than an individual word could represent.

The Context Size Limit

The network can process only a fixed number of vectors at a time, known as its context size. GPT-3 was trained with a context size of 2048, so the data flowing through the network always takes the form of an array of 2048 columns, each with 12,000 dimensions. The context size limits how much text the transformer can use when predicting the next word. This explains why long conversations with certain chatbots, such as early versions of ChatGPT, often felt as though the bot was losing the thread as the conversation went on.

Producing a Probability Distribution at the Output

At the end of the network, the desired output is a probability distribution over all tokens that might come next. For example, if the last word is Professor, and the context includes Harry Potter and the phrase least favorite teacher, a well-trained network with knowledge of Harry Potter would likely assign a high value to the word Snape. This involves two steps. First, another matrix maps the last vector in the context to a list of 50,000 values, one for each token in the vocabulary. Then a function called softmax normalizes these values into a probability distribution.

Why Only the Final Vector Is Not Used Alone

It may seem odd to use only the last embedding to make a prediction, since many other vectors in the final layer carry their own context-rich meanings. In training, however, it is much more efficient to use each vector in the final layer to simultaneously predict the token that would come immediately after it. More about training is covered later. The matrix that maps final vectors to vocabulary values is called the Unembedding matrix and is labeled W_U. Like all the weight matrices

Unembedding matrix and parameter count

Like every other weight matrix, the unembedding matrix starts with random entries, which are refined during training. It has one row for each word in the vocabulary, and each row has the same number of elements as the embedding dimension. It mirrors the embedding matrix with the order reversed, adding roughly 617 million parameters to the network. With that, the running total is a little over a billion, a small but not negligible fraction of the 175 billion parameters the full model will contain.

Softmax as a probability distribution

Softmax is the final mini-lesson for this chapter. It matters again later, when the attention blocks are introduced. To treat a sequence of numbers as a probability distribution, such as one over all possible next words, every value must lie between 0 and 1, and the values must sum to 1. The raw outputs of the matrix-vector multiplications used throughout deep learning satisfy neither condition. They are often negative or much larger than 1, and they rarely sum to 1. Softmax is the standard way to convert an arbitrary list of numbers into a valid distribution, pushing the largest values close to 1 and the smaller values very close to 0. Computing it takes two steps. First, each number is raised to the power of e, which yields a list of positive values. Then each term is divided by the sum of those values, normalizing the list so it adds up to 1. If one input is meaningfully larger than the rest, its term dominates the output, so sampling from the distribution would almost certainly return the maximizing input. Softmax is softer than a hard maximum, though. When several values are similarly large, each receives meaningful weight, and the output changes continuously as the inputs change.

Temperature and controlling randomness

When a system like ChatGPT uses this distribution to choose the next word, a temperature parameter T can be added to the exponents in the denominator. The name is borrowed loosely from the role of temperature in certain thermodynamics equations. A larger T gives more weight to the lower values, making the distribution more uniform. A smaller T lets the larger values dominate more aggressively. At the extreme, setting T to zero sends all of the weight to the maximum value. As an example, GPT-3 can be asked to continue the seed text "once upon a time there was A" at different temperatures. At temperature zero, it always picks the most predictable word, and the result is a trite derivative of Goldilocks. A higher temperature lets it choose less likely words, which makes the story more original at first, about a young web artist from South Korea, but it quickly degenerates into nonsense. The API does not allow a temperature above 2. That limit has no mathematical basis. It is an arbitrary constraint meant to keep the tool from producing overly nonsensical output. The animation in this example works by taking the 20 most probable next tokens that GPT-3 generates, which appears to be the maximum the API will return, and adjusting their probabilities using an exponent of 1/5.

Logits and the chapter's foundations

Just as the outputs of softmax are called probabilities, its inputs are commonly called logits. When text is fed into the network, the word embeddings pass through the layers, and the final multiplication with the unembedding matrix produces raw, unnormalized scores. In machine learning, these components of the raw output are called the logits for the next-word prediction. This chapter aimed to build the foundations needed to understand the attention mechanism. That requires a solid intuition for word embeddings, for softmax, for how dot products measure similarity, and for the premise that most calculations take the form of matrix multiplication with matrices full of tunable parameters. With those in place, the attention mechanism, a cornerstone of the modern boom in AI, should be relatively approachable. A draft of the next chapter is available for review by Patreon supporters. A public version is expected within a week or two, depending on how much changes after that review. Viewers who want to learn about attention, or who want to support the channel, can do so in the meantime.

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.