ReaderTube

AI summary

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

This video is a hands-on guide to language models, aimed at people who want to use them through code, with some deep learning background helpful but not required. It explains that a language model predicts the next token in a sequence, and that training in stages, from pretraining on large text collections through instruction tuning and preference-based fine-tuning, turns that raw prediction ability into a useful assistant. It then covers practical concerns, including GPT-4's strengths and failure modes, prompting tactics such as custom instructions, API costs and rate limits, building a function-calling code interpreter, and running open models locally on rented or owned GPUs. The guide ends by arguing that retrieval-augmented generation and fine-tuning are useful ways to ground models in private data, and by encouraging hands-on experimentation with the fast.ai community.

Introduction to Language Models

This is a hacker's guide to language models, taking a code-first approach to understanding how to use them in practice. Some familiarity with deep learning helps, and the first five lessons of the free course at course.fast.ai cover the fundamentals well, but a reader without that background can still gain a lot. This is less a formal tutorial than a quick run-through of the basic ideas behind language models, covering both open source models and OpenAI-based ones, with as much code as possible.

What a Language Model Does

A language model knows how to predict the next word of a sentence or fill in missing words. OpenAI's text-davinci-003 is one example. When given a passage, it predicts what words are likely to come next. For instance, given the prompt 'When I arrived back at the panda breeding facility after the extraordinary reign of live frogs I couldn't believe what I saw,' the model continues the story. Prompts like this suit creative brainstorming. The nat.dev site lets users experiment with a range of language models. With text-davinci-003 selected and the prompt submitted, the model generates: 'The pandas were happily playing and eating the frogs that had fallen from the sky. It's an amazing sight to see these animals taking advantage of such a unique opportunity, first after quick measures to ensure the safety of the pandas and the frogs.'

Probabilities Behind Each Word

The nat.dev interface can show the probability of each possible next word. After a panda breeding facility context, 'the' is very likely to come next, and 'Pandas were' is a likely continuation. Several verbs could follow, such as 'happily,' 'playing,' 'hopping,' or 'eating.' The model assigns a probability to each candidate. 'Happily' had roughly a 20 percent probability and was the most likely choice, so the model selected it. Depending on the settings, the model can always pick the most likely word, or parameters such as P values and temperature can be adjusted to change the output. Each run can produce a different result, such as frogs perched on the heads of some of the pandas. In every case, the model is predicting a probability distribution over many possible next words.

From Words to Tokens

Language models do not always predict whole words. In the example, the model predicts 'panned' and then, separately, 'us' after 'Panda,' showing that a word can be split across predictions. What the model actually predicts are tokens, which are either whole words or subword units, such as pieces of a word. Tokens can also be punctuation, numbers, and so forth. Tokenization converts a string into tokens. Using the tiktoken library, the same tokenizer that GPT models use can be applied, specifically the one used by text-davinci-003. When the phrase 'they are splashing' is encoded, the result is a list of numbers. Each number is a lookup into a vocabulary that OpenAI created. Training one's own models creates a vocabulary automatically. Decoding those numbers returns the pieces 'they,' ' are,' and ' splashing.' The space before a word is encoded as part of the token as well.

Why Language Models Need Further Training

Language models are remarkable that they work at all, but they are not designed to do anything useful on their own. In Howard's account, the approach behind systems like ChatGPT, GPT-4, and Bard comes from a 2017 algorithm called ULMFiT, which Howard developed. Howard and Sebastian Ruder wrote up the approach in early 2018, and it laid out the basic structure that many current systems follow. The approach has three steps. The first is language model training, which the paper calls pre-training. This step teaches the model to predict the next word of a sentence. The second is language model fine-tuning, and the third is classifier fine-tuning, which targets the final task.

Pre-Training on Wikipedia

In the original ULMFiT work, the language model was trained on Wikipedia. The model is a neural network, which is essentially a flexible mathematical function with many parameters. It cannot initially do anything useful, but stochastic gradient descent (SGD) can teach it almost anything given enough examples. Each training example is a sentence from Wikipedia cut off before its final word. For example, from the article on The Birds: 'The Birds is a 1963 American natural horror thriller film produced and directed by Alfred,' and the model must guess the next word. Guessing 'Hitchcock' earns a reward, while any other guess is penalized. Training effectively searches for a set of weights that makes the correct prediction more likely. Later in the same article, a sentence reads that a relationship ended due to Mitch's cold, overbearing mother Lydia, who dislikes any woman in Mitch's life. Many words could logically fit there, such as a woman in Mitch's closet or in his house. Filling the gap well requires thoughtful reasoning, and the correct answer is 'any woman in Mitch's life.'

Next-Word Prediction Requires World Knowledge

