Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

State of GPT: Karpathy's Training Pipeline Explained

Andrej Karpathy's talk breaks down the four-stage training process for GPT assistants: pretraining, supervised fine-tuning (SFT), reward modeling, and reinforcement learning. It reveals how large language models work and how to use them effectively.

GPTKarpathytraining pipelinepretrainingsupervised fine-tuning

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

  • Speaker: Andrej Karpathy (Founding member of OpenAI, former Head of AI at Tesla)
  • Published: May 24, 2023
  • About this translation: In "A16Z's Recommended AI Learning Path", this talk was recommended as the second introductory article, which inspired this translation. During the process, I came across various translated and video versions online. This version is not perfect and can be compared with other versions. Please point out any errors — thank you.

[Image]

Chinese Translation

ANDREJ KARPATHY: Hello everyone, I'm excited to be here to talk to you about the state of GPT. More broadly, I want to talk about the rapidly evolving large language model (LLM) ecosystem. So I'd like to divide this talk into two parts:

  • In the first part, I want to show you how we train GPT assistants.

  • In the second part, we'll look at how to effectively use these assistants in your applications.

1. How to Train a GPT Assistant

First, let's take a look at the emerging recipe for training these assistants. Keep in mind that all of this is very new and therefore evolving rapidly. But so far, the recipe roughly looks like this:

[Figure]

Now this is a fairly complex slide, so I'll explain it step by step. Broadly speaking, we have four main stages: pretraining, supervised fine-tuning, reward modeling, and reinforcement learning. They are executed sequentially.

Now, in each stage, we have a dataset that supports that stage. We have an algorithm, which for us is an objective for training a neural network. Then we get a model. There are also some notes at the bottom.

[Figure]

Pretraining

So we'll start with the pretraining stage. Now, this stage is special in the diagram, and the diagram is not drawn to scale, because this is where essentially all the computational work happens. It accounts for 99% of the training compute time and FLOPs.

So, this is where we process internet-scale datasets, with thousands of GPUs in supercomputers, and it can take several months of training. The other three stages are fine-tuning stages, which are more about using a few GPUs for hours or days.

Now, let's look at how we get a base model through the pretraining stage.

First, we collect a large amount of data. Here is an example of what we call a data mixture, from a paper published by Meta, where they released the LLaMA base model.

[Figure]

Now, you can roughly see the types of datasets involved in these collections. We have Common Crawl, which is just a web crawl, and C4, also a Common Crawl, and then some high-quality datasets such as: GitHub, Wikipedia, Books, ArXiv, StackExchange, etc. These are all mixed together and sampled according to certain proportions, forming the training set for the GPT neural network.

Before we actually train on this data, we need a preprocessing step: tokenization. This basically translates the raw text we scraped from the internet into sequences of integers, which is the native representation that GPT operates on.

[Figure]

Now, this is a lossless transformation between text fragments, tokens, and integers. There are many algorithms for this stage. Typically, for example, you can use something like Byte Pair Encoding, which iteratively merges small text chunks and groups them into tokens. So, I'm showing some example chunks of these tokens here, and then this is the raw integer sequence that actually goes into the transformer.

Now, I'm showing two similar examples here, which are about the hyperparameters that control this stage.

[Figure]

For GPT-4, not much has been released about how it was trained, etc. So I'm using numbers from GPT-3, but GPT-3 is of course a bit old now, about three years ago. But LLaMA is a fairly recent model from Meta.

So, these are roughly the orders of magnitude we deal with when doing pretraining. The vocabulary size is typically 10,000 tokens. The context length is usually 2,000, 4,000, and now even 100,000. This determines the maximum number of integers that GPT looks at when trying to predict the next integer in the sequence.

You can see the approximate number of parameters, for example, LLaMA has 65 billion parameters. Now, even though compared to GPT-3's 175 billion parameters, LLaMA only has 65 billion, LLaMA is a significantly more powerful model. Intuitively, this is because the model was trained for much longer, in this case on 1.4 trillion tokens, not just 300 billion tokens. You cannot judge a model's power solely by the number of parameters it contains.

Below, I show a table of hyperparameters typically used to specify the Transformer neural network, (including) the number of heads, dimension size, number of layers, etc.