To predict the next word well across many sentences, a neural network must learn a great deal about the world. It learns that objects exist, that time exists, and that objects react to each other over time. It learns that movies have directors, that people have names, and that Alfred Hitchcock was a movie director who made horror films. Deep neural networks can build a rich hierarchy of abstractions and representations that later layers draw on. When this approach was created, the model had around 100 million parameters, and today's models have billions. The key idea is that predicting the next word of any sentence in any situation requires extensive knowledge of the world. That knowledge includes solving math questions, working out the next move in a chess game, and recognizing poetry. Nobody guarantees that a model will do this well, and building one that does takes a lot of work. A model that performs well, however, has many internal capabilities that it can draw on.

Compression and Intelligence

In Howard's view, next-word prediction is a form of compression. The relationship between compression and intelligence goes back many decades. If a model can guess which words come next, it effectively compresses all that information into a neural network. Compression alone is not especially useful, though. The capabilities compressed inside the network have to be pulled out, and that requires two more steps.

Language Model Fine-Tuning

The second step is language model fine-tuning. The model is no longer trained only on Wikipedia. Today, a large chunk of the internet is used for pre-training. In fine-tuning, the model is fed a set of documents much closer to the final task it should perform. It still works by predicting the next word of a sentence.

Classifier Fine-Tuning and Instruction Tuning

The third step is classifier fine-tuning, which targets the end task the model is meant to perform. Today, the second step usually takes a particular form called instruction tuning. The most common goal is to solve problems and answer questions. Instruction tuning therefore uses datasets such as OpenOrca, which is built on top of the Flan collection and was created by a well-known open source group. It contains roughly four gigabytes of questions, context, and related material. Each example generally includes a question, an instruction, or a request, along with a response.

Examples of Instruction Tuning Data

Examples from the Flan dataset, which is likely the source here, show the variety of tasks. One asks whether a sentence about the Iron Age answers the question: the period from 1200 to 1000 BCE is known as what, with the choices one or two, or yes or no. The language model writes the appropriate answer. Another example, likely drawn from a music video, asks who the girl in the video is. The model must write the correct name of the model or dancer from that video. Fine-tuning and pre-training are still fundamentally the same kind of language modeling, but this stage is more targeted. It goes beyond filling in the missing parts of any document from the internet.

Instruction Tuning for Useful Tasks

The goal now shifts from filling in the missing parts of any internet document to filling in the words needed to answer questions and perform useful tasks. This is instruction tuning, the second step. The third step is classifier fine-tuning, which commonly uses approaches such as reinforcement learning from human feedback (RLHF) and related methods. In these methods, humans, or sometimes more advanced models, compare multiple candidate answers to a question. For example, a prompt might ask for five ideas for regaining enthusiasm for one's career. The model produces two possible answers, or a weaker model and a stronger model each produce an answer, and a human or a better model picks the best one. This preference signal is used for the final fine-tuning stage.

Why Fine-Tuning Matters

Pure language models can be downloaded from the internet, but they are generally not very useful on their own until they have been fine-tuned. The classifier fine-tuning stage is not always necessary. Researchers are finding that instruction tuning alone may be enough, though this remains somewhat controversial.

What Counts as a Language Model

The term language model can refer to a model that has only been pre-trained, a model that has been fine-tuned, or a model that has gone through a process such as RLHF. Nowadays all of these are generally described as language models.

Using the Best Available Model

In this view, being good at language modeling starts with being an effective user of language models, which requires using the best one available. As of September 2023, GPT-4 is by far the best, though this might change in the not too distant future. GPT-4 is a strong recommendation. It can be accessed through a $20 monthly subscription to OpenAI, and it is very hard to run out of credits.

Common Claims About GPT-4's Limits

It is useful to start with the common views found online and in academia about what GPT-4 cannot do. Such claims need careful checking. A paper titled 'GPT-4 Can't Reason' reports empirical analysis of 25 diverse reasoning problems, finding that the model could not solve them and is incapable of reasoning. The author of this view appears to have checked the first three problems from that paper directly against GPT-4. GPT-4's share button produces a shareable transcript of each chat, which makes results easy to document.

Checking a Medical Riddle

When the first three problems from the paper were tested on GPT-4, the model handled them. One example reads: Mabel's heart rate at 9:00 a.m. was 75 beats per minute, her blood pressure at 7 p.m. was 120 over 80, she died at 11 p.m., and she arrived at noon. GPT-4 recognized the prompt as a riddle rather than a real medical inquiry, summarized the information, and concluded that Mabel was alive at noon, which is correct.

A Second Claim That Fails Under Testing

A second problem from the same paper, which claims GPT-4 cannot solve it, was also tested, and GPT-4 could solve it. This suggests GPT-4 is probably much better than internet commentary about its mistakes would imply. Nearly every time a claim circulates online that GPT-4 can't do something, checking it tends to show the claim is wrong.

The Sally Riddle

A recent example asks: Sally is a girl with three brothers, and each brother has two sisters. How many sisters does Sally have? GPT-4 reasons that Sally counts as one of the sisters for each brother. If each brother has two sisters, there must be another sister in the family besides Sally, so Sally has one sister. This answer is correct.

The Diamond in the Cup