At the bottom, I show some training hyperparameters. For example, to train the 65B model, Meta used 2,000 GPUs, about 21 days of training time, and it cost roughly a few million dollars. So, these are the rough orders of magnitude you should keep in mind for the pretraining stage.

Now, what actually happens when we do pretraining? Roughly speaking, we will put our tokens into data batches. We have these arrays that will be fed into the transformer. These arrays are B—batch size, these are independent examples stacked row-wise, B times T, where T is the maximum context length.

[Figure]

In my picture, I only have 10, but this is the context length, so this number can be 2,000, 4,000, etc. These are very long rows. What we do is we take these documents, pack them into rows, and separate them with these special end-of-text tokens, basically telling the transformer where a new document starts.

Here, I have some example documents, and then I stretch them into this input. Now, we feed all these numbers into the transformer. Let me focus on a specific cell, but the same thing happens for every cell in this diagram.

[Figure]

So, let's look at the green cell. The green cell will look at all the tokens before it—here, all the yellow tokens. We feed the entire context into the transformer neural network. The transformer will try to predict the next token in the sequence, which in this example is the red one.

Now, regarding the transformer, I'm sorry I don't have much time to go into the details of this neural network architecture, but for our purposes, it's just a huge stack of neural network stuff, typically with tens of billions of parameters, or something like that.

Of course, when they adjust these parameters, the prediction distribution for each cell will be slightly different. For example, if our vocabulary size is 50,257 tokens, then we'll have that many numbers, because we need to specify a probability distribution for what comes next, so we basically have probabilities for everything that could possibly follow.

Now, in this particular example, for this specific cell, the next token is 513 (the red block in the image above). So we can use this as a supervision source to update our transformer weights. We basically apply this in parallel on every cell. We keep swapping batches, trying to get the transformer to correctly predict what the next token in the sequence is.

So, when you train one of these models, let me show you more concretely what that looks like. This is actually from The New York Times, where they trained a small GPT on Shakespeare's works. So here's a small snippet of Shakespeare, and they trained their GPT on it.

[Figure]

Now, at the beginning, the GPT starts with completely random weights, so you only get completely random outputs. But over time, as you train the GPT for longer and longer, you get increasingly coherent and consistent model samples.

Of course, the way to sample from it is to predict what comes next. You sample from this distribution and keep feeding it back into the process, and you can basically sample a large number of sequences.

So in the end, you'll see that the transformer has learned about words, where to put spaces, where to put commas, and so on. So over time, our predictions become more and more consistent.

When you're doing model pre-training, the kind of graph you look at is this one (see below). Essentially, we're observing how the loss function changes over time during training. A low loss means our transformer is predicting correctly—giving a higher probability to the correct next integer in the sequence.

[Figure]

So, after a month of training, how do we use this model? First, we notice that in this domain, these models, during the process of language modeling, have learned very powerful general-purpose representations, and they can be very effectively fine-tuned for any arbitrary downstream task you might be interested in.

[Figure]

For example, if you're interested in sentiment classification, the old approach was to collect a bunch of positive and negative sentiments and train an NLP model for that. But the new approach is to ignore sentiment classification, go do large-scale language model pre-training, train a big transformer, and then you only need a small number of examples to very effectively fine-tune your model for this task.

This approach works well in practice. The reason is that the transformer, during the language modeling task, is forced to handle a large number of tasks, because just in the process of predicting the next token, it has to understand a lot about the structure of the text and all the different concepts within it.

This was GPT-1.

Then, around GPT-2, people noticed that an even better approach than fine-tuning is that you can very effectively prompt these models. Because these are language models, they want to complete documents, so you can actually trick them into performing tasks by arranging these fake documents.

[Figure]

For example, in this case, we have some paragraphs, and then we do something like "Q&A, Q&A, Q&A" (this is called few-shot prompting, e.g., in the image above: "Q: How old is Catherine? A: 54"), and then we ask a question (in the image above: "where does she live?"), and when the transformer tries to complete the document, it actually answers our question. So this is an example of prompt engineering for a base model, making it think it's imitating a document and getting it to perform a task.

Therefore, I think this kicked off an era—I would say—where prompting outperformed fine-tuning, and we discovered that this can be very effective on many problems, even without training any neural network, without fine-tuning, etc.

[Figure]

Since then, we've seen the entire evolutionary tree of base models, and everyone has trained them. But not all of these models are available. For example, the GPT-4 base model was never released. The GPT-4 model you might interact with via the API is not a base model; it's an assistant model, and we'll discuss how to obtain these models later.

The GPT-3 base model was available via an API endpoint called DaVinci, and the GPT-2 base model is available as weights in our GitHub repository. But currently, the best available base model is probably Meta's LLaMA series, although it doesn't have a commercial license.

Now, it's worth pointing out that base models are not assistants (see the figure below). They don't want to answer your questions. They just want to complete documents. So if you tell them, "write a poem about bread and cheese," it will only—you know, it will respond to the question with more questions. It's just completing what it thinks is a document.

[Figure]

However, you can prompt the base model in specific ways that are more likely to work. So for example, here's a poem about bread and cheese, and in this case, it will correctly autocomplete.

You can even trick the base model into becoming an assistant. One way to do this is to create a specific few-shot prompt that looks like there's a document between a human and an assistant, and they are exchanging information.

[Figure]

Then at the bottom you put your query last, and the base model will condition itself to answer like a helpful assistant. But this isn't very reliable, and in practice it's not particularly effective, although it can be done.

So we have a different path to make a real GPT assistant, not just a document completer from a base model. This leads us to the Supervised Fine-Tuning stage.

Supervised Fine-Tuning Stage

[Figure]

In the Supervised Fine-Tuning stage, we will collect a small but high-quality dataset. In this case, we will ask human contractors to collect data of prompts and ideal responses. We'll collect a lot of these, typically tens of thousands or similar quantities.

Then we still perform language modeling on this data. So there's no change in the algorithm. We just swap out the training set. Before it was internet documents, which is large/low quality, now it's basically Q&A prompt-response type data, which is small/high quality.

So we still do language modeling. Then after training, we get an SFT model (Supervised Fine-Tuning model), which you can actually deploy, and these models are real assistants and are useful in a sense.

Let me show you what an example demonstration might look like. These are some random prompts that human contractors might come up with, like: "Can you write a short introduction to 'monopoly' in economics?" or something like that? Then the contractors also write out the ideal responses.

[Figure]

When they write out these responses, they are following a detailed labeling document, and they are asked to provide helpful, truthful, and harmless responses. These are the labeling instructions. You may not be able to read them clearly, and neither can I, but they are long. This is just the process of people following instructions to complete these prompts.

So this is what the dataset looks like. You can train these models, and this works to some extent.

Reward Modeling

Now, we can continue the pipeline from here into RLHF, which is "Reinforcement Learning from Human Feedback," and it consists of reward modeling and reinforcement learning.

Let me introduce them, and then I'll come back to discuss why you might want to do the additional steps, and how this differs from just using the SFT model.

[Figure]

In the reward modeling step, what we do is transform our data collection into a comparison format. Here's an example of our dataset. I have the same prompt at the top, asking the assistant to write a program or function that checks whether a given string is a palindrome (a word, sentence, or sequence of numbers that reads the same forward and backward).

[Figure]

Then what we do is take our already trained SFT model and create multiple completions. So in this example, we have three completions created by the model. Then we ask people to rank these completions.

[Figure]

If you stare at this for a while, by the way, comparing these predictions is very difficult, and it might even take people hours to compare a single prompt-completion pair. But suppose we decide one of them is much better than the others, and so on, so we rank them. Then we can formulate, for all possible pairs between these completions, something that looks very much like binary classification to perform the ranking.

[Figure]

So now what we're doing is lining up our prompts—the prompt is the same across all three rows. It's the same prompt, but the completions vary, so the yellow tokens come from the SFT model.

Then at the end we add a special reward readout token, and we basically only supervise this single green token's transformer, and the transformer will predict, for that prompt, how good this completion is.

So it basically makes a guess about the quality of each completion. Then once it has made guesses for all of them, we have the ground truth of how the model ranks them. So we can actually enforce that some of these numbers should be much higher than others, and so on. We formulate this as a loss function, and we train our model so that the model makes reward predictions that are consistent with the comparison ground truth data from human contractors.