A common view holds that language models cannot track objects through a sequence of changes. A riddle tests this. A diamond sits in a thimble inside a coffee cup on a chair in the living room. The chair is moved to the bedroom, the cup is placed on the bed and turned upside down, then turned upright and placed on the kitchen counter. GPT-4 answers that turning the cup upside down probably dropped the diamond, so the diamond is in the bedroom where it fell. This answer is also correct, and the model produced it only a few days before this was recorded.

Why Models Appear to Fail

Claims that GPT-4 can't do these things likely stem from a lack of awareness of how it was trained. GPT-4 was never trained to give correct answers. Its initial training taught it to predict the most likely next words, and much of the internet is not true. It contains fiction, jokes, and people saying foolish things. As a result, this first stage does not necessarily produce correct answers.

Preference Data and Confidence

The instruction tuning stage does aim for correct answers, but a problem arises when people are asked which answer they prefer. Those people tended to prefer more confident answers, and they were often not trained well enough to recognize wrong ones. As a result, the weight updates from this process do not entirely reward correct answers. There are many reasons for this, but the model can still be guided toward giving correct answers.

Priming the Model Through Pretraining Signals

Thinking about pretraining shows which features of a document signal high-quality information. Those same signals can be used to prime GPT-4 to give high-quality answers, through custom instructions.

How Custom Instructions Work

Custom instructions are text prepended to all of a user's queries. For example, a user can write that the model is brilliant at reasoning to prime it toward good answers. They can also counter the confidence bias from RLHF by telling the model to say so when there may not be a correct answer.

Why Longer Output Helps

Text generation works by producing one word, appending it to the input, and then generating the next word. The more words the model generates, the more computation it performs. For this reason, custom instructions can tell the model to first spend a few sentences explaining background and context before answering. This allows it to solve more challenging problems.

Pandas Example and Brevity Mode

Asking how to get a count of rows grouped by value in pandas produces a long response, which is effectively the model's own working. That working can be skipped to reach the final answer. Custom instructions can also request brevity: if a request begins with VV, the model gives the most concise answer possible. Adding VV to the same question produces a brief answer right away. A simple question like this needs no extra thinking time.

Getting Good Answers Requires Help

Getting good answers from language models takes active help from the user. If a model is not working well, the cause may be user error. Still, there are many things language models like GPT-4 cannot do. One thing worth checking is whether the model knows about itself, such as its context length, how it was trained, or which Transformer architecture it is based on. The model could not have learned these facts at any training stage.

Limits of Self-Knowledge

The pretraining stage could not have included information about GPT-4's training, since nothing on the internet described it during GPT-4's training. The instruction tuning and RLHF stages probably did not include it either. In general, a language model cannot be relied on for accurate facts about itself. Because of RLHF, it still wants to make the user happy, so it gives opinionated answers and produces the most likely response with great confidence.

Hallucination and Unknown URLs

This behavior is hallucination: the model wants to complete the text in an opinionated way that is likely to please people. The model does not know anything about URLs, because it has seen very few of them, and most were likely stripped out of its training data. If asked what is on a given webpage, it will generally make up an answer.

The Knowledge Cutoff

GPT-4 does not know anything after September 2021. Its pretraining data came from that period and earlier, and this boundary is called the knowledge cutoff.

A Modified River Crossing Puzzle

Steve Newman sent a logic puzzle that resembles the classic river crossing problem: carry a cabbage, a goat, and a wolf across a river, one item at a time, without leaving the goat with the cabbage or the cabbage with the wolf. The classic puzzle is so well known that it has its own Wikipedia page, and in it the wolf eats the goat or the goat eats the cabbage. In Steve's version, the goat eats the cabbage and the wolf eats the cabbage, but the wolf won't eat the goat.

Overwhelmed by Familiar Patterns

GPT-4 fails here because language model training has exposed it to the classic puzzle so many times that it confidently predicts the familiar next words. It proposes taking the goat across and leaving it on the other side, leaving the wolf with the cabbage, even though the prompt states that the wolf cannot be left with the cabbage. The answer is therefore wrong.

Retrying Through a Multi-Stage Conversation

The model can be encouraged to try again. Instruction tuning and RLHF use multi-stage conversations, so a user can ask it to repeat back the constraints. When asked what happened after the first step, the model admits that a constraint was violated, apologizes, and proposes a new plan. That plan repeats the same mistake, leaving the goat with the cabbage or the cabbage with the wolf.

Repeated Errors and Compounding Mistakes

The model's later attempts still break the constraints, with one proposal taking the wolf across and leaving the goat with the cabbage, and another proposing to take the goat across the other side, which fails again. This happens because the internet contains many examples of flawed reasoning. When a web page is wrong, it is often followed by more wrong content. Once GPT-4 starts being wrong, it tends to become more wrong, and it is very hard to turn it around and make it right. So you actually have to go back and there's actually

Fixing a mistake by editing the prompt