This is how we train our reward model, which allows us to evaluate how good a completion is for any given prompt.

Reinforcement Learning

[Figure]

Once we have this reward model, we can't deploy it directly, because by itself it doesn't work well as an assistant, but it's very useful for the reinforcement learning stage that comes next. Because we have a reward model, we can score any completion for any given prompt.

So in the reinforcement learning process, what we do is basically take a large number of prompts again, and then we perform reinforcement learning based on the reward model.

How is this done? We take a single prompt, arrange it into rows, and now we use the SFT model. We use the model we want to train, initialized as the SFT model, to generate some yellow completions. Then we add the reward token again, read the reward from the reward model, and now the reward model is fixed and no longer changes.

[Figure]

Now, the reward model tells us the quality of each completion under each prompt. So what we can do now is apply the same language modeling loss function, but we are currently training on the yellow tokens. We weigh the language modeling objective according to the rewards indicated by the reward model.

For example (as shown in the figure above), in the first row, the reward model considers this a fairly high-scoring completion. Therefore, all the tokens we sampled in the first row will be reinforced, and they will have higher probabilities in the future. Conversely, in the second row, the reward model strongly dislikes this completion, giving it -1.2. Thus, every token we sampled in the second row will have slightly lower probabilities in the future. We repeat this process over many prompts and many batches. Essentially, we obtain a policy that generates these yellow tokens here, which are basically all the completions, and all these completions will score highly according to the reward model we trained in the previous stage.

This is how we train. This is the RLHF process.

[Figure]

Then finally, you get a model that can be deployed. For example, ChatGPT is an RLHF model, but you might encounter other models, such as Vicuna-13B (commonly known as the little alpaca model), etc., which are SFT models. We have base models, SFT models, and RLHF models—that's the current state.

Now you might ask why you would want to do RLHF? The answer may not be that exciting: it simply performs better.

[Figure]

This figure comes from the InstructGPT paper. Based on these experiments, which are a bit dated now, these PPO models are RLHF. We see that when presented to humans, they are preferred in many comparisons. Compared to the base model prompted as an assistant, and compared to the SFT model, humans basically prefer the tokens (output text) from the RLHF model. So, it just works better.

But you might ask why? Why does it work better? I don't think there's a surprising answer that the community fully agrees on, but I can offer a possible reason, related to the asymmetry in computational ease between comparison and generation.

Let's take generating a haiku as an example. Suppose I ask a model to write a haiku about a paperclip. If you are a contractor trying to provide training data, imagine being a contractor collecting SFT data. How would you create a good haiku about a paperclip? You might just not be good at it. But if I give you a few examples of haikus, you might be able to better appreciate some of them. Therefore, judging which one is good is an easier task. Basically, this asymmetry makes comparison a potentially better way to leverage your human judgment to create a slightly better model.

[Figure]

Now, RLHF models are not always an improvement over base models in all cases. In particular, we notice that, for example, RLHF loses some entropy. This means they can output samples with less variation; they can output samples with lower diversity than the base model. The base model has a lot of entropy and gives diverse outputs.

[Figure]

For example, I still prefer using the base model in certain situations, specifically when you have n things and you want to generate more things similar to them. Here's an example I just made up.

[Figure]

I want to generate cool Pokémon names. I give seven Pokémon names and ask the base model to complete the document. It gives me more Pokémon names. These are all made up—I tried to look them up, and I don't think these are real Pokémon. This is a task where I think the base model excels, because it still has a lot of entropy and gives you diverse, cool additional things that look like whatever you gave it before.

That said, these are the assistant models you can use now. A team at Berkeley ranked many available assistant models and assigned them ELO ratings.

[Figure]

Currently, some of the best models—of course, far ahead—are GPT-4, followed by Claude, GPT-3.5, and then some other models. Some may be available in the form of weights, like Vicuna, Koala, etc. The top three rows here are all RLHF models, while all the other models, to my knowledge, I believe are SFT models.

Okay, that's how we train these models at a high level. Now, I'm going to shift direction and look at how to best apply the GPT assistant model to your problems.

2. Applying the GPT Assistant Model to a Problem

Now, I'd like to demonstrate this with a concrete scenario. Let's use a specific example. Suppose you're writing an article or blog post, and you plan to end the article with a sentence like: "The population of California is 53 times that of Alaska." For some reason, you want to compare the populations of these two states.

[Figure]

Think about the rich inner dialogue and tool use happening in your mind, and how much computational work your brain is actually doing to generate that final sentence. Here's what your brain might be doing (how it might be running):

  • Okay, next step, let me write the blog post. Let me compare these two populations.

  • Okay, first of all, obviously, I need to get these two population figures.

  • Now, I know I probably won't know these population numbers off the top of my head, so I'm aware of what I know and what I don't know, right?

  • I use some tools, go to Wikipedia to check the population of California and the population of Alaska.

  • Now I know I should divide these two numbers, but I also know that trying to divide 39.2 by 0.74 in my head is probably not something I can do. This isn't something I can accomplish mentally.

  • So, I'm going to rely on a calculator. I'll use a calculator, input these two numbers, and see the result is approximately 53.

  • Then I might do some reflection and sanity-checking in my brain to see if the number 53 makes sense.

  • Wow, that's a big multiple, but California is the most populous state, so it might seem reasonable.

  • Then I have all the information I might need, and now I can move on to the creative part—the writing.

  • I might start writing something like, "The population of California is 53 times that of Alaska."

  • Then I realize, this is actually a pretty awkward way to say it. Let me delete that and try again.

  • So, as I write, I have a separate process that is almost checking what I'm writing, evaluating whether it looks good. Then maybe I'll delete, maybe I'll restructure the sentence, and then maybe I'll be satisfied with the result.

Basically, long story short, when you create a sentence like this, your inner monologue is doing a tremendous amount of work behind the scenes. But, when we're training GPT, what does a sentence like this look like?

[Figure]

From GPT's perspective, this is just a sequence of tokens. When GPT reads or generates these tokens, it simply processes them one by one, spending roughly the same amount of computational work on each chunk. And these transformers aren't very shallow networks. They have roughly 80 layers of reasoning capability, but 80 layers isn't that many. So, this transformer will do its best to imitate, but clearly, the process here looks very, very different from what you experience.

In particular, in our final product, in the dataset we create, and then ultimately fed into LLMs, all the internal dialogue is completely stripped away. Unlike you, GPT looks at each and every token and spends the same amount of computation on each one. So, you can't expect it to actually—well, you can't expect it to do too much work on each token.

And, in particular, basically these transformers are like token simulators. They don't know what they don't know. They just imitate the next token. They don't know what they're good at or bad at. They simply do their best to imitate the next token. They don't reflect in a loop. They don't do any sanity-checking. By default, they don't correct their own errors in the process. They just sample token sequences. There's no separate stream of inner monologue in their brain, right? They are evaluating what's happening.

However, I would say they do have some cognitive advantages, namely that they actually have a very large base of factual knowledge covering a wide range of domains, because they have tens of billions of parameters. This is a huge storage space for storing a large amount of facts, and I think they also have a relatively large and perfectly working memory. Whatever fits within the context window is immediately available to the transformer through its internal self-attention mechanism. So, it's kind of like a perfect memory, but its size is limited. However, the transformer can access it directly. So, it can losslessly remember anything within its context window.

This is how I compare the two. The reason I'm bringing all this up is because I think to a large extent, prompting is just about compensating for the cognitive differences between these two architectures (our brain and the large language model's brain). You could almost look at it from this perspective.

For example, people have found that one thing works pretty well in practice. Especially if your task requires reasoning, you can't expect the transformer to do too much reasoning on each token. So, you have to really spread the reasoning out across more and more tokens. For example, you can't give a transformer a very complex problem and expect it to arrive at the answer in one token. There's just not enough time for it. These transformers need tokens to "think," which I sometimes like to put it that way.

[Figure]

So, these are some methods that have proven to work. For example, you might have some few-shot prompts that tell the transformer it should show its work when answering a question. If you give it a few examples, the transformer will imitate that template, and will ultimately perform better in terms of evaluation.

Additionally, you can elicit this behavior from a Transformer by saying "let's think step by step," because it puts the Transformer into a mode of showing its work. Since it enters a mode of demonstrating its process, its computational effort per token is reduced. As a result, the outcome is more likely to succeed because it is reasoning slowly.