When a model has made a mistake, the usual advice is not to ask it for more information to correct itself. Instead, go back and use the edit button on the earlier message, then change the prompt there. This way the model does not carry the wrong answer forward and get confused. Fixing the Steve example took considerable effort, but eventually the model was made to answer correctly. The approach that worked was to warn it that people often read too quickly and get tricked by patterns, then present the tricky puzzle. Custom instructions that encourage the model to discuss the problem at length also helped. In the end, the model took the cabbage across first and solved the puzzle. Getting there required a lot of effort, because once a model has been primed to answer a certain way again and again, it is very hard for it to break that pattern.

Advanced Data Analysis and its limits

Advanced Data Analysis, which can write and run code on your behalf, is a useful feature. It is worth learning how to use it before building similar tools from scratch. In one example, the goal was to split a document into third-level markdown headings, meaning lines beginning with three hashes. Because regular expressions were slow on the whole of Wikipedia, the model was asked to speed up the code. It produced a solution and wrote test cases, but its tests showed that it was removing the carriage return at the end of each sentence. Each attempt to fix the code and tests produced another failed attempt, and the process went on for a long time. The author eventually stopped before a solution appeared. This shows that the model's logic has clear limits, even on a simple question. Advanced Data Analysis does not replace programmers, although it can accomplish a great deal in many tasks.

Extracting text from images

Advanced Data Analysis can also handle images. A user can upload a screenshot, and the model can extract the text from it. In this example, the model recognized that it could use OCR and wrote an OCR script that produced the text within seconds. The task did not demand much new reasoning. It relied on a familiar pattern the model had seen many times. Language models generally perform best when a task does not require thinking far outside the box. They are strong at code across many libraries and languages, and they are good at creative work. They are weaker at reasoning and logic that falls outside familiar patterns. Google's language model, Bard, is considerably less capable than GPT-4 in most cases. However, it lets users paste an image straight into the prompt. When asked to perform OCR, it returned the result without using code, commented on the output, and even identified where the OCR text came from and linked to it.

Creating a pricing table from the OpenAI website

The OpenAI pricing information was scattered across several separate tables on the webpage, which made it hard to compare costs. To combine it, the page was selected in full and pasted into ChatGPT, with a prompt asking for a table of the pricing information. The prompt specified no summarization, no information that was not on the page, and a separate row for every entry. Pasting the whole page brought in navigation bars and footers, which made the task harder, yet ChatGPT produced a correct markdown table on the first attempt. The table was then copied into Jupyter. At a glance, it showed the cost of GPT-4 and GPT-3.5. The table was then charted from its input-row values, which the model also handled well.

Understanding API pricing and token costs

ChatGPT costs $20 a month with no per-token charge. Using the API from Python or other code, however, is billed per token. A token is roughly a word, and on average there are about one and a third tokens per word. In the pricing table, GPT-4 costs far more than GPT-3.5. The GPT-4 input price is $0.03 per thousand tokens, while GPT-3.5 is $0.0015 per thousand tokens, so GPT-3.5 is much cheaper. Because it is so inexpensive, it is easy to experiment with. The API is useful when the work needs to be done programmatically, such as analyzing datasets, handling repetitive tasks, or a different style of programming for tasks that can be described clearly.

A basic API call with a system message

The simplest API example starts by installing the OpenAI package and importing the chat completion function. A call to chat completion create specifies GPT-3.5 Turbo and passes an array of messages. The first message is the system message, which works much like custom instructions. In this example, the system prompt asks the model to act as an Australian LLM that uses Aussie slang and analogies wherever possible. The user message asks, "What is money?" The response returns a nested dictionary, and its message content explains money as the oil that keeps the economy's machinery running smoothly, comparing it to how a koala needs eucalyptus leaves. GPT-4 is far better at anything remotely challenging, but it is also much more expensive. A sensible rule of thumb is to try GPT-3.5 Turbo first, and to move to GPT-4 only if the results are not good enough.

Measuring cost and tracking usage

A helper function called response can print the nested result in a readable form. The result also includes a usage field showing the number of tokens used. In this example, the call used about 150 tokens. At $0.002 per thousand tokens for GPT-3.5, that comes to $0.0003, which is a very small amount. With GPT-4, the same call would cost about half a cent. Unless many thousands of GPT-4 calls are made, the cost will rarely reach even a few dollars, and GPT-3.5 is cheaper still. Even so, it is wise to watch spending, and OpenAI provides a usage page for tracking it.

How follow-up messages work

Follow-up messages in the same conversation work because the entire conversation is sent back to the model each time. The API stores no state on the server. In the example, the question was what "goat" means. The model answered that Michael Jordan is often called the GOAT for his exceptional skills, and that Elvis and the Beatles have also been called the GOAT because of their profound influence. A follow-up question asked which influences and achievements were meant, and the model clarified that it meant Elvis Presley and the Beatles. To demonstrate how this works, the previous assistant reply was changed to say that money is like kangaroos. The model then explained the analogy as if it were its own, describing how kangaroos hop around and carry their joeys in a pouch, just as money carries value. This shows that a conversation can be invented in full, since the model simply responds to whatever history it is given. A helper function was then created to combine the system prompt and user message and return the completion. Asked for the meaning of life, the model replied that it is like trying to catch a wave on a sunny day at Bondi Beach.