Here's another example, called self-consistency.

[Image]

We've discovered that we have the ability to start writing, and if it doesn't succeed, we can try again. We can attempt multiple times and then perhaps choose the best one. In these methods, you might not just sample once, but multiple times, and then have some way to identify which ones are good, keep only those samples, or do majority voting, or something similar. Essentially, these Transformers, in the process of predicting the next token, just like you, can have bad luck. They might sample a not-so-good token and end up in a dead-end line of reasoning.

Therefore, unlike you, they cannot recover from it. They are stuck with every token they sample. So even if they know the sequence won't succeed, they continue with it. Giving them the ability to look back, check, or try to sample around is also a technique.

It turns out that, in fact, LLMs know when they've messed up.

[Image]

For example, suppose you ask the model to generate a poem that doesn't rhyme. It might give you a poem that actually does rhyme. But it turns out, especially for larger models like GPT-4, you can directly ask it, "Did you complete the task?" In fact, GPT-4 is very aware that it didn't complete the task. It was just a bit unlucky in its sampling. So it will tell you, "No, I actually didn't complete the task. Let me try again."

But without your prompt, it wouldn't even know. It doesn't know to reconsider, etc. You have to compensate for that in your prompt. You have to make it check. If you don't ask it to check, it won't check on its own. It's just a token simulator.