Rate limits and usage precautions

Several precautions apply when using the API. Usage should be monitored, especially when a request runs hundreds or thousands of times in a loop, to avoid spending too much money. Requests sent too quickly are another risk. Newly created accounts, particularly during their first day or two, are likely to hit API rate limits. Initially, the limit is quite low, at three requests per minute for free users. After the first 48 hours, the limit rises, and higher limits can always be requested. These limits matter because they affect the design of any function that calls the API repeatedly.

Handling Rate Limits

Rate limits need to be planned for, especially early on. Usage should be monitored when code makes hundreds or thousands of calls in a loop, both to avoid overspending and to avoid sending requests too quickly. New accounts are likely to hit API limits during the first day or two, because initial limits are fairly low, starting at three requests per minute for free users. Limits rise after the first 48 hours, and higher limits can be requested. For this reason, a helper function that manages rate limits is useful. One approach is to ask Bing, which runs a somewhat limited version of GPT-4 but can still handle basic tasks for free, to write Python code that calls the OpenAI API and handles rate limits. The code it produced checks for rate-limit errors, reads the retry-after value, sleeps for that long, and then calls itself again. With that in place, a question such as 'what's the world's funniest joke' can be sent to the API and answered. These are the basics needed to start working with OpenAI LLMs, and spending plenty of time experimenting with them builds real fluency.

Introducing Function Calling

The next step is building a custom code interpreter that runs inside Jupyter. This relies on function calling, a feature provided by the OpenAI API. The ask_gpt function accepts keyword arguments, which are passed along to chat.completions.create. One of those arguments is functions, which tells OpenAI about the tools and functions available to the model.

Describing Functions with JSON Schema

As an example, a simple function called sums adds two numbers. A Python function cannot be passed to the API directly. Instead, it must be described with a JSON schema. A helper function built with Pydantic and Python's inspect module can take any Python function and generate its schema automatically. The schema tells the model the function's name, what it does, which parameters it takes, their default values, and which ones are required. This works quite differently from conventional programming, where the code itself is the main instruction. Here, the docstring is what GPT-4 reads to decide what a function does, so it must describe the function exactly.

When the Model Chooses to Call a Function

The model uses a function only when it judges one is needed. For a question like what is six plus three, it can answer directly without calling sums, so extra prompting was used to test the behavior. Describing this as the model 'feeling' that it needs a function is imprecise, but anthropomorphic language is hard to avoid, since these systems don't behave like normal computer programs. When the sums function is available, the response is not the number nine. Instead, it asks for a specific function to be called with specific arguments. A small helper handles this step. It reads the requested function call from the result, checks that the function name is on the allowed list, looks it up in the global namespace, and calls it with the given parameters. Calling the returned function produces nine.

A Python Execution Function

This example is not very useful on its own, but a more powerful function can be built: python, which executes Python code and returns the result. Running arbitrary code generated by the model without checking would be risky, so the approach adds a confirmation step before anything runs. With the python function available and a system prompt stating that Python may be used for required computations, asking for the factorial of 12 produces a request to call python with a specific argument. The code imports math, computes the factorial, and returns the result. Running the request gives the answer.

Returning Results in Chat Format

A raw result is sometimes less useful than a conversational answer. To get one, the full conversation is sent again, but instead of adding an assistant response, a message with the function role is added, containing the result returned by the function. The model then replies in prose: 12 factorial is equal to 479,001,600. Functions that are irrelevant to a question are simply ignored, so many custom tools can be available at once. The model answers whatever it can on its own and uses the available functions where they help.

Running Language Models Locally

This completes a code interpreter built from scratch, which shows some of what the OpenAI API can do. Running a language model on your own computer is another option, and it requires a GPU. Before choosing that route, it's worth asking whether it makes sense. No open-source models yet match GPT-4, and OpenAI's pricing is quite good, so moving in-house is not an obvious win. There are still good reasons to do it. These include asking questions about proprietary documents, working with information after the September 2021 knowledge cutoff, and building a model tuned for specific problems through fine-tuning. Each of these can be done at work or at home without large amounts of money or travel.

Renting GPU Access

Buying hardware isn't required, since GPU access can be rented or obtained for free. Kaggle provides a notebook with two fairly old GPUs and very little RAM. Colab offers better GPUs and more RAM, particularly with a monthly subscription. GPU server providers rent machines, and their offerings change often. RunPod is one example, where the largest machines cost roughly $3 to $4 an hour, though considerably cheaper options exist, around 80 cents an hour. Lambda Labs is often a good choice, but available machines are hard to find, and listings frequently show few or none free. Fast AI lets people use other people's computers when they are not in use. These machines tend to be cheaper and more available, but sensitive data should not be run on a stranger's machine.