I think more generally, many of these techniques fall into what I call reconstructing our System 2. You might be familiar with the human System 1, System 2 way of thinking (see Daniel Kahneman's Thinking, Fast and Slow). System 1 is a fast, automatic process, which I think corresponds to LLMs sampling tokens. System 2 is the slower, more deliberate planning part of your brain.

[Image]

In fact, this is a paper from last week, because the field is moving very fast. It's called "Tree of Thought" (Tree of Thought). In "Tree of Thought," the authors propose maintaining multiple completions for any given prompt, scoring them throughout the process, and keeping those that are going well, if that makes sense. So many people are trying to use prompt engineering, essentially hoping to restore some of the capabilities our brains have.

Now, one point I want to make here is that this is not just a single prompt. It's actually a set of prompts used together with some Python glue code, because you have to maintain multiple prompts and also do some tree search algorithm to figure out which prompts to expand, etc. It's a symbiotic relationship between Python glue code and individual prompts, called in a while loop or within a larger algorithm.

I also think there's a very cool analogy here: AlphaGo. When playing Go, AlphaGo has a policy for placing the next stone, initially trained by imitating humans. But in addition to that policy, it also performs Monte Carlo tree search. Basically, it plays out some possibilities in its mind, evaluates them, and only keeps those that work well. So I think this is like the text version of AlphaGo, if that analogy makes sense.

Like "Tree of Thought," I think more generally, people are starting to explore not just simple question-and-answer prompts, but more general techniques that resemble Python glue code chaining multiple prompts together.

[Image]

On the right, I have an example from a paper called ReAct, where they structure the prompt's answer as a series of thoughts, actions, observations, thoughts, actions, observations. It's a comprehensive deduction, a thought process for answering a query. In these actions, the model is also allowed to use tools.

On the left is an example of Auto-GPT. By the way, the Auto-GPT project has been hyped recently, but I still find it very instructive. It's a project that allows an LLM to maintain a task list and recursively decompose tasks. I don't think it works well currently, and I don't recommend people use it in practical applications. I just think it's something to draw inspiration from, and I believe that inspiration will gradually emerge over time.

It's like giving our model a System 2 (slow thinking) way of thinking.

The next interesting thing I've found is, I'd say, a psychological quirk of LLMs: LLMs don't want to succeed. (Laughter) They just want to imitate. You want to succeed, you should ask for it. (Laughter)

[Image]

I mean, when transformers are trained, they have training sets. Their training data can contain a whole range of performance quality.

For example, there might be prompts about some physics problem or something similar, where there could be a completely wrong student answer, but also an extremely correct expert answer. Transformers cannot distinguish between low-quality and high-quality solutions—I mean, they know both solutions, but by default, they want to imitate all of them because they are simply trained as language models. So, at test time, you actually have to ask for good performance.

In the example from the paper above, they tried various prompts. "Let's think step by step" is very powerful because it spreads reasoning across many tokens. But an even better prompt is: "Let's solve this problem step by step, making sure we have the correct answer." So, this is somewhat like conditioning on getting the correct answer. This actually makes the transformer work better because now the transformer doesn't have to spread its probability mass over low-quality solutions, even though it sounds absurd.

So, basically, you can safely ask for a strong solution. Say things like "You are an authoritative expert on this topic," "Assume your IQ is over 120," and so on. But don't try to ask for too high an IQ, because if you ask for an IQ that's too high, you might go out of the data distribution, or worse, you might end up in the data distribution of some sci-fi content, and it will start doing some sci-fi role-playing or something like that. (Laughter) You have to find the right IQ—I think there's a U-shaped curve here.

Tools and Plugins

Next, as we've seen, when we try to solve problems, we know what we're good at and what we're not, and we rely on tools for calculations. You might want to do the same with your LLM. In particular, we might want to give them calculators, code interpreters, etc., as well as the ability to search. There are many techniques for doing this.

[Figure]

One thing to keep in mind again is that these transformers may not know what they don't know by default. You might even want to tell the transformer in the prompt, "You are not very good at mental arithmetic. Whenever you need to add, multiply, or do other operations with large numbers, use a calculator. Here's how to use the calculator: use this token combination, etc., etc." You really have to spell it out, because the model doesn't know what it's good or bad at by default, just like you and me.

Next, I think it's very interesting that we've moved from a world where we only retrieved information to one where we rely entirely on LLM memory. But actually, there's a whole space of retrieval-augmented models between these two extremes, and they perform very well in practice.

[Figure]

As I mentioned, the transformer's context window is its working memory. If you can load any task-relevant information into the working memory, the model will perform very well because it has immediate access to all that memory. So, I think many people are very interested in basic retrieval-augmented generation. At the bottom, I have an example using LLaMA Index, which has a data connector that can connect to various types of data. You can index all this data and make it accessible to the LLM.

The emerging recipe here is: you take relevant documents, split them into chunks, embed them all, and basically get embedding vectors representing that data. You store them in a vector store. Then at test time, you perform some query against your vector store. You retrieve chunks that might be relevant to your task, stuff them into the prompt, and generate. This can work quite well in practice.

This is similar to how we solve problems. You can rely entirely on your memory, and the transformer's memory is very powerful and extensive, but it's also helpful to reference some key documents. Whenever you find yourself needing to go back to a textbook or look up documentation for a library, the transformer needs to do the same. You have some memory of the library's documentation, but it's better to look it up. The same applies here.

Constrained Prompting

Next, I want to briefly talk about constrained prompting. I also find this very interesting. This is essentially a technique to force the LLM's output to conform to a certain template. Microsoft's Guidance project (https://github.com/microsoft/guidance) is an example. Here, we force the LLM's output to be JSON. This ensures the output will take that form because we intervene in the probabilities of all the different tokens coming out of the transformer and restrict those tokens. Then, the transformer only fills in the blanks. You can then enforce other constraints on those blank parts.

[Figure]

I think this can be very helpful, and I find this kind of constrained sampling very interesting as well.

Fine-Tuning

I also want to say a few words about fine-tuning. You can make a lot of progress with prompt engineering, but you might also consider fine-tuning your model.

[Figure]

Now, fine-tuning a model means you actually change the model's weights. Doing this in practice has become increasingly easier, thanks to many recently developed techniques and codebases built for them.

For example, parameter-efficient fine-tuning techniques like LoRA ensure that you only train a small, sparse subset of the model. Most of the model stays frozen in its base state, and only a small portion is allowed to change. In practice, this still works quite well, making it much cheaper to adjust only a small part of the model. Moreover, because most of your model is fixed, you can compute those parts with very low precision since they won’t be updated by gradient descent. This also makes the whole process more efficient.

Additionally, we have many open-source, high-quality base models, as I just mentioned. I think LLaMA is good, though I believe it doesn’t have a commercial license yet.

One thing to keep in mind is that, fundamentally, fine-tuning is technically more complex. It requires more technical expertise to get right. It needs datasets from human data contractors (and/or) potentially quite complex synthetic data pipelines. This will definitely slow down your iteration cycle significantly.

I’d say at a high level, SFT (Supervised Fine-Tuning) is feasible because you’re continuing the language modeling task, which is relatively straightforward. However, I would say RLHF (Reinforcement Learning from Human Feedback) is very much a research area and even harder to make work effectively. So, I probably wouldn’t recommend that someone try to build their own RLHF implementation. These things are very unstable, very difficult to train, and at the moment I don’t think they’re very beginner-friendly. And it’s likely still changing rapidly.

Default Recommendations

I think these are my current default recommendations. I would split your task into two main parts. First, achieve your best performance, and second, optimize your costs to bring them down, in that order.

[Figure]

  • First, the best performance currently comes from the GPT-4 model, which is by far the most capable model.

  • Use very detailed prompts that include task context, relevant information, and instructions. Think along these lines: if they couldn’t reply to your email, what would you tell them? But also remember that task contractors are humans, they have inner thoughts, they’re very smart, etc. LLMs don’t have those qualities, so make sure to almost account for the LLM’s psychology and design prompts accordingly.

  • Refer heavily to a wide range of prompt engineering techniques, retrieve and add any relevant context and information into those prompts. Some of these are highlighted in the slides above, but this is also a very large field, and I’d just recommend looking for prompt engineering techniques online—there’s a lot of content out there.

  • Try using few-shot prompts. This means you don’t just want to ask, you also want to show (what you want) as much as possible, give it examples, and if you can, help it truly understand what you mean.

  • Try using tools and plugins to offload tasks that are difficult for the LLM itself to handle.

  • Don’t just think about a single prompt and answer, but also consider potential chains and reflections, and how to glue them together, as well as how to create multiple samples, etc.

  • Finally, if you think you’ve maximized the effectiveness of prompt engineering, I think you should stick with it for a while, look at possibly fine-tuning a model for your application, but expect that to be slower and involve more work.

  • Then there’s an expert-level research area, which is RLHF, and if you can make it work, it currently does work a bit better than SFT. But again, I’d say it’s very complex. To optimize your costs, try exploring lower-capacity models or shorter prompts, etc.

Suitable Use Cases

I also want to say a few words about what I think LLMs are currently suitable for. Note in particular that today’s LLMs have many limitations, and I would keep this in mind for all applications. By the way, this could be a whole talk, so I don’t have time to go into detail.

[Figure]

Models can be biased. They can make things up, hallucinate information, they can have reasoning errors, and they can struggle across entire application categories. They have a knowledge cutoff, so they may not know anything about, say, events after September 2021. They are vulnerable to a wide range of attacks that are posted on Twitter every day, including prompt injection, jailbreaking attacks, data poisoning attacks, and so on.

My advice right now is to use LLMs in lower-risk applications, always combine them with human oversight, use them as a source of inspiration and suggestions, and consider usage patterns like copilots rather than fully autonomous agents performing tasks somewhere. It’s not yet clear whether the models are ready for that.

Conclusion

Finally, I want to say that GPT-4 is an incredible achievement. I am deeply grateful for its existence—it is beautiful.

[Image]

It possesses vast knowledge across many domains, capable of performing mathematical calculations, writing code, and more. Additionally, there is this thriving ecosystem where everything else is built and integrated into it, some of which I have already discussed. All these capabilities are at your fingertips, providing everything needed to ask GPT-4 questions, give it prompts, and receive responses.

[Image]

I asked GPT-4, "What can you say to inspire the audience at Microsoft Build 2023?"

[Image]

I simply typed this into Python, and GPT-4 responded verbatim with the following.

By the way, I had no idea they used this trick in the keynote, so I thought I was being clever (laughter). But it is really good at this.

[Image]

It said: "Ladies and gentlemen, innovators and pioneers of Microsoft Build 2023, welcome to this gathering of countless brilliant minds. You are the architects of the future, the visionaries shaping the digital realm upon which human prosperity depends. Embrace the boundless possibilities of technology, and let your ideas soar as high as your imagination. Together, let us create a more connected, exceptional, and inclusive world for generations to come. Prepare to unleash your creativity, explore the unknown, and turn your dreams into reality. Your journey begins today."

Thank you! (Applause)