Buying GPU Hardware

If possible, buying a GPU is worth considering. Currently, the best choice is a used RTX 3090, which can often be found on eBay for around $700. The newer RTX 4090 isn't much better for language models. Language model performance depends mainly on memory speed, meaning how quickly data moves in and out of memory, rather than processor speed, and memory speed has not improved much. Memory size matters too. At 24 GB, a single card often falls short, so two 3090s, around $1,500 in total, are usually the better setup. A 48 GB card such as the A6000 costs closer to $5,000, so two 3090s are still the better deal, and the A6000 isn't faster. A Mac with a large amount of unified memory is another option. An M2 Ultra, for example, may offer around 192 GB. It is much slower than an Nvidia card, but it is not a bad choice, particularly for running existing trained models rather than training new ones. Most people who work with these models seriously use video cards.

Hugging Face Transformers and Model Leaderboards

This work will use the Transformers library from Hugging Face. People upload many pretrained and fine-tuned models to the Hugging Face Hub, which also hosts leaderboards that rank them. Leaderboards are a tricky area. The model at the top of one may have the highest average score and may well be good, but that is not confirmed here. Benchmark metrics often do not reflect real-world usage well, for many reasons. Leaderboards are useful as a rule of thumb for choosing what to try, but models should always be tested directly.

Leakage and Reading Model Sizes

Leaderboard scores can also be distorted by leakage, which occurs when some benchmark questions appear in training data. Model names indicate size. A name with 70B means 70 billion parameters. For the kinds of GPUs under discussion, models of 13B parameters or smaller are the practical limit, and 7B models are often the right choice.

Evaluation Leaderboards and Choosing a Model

Models can be chosen from leaderboards like these. FastEval is preferred because it uses more sophisticated evaluation methods, such as chain-of-thought evaluation, so its results are considered more trustworthy. Its benchmarks include GSM8K, a difficult math test, and Big Bench Hard. Good options include Stable Beluga 2, WizardMath 13B, Dolphin LIMA 13B, and others. A model has to be picked, and nearly all strong current models are based on Meta's Llama 2.

Llama 2 Base Models

Models based on Llama carry the Llama name. For example, Llama 2 7B is Meta's second version of Llama at the 7-billion-parameter size, which is the smallest one Meta makes. These weights were prepared specifically for Hugging Face, so they can be loaded with the Hugging Face Transformers library.

Starting from a pretrained base model

The model being loaded has only completed the language model pretraining stage. It has not received instruction tuning or RLHF (reinforcement learning from human feedback), so it needs fine-tuning before it does anything useful. The language model stage corresponds to the first stage of the ULMFiT process. The model is Llama 2 7B, Meta's second version of Llama at its smallest, seven-billion-parameter size. The weights were packaged for Hugging Face, so they can be loaded with the Hugging Face Transformers library.

Memory requirements and 8-bit loading

Models are usually stored in 16-bit floating-point numbers. Each 16-bit value takes two bytes, so a 7-billion-parameter model needs about 14 gigabytes of memory just to load its weights. That makes a capable GPU necessary. Surprisingly, the weights can be cast to 8-bit precision and the model still works quite well, thanks to a technique called quantization. A language model of this kind only completes text, so it cannot be expected to answer a question well. Instead, the model is given the start of a sentence, such as 'Jeremy Howard is a'. The matching tokenizer is created automatically for the model, which converts the text into tokens.

Generating text one token at a time

The tokens are converted to PyTorch tensors. As a check, decoding them returns the original text along with a special token that marks the start of a document. Text generation is autoregressive: the model is called repeatedly, and each output is passed back in as the next input. In this example, the loop runs 15 times. Writing this loop by hand is a useful exercise for understanding how generation works, since the process involves no unusual tricks. The tokens must be moved to the GPU for processing, and the results are moved back to the CPU afterward.

Decoding the model's output

The raw output is a list of token IDs, which means little on its own. Decoding them with the tokenizer produces the first 15 tokens as readable text: 'Jeremy Howard is a 28 year old Australian AI researcher and entrepreneur.' The age is not exactly right, but the model is close enough, and the output reads as coherent text. At this stage, the model is completing sentences, not answering questions.

Speed gains from bfloat16

With 8-bit weights, generating the text took about 1.3 seconds. That is slower than it could be. Switching to bfloat16, a 16-bit floating-point format supported by most recent Nvidia GPUs, uses twice as much memory as 8-bit weights, but it reduces generation time to about 390 milliseconds.

GPTQ quantization

GPTQ is a more effective option. It is a quantization method in which a model is carefully optimized to run on 4-bit, 8-bit, or other low-precision data. Thanks to a user known as TheBloke, who regularly applies this optimization to popular models and uploads the results to Hugging Face, these quantized versions are easy to use. The 4-bit precision is likely used in this case, though the exact bit count is uncertain. Even so, the GPTQ version runs in about 270 milliseconds, which is faster than the 16-bit model. The model casts values up to 16-bit precision for each layer during computation, but it moves much less memory around, which makes the process faster overall.

Scaling up to a 13B GPTQ model

The GPTQ version also makes larger models practical. The 13-billion-parameter GPTQ model runs faster than the 7B model in 16-bit precision, which makes it a useful technique to know. The tokenizer, the generation loop, and the batch decoding are combined into a single function called gen. Using the 13B GPTQ model with the prompt 'Jeremy Howard is a' generates about 50 tokens. The output describes him as a 16-year veteran of Silicon Valley and co-founder of Kaggle, a marketplace for predictive models and a site that hosts data science competitions. Some details are wrong. He was at Kaggle for 10 years, not 16. Still, the output is on the right track.

Instruction-tuned models and the prompt format

For questions and instructions, a model that has been instruction-tuned is more useful. Stability AI's Stable Beluga series includes a 7B model and larger ones, all based on Llama 2. These models have been instruction-tuned, and they may also have been trained with RLHF. Instruction-tuned models expect input in a specific prompt format, and that format often differs from one fine-tune to another. The format is usually listed on the model's web page, so it must be checked there before use. Once the format is copied, a function called make_prompt can wrap each question in the same structure. Asking 'Who is Jeremy Howard?' through this function returns a response that includes a system instruction, the question, and the assistant's answer. The answer describes Jeremy Howard as an Australian entrepreneur, computer scientist, and co-founder of a machine learning and deep learning company, fast.ai. This answer is accurate, so the instruction-tuned model is clearly improving the results.

Using OpenOrca and Platypus fine-tunes

The next step is a larger model. The Llama 2 13B model has been fine-tuned on the OpenOrca dataset and then on another dataset called Platypus. Together, these produce the OpenOrca-Platypus model. The GPTQ version is quantized, so it uses its own prompt format. That format is also listed on the model's page and is wrapped in a function called make_open_orca_prompt. Asking 'Who is Jeremy Howard?' through this model produces a mixed answer. It says he is British, which is partly true, because he was born in England but moved to Australia. It also incorrectly describes him as a professional poker player, which is not true. The answer correctly mentions that he co-founded several companies, including fast.ai, and Kaggle. The model's claim that Kaggle was acquired by Google in 2017 is probably roughly correct.

The hallucination problem and retrieval-augmented generation

These models can provide useful information, but they still hallucinate. Llama 2 was likely trained on more recent information than GPT-4, which has a September 2021 knowledge cutoff, but it still has a cutoff. Ideally, a model should answer questions using the most current and relevant information available. Retrieval-augmented generation addresses this problem. When a question is asked, such as 'Who is Jeremy Howard?', the system first searches for documents that may help answer it. Wikipedia is an obvious source. The retrieved information is then passed to the language model along with the question, so that the model answers based on the found material.

Retrieving a Wikipedia page as context

To demonstrate, a Python package is used to scrape the Wikipedia page for Jeremy Howard. The page is about 613 words long. Open-source models usually have a context length of about 2,000 to 4,000 tokens, which is the maximum number of tokens they can process. The full page fits within that limit. The prompt is built in two parts. First, it instructs the model to answer the question with the help of the context. Next, it includes the whole Wikipedia page as the context, followed by the question. The prompt is much longer as a result, but the model handles it. The response describes Jeremy Howard as an Australian data scientist, entrepreneur, and educator known for his work in deep learning and for co-founding fast.ai. It also mentions that he teaches courses, develops software, and conducts research. The answer is accurate and well written. A reasonable 100-word biography would be hard to write better by hand. Although 300 tokens were allowed, the model emitted an end-of-stream token and stopped early.

Choosing the right document with sentence embeddings

A remaining question is how to choose which document to pass in. Another model can determine which document is most useful for answering a question. A sentence transformer is designed to convert a document into a set of activations, or embeddings, so that similar documents produce similar embeddings. A small example shows how this works. The first paragraph of the Jeremy Howard Wikipedia page and the first paragraph of the Tony Blair Wikipedia page are each encoded, along with the question 'Who is Jeremy Howard?'. Each encoding is a 384-length vector. The similarity between the question and the Jeremy Howard paragraph is higher than the similarity between the question and the Tony Blair paragraph. That means the Jeremy Howard page is the better document for answering the question.

Scaling retrieval with vector databases

With a few hundred candidate documents, each one can be encoded and compared to the question one at a time, and the closest match can be selected. With thousands or millions of documents, that approach becomes impractical. A vector database solves this problem. All documents are encoded once, and the vectors are stored so that searches are fast. Many prebuilt systems do this. One example is H2O GPT, an open-source application written in Python. It runs locally on port 7860, so it can be opened in a browser at localhost:7860. Documents can be uploaded through that interface.

Querying Uploaded Papers Locally

A batch of papers is uploaded through the local web interface by clicking upload. Once they are in, the system can search across them. For example, the ULMFiT paper by Howard and Ruder can be queried. The system converts the PDF into a rough text format and creates an embedding for each section. A question such as 'What is ULMFiT?' can then be asked. The model answers based on the retrieved context, and the interface shows the passages it was given as citations. In this case, the answer describes the three steps of ULMFiT: pre-training, fine-tuning the language model, and fine-tuning a classifier. The answer is reasonable but not outstanding, because the retrieved context is fairly small.

Limits of Follow-Up Questions

Follow-up questions work poorly in this setup. When the answer mentions fine-tuning a classifier, a follow-up such as 'What classifier is used?' fails because only the new question is sent to the embedding model. The earlier context about ULMFiT is lost, so the system has no idea what the question refers to. In one test, the system claimed the classifier was a RoBERTa model, but the cited sources no longer referred to Howard and Ruder. Retrieval only works well when each query stands on its own.

Retrieval-Augmented Generation and Private Options

This approach is called retrieval-augmented generation, or RAG. It is a useful technique, but it must be applied carefully. Many private GPT-style tools already exist, and the H2O GPT web page lists and compares many of them, so there is no shortage of options for running a private system with retrieval. The H2O GPT tool used in the demo is an open source Python application that runs locally on port 7860. Personally, it was only acceptable and not a favorite.

Fine-Tuning a Model on Documents

Fine-tuning offers a more powerful option. Rather than retrieving documents that may contain useful context, fine-tuning changes the model so that it behaves according to the documents available. The example uses a SQL dataset. Each entry includes a database table schema, a natural language question, and the correct SQL query that answers the question using that schema. The goal is a practical tool for business users, who could type a plain English question and receive generated SQL automatically. Whether this works reliably in practice is not yet known. Many startups are pursuing this idea more seriously, but the experiment was quick to build and worked within a couple of hours.

Loading the Dataset and Preparing Training

The Hugging Face datasets library loads the data. Just as the Hugging Face Hub stores models, it also stores datasets. Instead of the Transformers library, which loads models, the datasets library is used, and the name of the dataset's owner and repository is passed in. The dataset contains a training split with defined features, and a sample can be inspected directly. Writing a fine-tuning loop from scratch would take around 100 lines of code. Given the time constraints, a ready-made tool is a better choice. Axolotl is an open source tool that can be installed with pip. It supports features such as GPTQ and 16-bit training, so it is ready to use.

Configuring Axolotl and Training

Axolotl includes many example configurations for tasks it already supports, including Llama 2 examples. The Llama 2 example was copied and modified into a SQL example. The configuration points to the path of the SQL dataset and sets the data type, while most other settings are left as they were. Training is started with the accelerate launch command, passing in the YAML configuration file, as described in the project's readme. On a GPU, training took about an hour. The output was saved to a directory named with the prefix q, which stands for quantized, because a smaller quantized model was produced. LoRA, which is a separate technique, was not covered, but it reduces model size and allows larger models to be trained on smaller GPUs.

Testing the Fine-Tuned SQL Model

The trained model is tested with a prompt that provides contextual information, including a table creation statement, and asks a question: get the count of competition hosts by theme. No answer is supplied. The prompt format used by the training dataset is reproduced in a SQL prompt function. The instruction tells the model to use the contextual information to answer the question. The model generates the SQL query 'SELECT COUNT(hosts), theme FROM farm_competition GROUP BY theme', which is correct. The result is notable: in about two hours in total, including an hour to work out the method and an hour for training, a model was built that converts plain English questions into SQL based on a schema.

Running Models on a Mac

There are good options for running language models on a Mac. Two main choices are MLC and llama.cpp. MLC is underappreciated. It is a well-designed project that can run language models on iPhones, Android devices, and web browsers. A small Python program can run a quantized 7B model on a Mac, answering a question such as 'What is the meaning of life?' The answer is a thoughtful, philosophical response that mentions relationships and impact on the world. The model generates about 9.6 tokens per second. The tooling was installed only recently, and it was surprisingly easy to get working.

Using llama.cpp and Choosing a Setup

llama.cpp runs on many platforms, including Macs and CUDA GPUs. It uses the GGUF model format. A GGUF file can be downloaded from Hugging Face and loaded through the Python wrapper by passing the model path. The model prints a large amount of output during loading. A question such as 'Name the planets of the solar system' can then be answered with a set token limit, producing a list that includes Pluto is no longer considered a planet. For users with an Nvidia graphics card who are comfortable with Python, PyTorch and the Hugging Face ecosystem are the most common choice. These tools change quickly, however, and new developments are arriving fast.

Getting Started and Community Support

Language models offer many options right now, especially for experienced Python programmers. The field is exciting but frustrating at the moment. It is early, many features have odd edge cases, and installation can be tricky. Community help is valuable. The fast.ai community has a Discord server, which can be found by searching for fast AI Discord, with a channel called generative for questions and shared findings. People are still working things out together, so learning with others is important. The hope is that this provides a useful starting point for the journey.

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.