Skip to main content

What Is a Large Language Model (LLM)?

A large language model, or LLM, is a program that does one thing: for the text it's given, it works out how likely each possible next piece of text is. Pick one of those pieces, add it to the text, ask again, and the model writes. The AI models behind chat assistants such as ChatGPT, Claude and Gemini are LLMs. This page explains what's inside one, shows a tiny language model in a few lines of Python and a small real one that I trained on a laptop, and maps every concept of an LLM to the tutorial in this track that teaches it. By the end of the track, you'll have built and trained your own.

What a Large Language Model Does​

The name has three parts. Read from the back, they are:

  • Model: a calculation whose numbers were learned from examples, instead of rules that a person wrote. Those learned numbers are called parameters.
  • Language model: a model of text. Its one job is to say what's likely to come next. Given The fish likes to, a good one says that swim is far more likely than sing.
  • Large: it has a lot of parameters, and it learned them from a lot of text.

How much is a lot? GPT-2, a model that OpenAI released in 2019 for anyone to download, makes a good yardstick. Its model card lists four sizes: 1.5 billion parameters: the fourth and largest GPT-2 version. We have also released 124 million, 355 million, and 774 million parameter models. The paper behind it says the text it learned from came to slightly over 8 million documents for a total of 40 GB of text. No rule says where "large" begins, and many newer models are much bigger than GPT-2. They're built from the same parts, though, which is why this track can teach those parts on a model small enough for a laptop.

The same paper puts its idea in one line: At the core of our approach is language modeling. Its title says what came out of that: Language Models are Unsupervised Multitask Learners. A model trained only to continue text began to answer questions, translate and summarize, without being trained for any of those tasks.

What an LLM Isn't​

  • It isn't a database. An LLM doesn't keep the texts it learned from and look answers up in them. It keeps parameters, and it computes every next piece of text from them. That's why it can write a sentence nobody has written before, and also why it can say something false in the same confident tone. OpenAI's model card for GPT-2 is plain about it: Because large-scale language models like GPT-2 do not distinguish fact from fiction, we don’t support use-cases that require the generated text to be true.
  • It isn't a set of rules. Nobody typed grammar or facts into it. Everything it does comes from its parameters, and training on text set those.
  • It has no memory of its own. The parameters don't change while the model is used. A chat seems to remember because the application sends the whole conversation back to the model with every new message.

Where It Comes From​

Almost every LLM today is a transformer. That's a design for a neural network, which is a calculation made of many small steps that each have their own parameters. The design comes from a 2017 paper, Attention Is All You Need, whose abstract says: We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. The paper tested it on translating between languages.

Two years later, the GPT-2 paper used the design for a language model: We use a Transformer (Vaswani et al., 2017) based architecture for our LMs. An LM is a language model. Attention, the mechanism in the 2017 paper's title, lets the model weigh every earlier piece of the text when it works out the next one. It gets five tutorials of its own in this track.

Tokens, Probabilities and the Loop​

Three ideas explain how an LLM writes.

Tokens. A model doesn't read letters or whole words. The text is first cut into tokens: pieces that are often a word, sometimes part of a word, and sometimes one character. The list of all the tokens a model knows is its vocabulary, and every token in it has a number, its token ID. The model only ever sees the numbers.

To show a real split, I trained a tokenizer, the program that does the cutting, on short children's stories, with a vocabulary of 4,096 tokens. This is how it cut two sentences:

Output
The fish likes to swim.
6 tokens: ['The', ' fish', ' likes', ' to', ' swim', '.']
IDs: [410, 787, 1532, 266, 1367, 46]
Photosynthesis is unbelievable.
16 tokens: ['P', 'h', 'ot', 'os', 'y', 'nt', 'hes', 'is', ' is', ' un', 'b', 'el', 'ie', 'v', 'able', '.']
IDs: [80, 104, 300, 1651, 121, 347, 958, 287, 430, 708, 98, 416, 597, 118, 835, 46]

The first sentence is six tokens. Each common word is one token, the space before a word belongs to that word's token, and the full stop is a token of its own. The second sentence has only three words and still takes 16 tokens: the tokenizer had no token for Photosynthesis or unbelievable, so it spelled them out of smaller pieces that it did know. That's the point of tokens. A fixed vocabulary can write any text, and the words it has seen often cost the fewest tokens.

Probabilities. For the text so far, the model gives every token in its vocabulary a probability: a number from 0 to 1 that says how likely that token is to come next. Together they add up to 1. A probability of 0.57 is the same as 57%.

The loop. To write, a program picks one token with those probabilities, adds it to the end of the text, and asks the model again with the longer text. That's one token per round. The text the loop starts from is the prompt. The most text a model can look at in one go is its context window, counted in tokens. GPT-2's is 1,024 tokens.

That's all an LLM does when it writes. The next section runs the loop in real code, with a model small enough to read.

A Language Model in a Few Lines of Python​

Here's a complete language model. Its vocabulary has 11 tokens: ten words and the full stop. A real LLM computes its probabilities with millions of learned parameters. This one keeps them in a table that I wrote by hand: for each word, the words that can follow it and how likely each one is. You'll write code yourself, step by step, starting in the next tutorial. For now, read the code and look at what it prints.

next_word.py
import random

# For each word: the words that can follow it, and how likely each one is.
NEXT_WORD = {
"the": {"dog": 0.5, "bird": 0.3, "fish": 0.2},
"dog": {"often": 0.6, "always": 0.4},
"bird": {"often": 0.6, "always": 0.4},
"fish": {"often": 0.6, "always": 0.4},
"often": {"barks": 0.5, "sings": 0.3, "swims": 0.2},
"always": {"barks": 0.5, "sings": 0.3, "swims": 0.2},
"barks": {".": 0.7, "and": 0.3},
"sings": {".": 0.7, "and": 0.3},
"swims": {".": 0.7, "and": 0.3},
"and": {"the": 1.0},
}


def write(prompt):
words = prompt.split()
while words[-1] != ".":
options = NEXT_WORD[words[-1]]
word = random.choices(list(options.keys()), weights=list(options.values()))[0]
words.append(word)
return " ".join(words)


random.seed(12)
for _ in range(5):
print(write("the"))

macOS-style code window titled next_word.py, showing a tiny language model in Python: a NEXT_WORD table that lists, for each word, the words that can follow it with their probabilities, a write function that keeps picking a next word with random.choices until it reaches a full stop, and a loop that prints five sentences starting from the prompt the.

  • NEXT_WORD is the model. It's a table with one row for each word. After the, the next word is dog half of the time (0.5), bird three times in ten (0.3) and fish twice in ten (0.2). The numbers in every row add up to 1.
  • write is the loop. It splits the prompt into words. Then, as long as the last word isn't a full stop, it looks up the options for the last word, picks one of them, and adds it to the end.
  • random.choices makes the pick. It draws one word by chance, with the probabilities as weights, so dog comes up more often than fish, but not every time.
  • random.seed(12) fixes the random numbers, so the script prints the same sentences on every run. Without that line, every run writes different ones.
  • The last two lines call write five times with the prompt the, and print each sentence.

When I ran it with uv run next_word.py, it printed:

Output
the dog always sings .
the dog often barks and the bird often sings .
the dog often swims .
the fish often sings .
the dog always barks .

macOS-style terminal window titled Terminal, showing uv run next_word.py printing five sentences: the dog always sings, the dog often barks and the bird often sings, the dog often swims, the fish often sings, and the dog always barks, each ending with a full stop after a space.

Five sentences came out of one prompt, and the script stores no sentences at all. It only knows what can follow each word. The second sentence is longer because the pick after sings was and, which leads back to the. The space before each full stop is there because . is a token like any other, and the script joins the tokens with spaces.

What Happens During a Run​

Every round of the loop does three things: it looks up the options for the last word, picks one, and adds it to the text.

To see each round for real, I added one line to the loop. It prints the last word, its options, and the word that was picked:

steps.py
def write(prompt):
words = prompt.split()
while words[-1] != ".":
options = NEXT_WORD[words[-1]]
word = random.choices(list(options.keys()), weights=list(options.values()))[0]
print(f"after {words[-1]}: {options} -> {word}")
words.append(word)
return " ".join(words)

With the same seed, uv run steps.py wrote one sentence and printed:

Output
after the: {'dog': 0.5, 'bird': 0.3, 'fish': 0.2} -> dog
after dog: {'often': 0.6, 'always': 0.4} -> always
after always: {'barks': 0.5, 'sings': 0.3, 'swims': 0.2} -> sings
after sings: {'.': 0.7, 'and': 0.3} -> .
the dog always sings .

macOS-style terminal window titled Terminal, showing uv run steps.py printing the four rounds of the loop, after the, after dog, after always and after sings, each with its options and the word that was picked, and then the finished sentence the dog always sings.

Four rounds, four picks. In the second round always was picked although often was more likely: a pick by chance doesn't always take the most likely word. The fourth pick was the full stop, which ended the loop.

Do the probabilities really steer the picks? I had the script write 10,000 sentences and counted the second word of each: dog 5,014 times, bird 2,985 times and fish 2,001 times. The table says 0.5, 0.3 and 0.2. Those 10,000 sentences were 1,173 different ones, from 5 tokens long to 35.

Where This Tiny Model Falls Short​

You may have noticed that its dog sings and its fish barks. The table only looks at the last word. When it picks the verb, the last word is often or always, and the animal is already out of sight. A prompt that ends just before the verb makes this plain. I changed the last lines to write three sentences from the prompt the fish often:

Output
the fish often barks .
the fish often sings .
the fish often barks .

The fish never swam. Of the 10,000 sentences, 6,993 had one animal and one verb, and in only 2,645 of them, 38%, did the verb suit the animal. That's what chance alone gives: 0.5 × 0.5 + 0.3 × 0.3 + 0.2 × 0.2 = 0.38.

A bigger table doesn't fix it. A row for every pair of words would need almost 17 million rows for a vocabulary of 4,096 tokens (4,096 × 4,096 = 16,777,216), and most of those pairs never show up in the text you'd count them from. A real LLM solves both problems. It looks at every token in its context window, not only the last one, and it computes the probabilities from learned parameters, so it never needs a row for every possible text.

From a Table to a Real Model​

To show the difference with real numbers, I trained a small LLM for this page. It's a transformer of the same kind as GPT-2, at about a twentieth of the size of GPT-2's smallest version: 5.9 million parameters. It learned from short children's stories for 20 minutes, on the GPU of a laptop, an Apple M1 Pro.

I gave it three prompts that end in the same word, to, and asked for the probabilities of the next token:

Bar chart titled Same last word, different next word, with the probabilities a small trained language model gives the next token after three prompts. After The fish likes to: swim 56.9%, play 11.8%, dive 7.7% and eat 2.7%. After The bird likes to: fly 25.6%, sing 21.6%, soar 6.8% and play 6.0%. After The dog likes to: play 49.4%, run 6.3%, eat 3.2% and jog 1.8%.

PromptThe four most likely next tokens
The fish likes toswim 56.9%, play 11.8%, dive 7.7%, eat 2.7%
The bird likes tofly 25.6%, sing 21.6%, soar 6.8%, play 6.0%
The dog likes toplay 49.4%, run 6.3%, eat 3.2%, jog 1.8%

The last word is the same in all three prompts, and the model still gives the fish swim and the bird fly. It used the whole prompt, which the hand-written table couldn't do. Nobody told this model what fish do, either. It worked that out from the stories.

Put in the same loop as before, the model writes. I gave it the first ten words, and it wrote the rest. This is the sample as it came out, unedited:

Once upon a time, there was a little dog named Spot. Spot loved to carry things. One day, Spot found a big, red ball in the yard. He was very happy.

Spot played with the big, red ball all day. He rolled it around the yard. The sun was bright and the sky was blue. Spot knew he had to bring the ball back to his family.

As the sun went down, Spot went back to his family. They all wore a leash to keep the ball close to him. They all took turns throwing the ball and throwing it. They had so much fun together.

It's a story with a beginning and an end, in correct English, and it stays with one dog and one ball. It also slips: a family that "all wore a leash", and "throwing the ball and throwing it". That's what 20 minutes buy. In that time the model saw 46.9 million tokens of stories, which is less than one pass over the part of the text I gave it.

Before I chose this size, I timed bigger models. One with 15.9 million parameters ran at well under half the speed, and when I doubled its batch, the amount of text it takes in per step, it stopped with an out-of-memory error. PyTorch won't give a script more GPU memory than its limit allows, and I had set that limit low on purpose. Fixed: RuntimeError: MPS backend out of memory explains the error and its numbers.

The stories are from TinyStories, a dataset by Ronen Eldan and Yuanzhi Li that's shared under the CDLA-Sharing-1.0 license. Their paper describes it as a synthetic dataset of short stories that only contain words that a typical 3 to 4-year-olds usually understand, generated by GPT-3.5 and GPT-4. I trained on the first 200 MB of its training file.

What's Inside an LLM​

Between the text and the probabilities, a transformer runs the same few kinds of step, in this order:

  1. The tokenizer cuts the text into tokens and looks up their IDs. It isn't a neural network. It's built once, before training, from the same kind of text.
  2. The embeddings are a table with one row of numbers for every token in the vocabulary. The model computes with those rows, never with the IDs themselves. In GPT-2, a second table adds where in the text each token stands, because the order of the words matters.
  3. The transformer blocks are the heart of the model: the same kind of block, repeated. Each block has two parts. Attention lets every token gather information from the tokens before it, which is how fish reaches the place where the next word is decided. A feed-forward network then works on each token's numbers on its own.
  4. The output layer turns the numbers at the last position into one score for every token in the vocabulary. Those scores are called logits.
  5. Softmax is a small formula that turns the scores into probabilities that add up to 1.
  6. The pick isn't part of the model. The program around it chooses a token, and settings such as temperature act here.

Every number in the embedding tables, the blocks and the output layer is a parameter. GPT-2's smallest version shows how they add up, next to the model I trained for this page:

SettingGPT-2, smallest versionThe model on this page
Vocabulary50,257 tokens4,096 tokens
Context window1,024 tokens256 tokens
Numbers per token768256
Transformer blocks126
Attention heads in each block124
Parameters124,439,8085,853,184

GPT-2's settings are from its published configuration file. I counted its parameters by adding up every table and layer those settings give: 38,597,376 in the token table, 786,432 for the positions, 7,087,872 in each of the 12 blocks, and 1,536 in a last step before the output. That's the "124 million" of the model card. You may also see 117 million for this model. OpenAI's repository explains why: Note that our original parameter counts were wrong due to an error (in our previous blog posts and paper). Thus you may have seen small referred to as 117M and medium referred to as 345M.

How an LLM Learns: Training, Fine-Tuning and Use​

Where do the parameters come from? They start as random numbers. A model in that state gives every token about the same probability, and what it writes is noise. Training changes that with one exercise, repeated millions of times:

  1. Take a piece of real text, and hide the token that comes next.
  2. Let the model give its probabilities for the next token.
  3. Measure how wrong it was. That measure is called the loss. It's low when the model gave the real next token a high probability, and high when it didn't.
  4. Change every parameter a tiny bit, in the direction that would have made the loss lower.

Nobody marks anything by hand. The text is its own answer key, because the token that comes next is always right there in the text.

The loss is a number you can watch. A model that guesses blindly among 4,096 tokens scores 8.32. Before its first training step, the small model scored 8.37 on stories that were held back from its training. Twenty minutes later it scored 1.71:

Line chart titled The loss falls as the model trains. The loss on stories the model never trained on is 8.37 before training, 2.38 after 3.5 minutes, 2.05 after 7 minutes, 1.90 after 10 minutes, 1.79 after 14 minutes, 1.73 after 17 minutes and 1.71 after 20 minutes. The loss on the stories it trained on falls along the same curve, from 6.08 to 1.69.

The seven dots are the loss on the held-back stories: 8.37 before training, then 2.38 after 3.5 minutes, 2.05 after 7 minutes, 1.90 after 10, 1.79 after 14, 1.73 after 17, and 1.71 at the end. The line is the loss on the stories the model trained on, averaged over every 100 steps: 6.08 over the first hundred and 1.69 over the last. Most of the fall happens in the first two minutes. And the dots sit on the line: the model does as well on stories it never saw as on the ones it practiced on. It learned how such stories go, instead of learning them by heart.

A model usually goes through up to three stages:

StageWhat happensWhat changes in the model
PretrainingThe model learns language from a large amount of general text, starting from random parametersEvery parameter
Fine-tuningA pretrained model trains a little more on a smaller, special set of text, for example to sort messages into groups or to answer in a chatSome or all parameters, each by a little
Use, also called inferenceThe finished model computes next-token probabilities for a promptNothing

When you chat with an assistant, the model is in the third stage: its parameters stay as they are while it answers. This track goes through all three. It pretrains a small model from random parameters, fine-tunes pretrained ones in two ways, to sort text into groups and to follow instructions in a chat, and uses every one of them.

What "From Scratch" Means in This Track​

"From scratch" can mean many things. Here is what this track builds itself, and what it takes ready-made.

  • Tutorials 3 to 21 use plain Python, joined by NumPy from tutorial 13. A language model made by counting, a tokenizer, the maths of learning, a small neural network, and the engine that works out every correction: each one is written by hand, with numbers small enough to check on paper. NumPy's documentation calls it the fundamental package for scientific computing in Python. Here it holds the grids of numbers.
  • From tutorial 22, PyTorch does the arithmetic. Its documentation describes it as an optimized tensor library for deep learning using GPUs and CPUs. The track takes three things from it: tensors, which are grids of numbers, the automatic working-out of corrections that tutorial 21 first builds by hand, and the GPU.
  • The model is always our own code. The tokenizer, the embeddings, attention, the transformer block, the training loop and the code that writes text are written line by line in these tutorials. The track never builds on a ready-made transformer, attention layer, tokenizer or training framework: not PyTorch's nn.Transformer or nn.MultiheadAttention, and not Hugging Face's transformers or tokenizers libraries.
  • Small building blocks are written by hand once, then taken from PyTorch. Each of them, softmax and the loss for example, is written by hand in its own tutorial and checked against PyTorch's version on the same numbers. After that, the code uses PyTorch's.
  • Everything runs on one laptop. Every output on these pages comes from an Apple M1 Pro with 16 GB of memory. There's no cloud account, no rented GPU and no API key.

The track leaves out how to use a finished LLM in an application: writing prompts, calling a model over an API, searching your own documents, building agents. This site teaches those in the LangChain and LangGraph tutorials, and in the series Build an AI Lead Qualification Agent with Claude and Python.

So you won't finish this track having called somebody else's model. You'll have built one, trained it, and you'll know what every line of it does.

Every Concept, and Where This Track Teaches It​

This track teaches an LLM one concept at a time, in the order below. Each tutorial has its own small example, like the next-word table on this page, and builds only on the tutorials before it. They're published one at a time, and each concept becomes a link here when its tutorial is out.

The last column names the product line, described further down, that first puts the concept to work. Each later product starts from the finished code of the ones before it, so it relies on their concepts too.

Start Here​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
1What an LLM isKnow what an LLM does, what's inside it, how it learns and what this track buildsThis pageMain LLM
2Python for the tutorialsSet up uv and Python 3.15, create the one project every tutorial adds to, and run a first scriptComing soonMain LLM

A Language Model by Counting​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
3Tokens, vocabulary and token IDsTurn text into numbers and back, by characters and by words, and see why unknown words are a problemComing soonMain LLM
4Probability from countsTurn counts into probabilities, and work out the probability of a whole sentenceComing soonMain LLM
5A bigram model by countingBuild a working language model: a table, counted from text, of what follows each tokenComing soonMain LLM
6Greedy decoding and samplingWrite text by always taking the most likely token, or by drawing one by chanceComing soonMain LLM
7Cross-entropy loss and perplexityMeasure how wrong a model is, and know what a blind guess scoresComing soonMain LLM
8N-gram models, validation loss and overfittingLook back more than one token, test on held-back text, and tell learning from memorizingComing soonMain LLM

Real Text Becomes Tokens​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
9Unicode and UTF-8 bytesSee how a computer stores any text as bytes, the alphabet a tokenizer starts fromComing soonMain LLM
10Byte pair encoding (BPE)Train a tokenizer that builds its own word pieces, one merge at a timeComing soonMain LLM
11Encoding and decoding with BPETurn any text into token IDs and back, and save and load the tokenizerComing soonMain LLM
12Special tokensMark the end of a text, and keep a user's text from creating such a tokenComing soonMain LLM
13Preparing a text datasetSplit text for training and validation, encode it once, and keep the token IDs in a fileComing soonMain LLM

How a Model Learns, by Hand​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
14Vectors, matrices and the dot productDo the maths an LLM runs onComing soonMain LLM
15Logits and softmaxTurn scores into probabilities, safely even for big numbersComing soonMain LLM
16Gradient descentLower a loss in small steps, and choose the size of the stepsComing soonMain LLM
17Backpropagation by handWork out how every number in a calculation should change, and check itComing soonMain LLM
18A next-token model trained by gradient descentLearn the table of tutorial 5 instead of counting it, and see the two agreeComing soonMain LLM
19A neuron and a layerBuild the smallest piece of a neural network: weights, a bias and an activation functionComing soonMain LLM
20A neural network in NumPyTrain a small network with your own forward and backward passComing soonMain LLM
21A tiny autograd engineBuild the engine that works out every correction automaticallyComing soonMain LLM

PyTorch Enters​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
22From NumPy to PyTorchDo the same work with PyTorch's tensors and automatic gradients, and see the numbers matchComing soonMain LLM
23The same model in PyTorchUse PyTorch's modules, loss and optimizer, checked against your ownComing soonMain LLM

Neural Language Models​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
24Token embeddingsGive every token a row of numbers that the model learnsComing soonMain LLM
25Inputs, targets and batchesCut text into training examples, and feed the model many at a timeComing soonMain LLM
26A context-window language modelPredict from several earlier tokens, and see why that alone doesn't scaleComing soonMain LLM

Attention​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
27What attention isBlend pieces of information by how well each one matches a questionComing soonMain LLM
28Self-attentionLet every token look at the other tokens, with queries, keys and valuesComing soonMain LLM
29Causal maskingStop a token from seeing the tokens that come after itComing soonMain LLM
30Positional embeddingsTell the model the order of the tokensComing soonMain LLM
31Multi-head attentionRun several attentions side by sideComing soonMain LLM

The Transformer Block and the GPT Model​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
32The feed-forward network and GELUBuild the step that follows attention in every blockComing soonMain LLM
33Residual connectionsGive a deep model the shortcuts it needs to trainComing soonMain LLM
34Layer normalizationKeep the numbers in range from block to blockComing soonMain LLM
35The transformer blockPut attention, the feed-forward network, the shortcuts and the normalization togetherComing soonMain LLM
36The GPT modelStack the blocks into a complete model, with its embeddings and its output layerComing soonMain LLM
37Parameters and memoryCount a model's parameters, and work out the memory it needsComing soonMain LLM
38Weight initializationStart a model from good random numbers, and check its first lossComing soonMain LLM

Make It Write, Then Train It​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
39The generation loopMake a model write, one token at a time, within its context windowComing soonMain LLM
40OptimizersTake better training steps with SGD, momentum, Adam and AdamWComing soonMain LLM
41The training loopTrain a language model, and check first that it can learn at allComing soonMain LLM
42Learning-rate warmup and cosine decayChange the size of the steps during a runComing soonMain LLM
43Gradient clippingTame steps that are too bigComing soonMain LLM
44DropoutSwitch parts of a model off during training, and know when not toComing soonMain LLM
45CheckpointsSave a run, and resume it exactly where it stoppedComing soonMain LLM
46Gradient accumulationTrain with a bigger batch than memory allowsComing soonMain LLM
47Training speed, memory and timeTime a model honestly on the CPU and the GPU, and estimate a runComing soonMain LLM

Better Text, and Measuring It​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
48TemperatureTurn the randomness of the writing up and downComing soonMain LLM
49Top-k and top-p samplingChoose only among the likely tokensComing soonMain LLM
50The KV cacheWrite faster by not repeating work that's already doneComing soonMain LLM
51Evaluating a language modelJudge a model by its loss on held-back text and by what it writesComing soonMain LLM

Pretrained Weights​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
52GPT-2's tokenizerRebuild GPT-2's tokenizer from its published files, and count tokens the way it doesComing soonText Classifier
53Inside a model fileRead a file of trained parameters by handComing soonText Classifier
54Loading GPT-2's weightsLoad OpenAI's trained parameters into the model you builtComing soonText Classifier
55Pretraining and fine-tuningStart from a trained model, and choose which parts of it to keep fixedComing soonText Classifier

Fine-Tune to Classify​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
56Padding and ignored targetsTrain on batches of texts that have different lengthsComing soonText Classifier
57Fine-tuning for text classificationTeach a model to sort text into groups, and measure how often it's rightComing soonText Classifier

Modern LLMs​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
58RMSNormUse the simpler normalization of newer modelsComing soonModern LLM
59Rotary position embeddings (RoPE)Encode the order of the tokens by rotating their numbersComing soonModern LLM
60SwiGLUUse the feed-forward step of newer modelsComing soonModern LLM
61Grouped-query attentionShare keys and values between attention headsComing soonModern LLM
62float32, float16 and bfloat16Choose how precisely a model stores its numbersComing soonModern LLM
63A modern LLM, put togetherCombine the newer parts in one model, and load an open model's weights into itComing soonModern LLM
64QuantizationShrink a model to 8-bit and 4-bit numbers, and measure what that costsComing soonModern LLM

Teaching a Model to Chat​

#ConceptWhat it lets you doWhere you'll learn itFirst used in
65Chat templatesFormat a conversation the way a chat model reads itComing soonChat Assistant
66Instruction fine-tuningTeach a model to follow instructions, and to stop when it's doneComing soonChat Assistant
67LoRAFine-tune a model by training a few small added tables of numbersComing soonChat Assistant
68Evaluating a chat modelCheck a model's answers with tasks that a program can markComing soonChat Assistant

The Product Lines​

Below the Fundamentals in the sidebar, four product lines will put the concepts together in complete projects, each built from an empty folder to a finished program, one part at a time. Where a part uses a concept, it links the concept's tutorial and spends its own words on what's specific to the product. Each line follows one stretch of the tutorials:

All four are coming soon:

  • Main LLM builds a complete small GPT-style language model as a Python program with its own commands. They fetch the training text, train a tokenizer, turn the text into token files, train the model with checkpoints that resume exactly, write text, and measure the result. The last part trains it on your own text.
  • Text Classifier loads GPT-2's published parameters into that code and fine-tunes the model to sort text into groups, with a command that sorts new text.
  • Modern LLM rebuilds the model with the parts that newer open models use, loads a small open model's parameters into it and runs it, with a KV cache and smaller number formats.
  • Chat Assistant puts a chat in the terminal on top of the modern model, and teaches the model new instructions with LoRA on your own data.

The model that the Main LLM line trains on a laptop is small. It writes short, simple stories like the sample on this page, and it doesn't answer questions. That's why the Chat Assistant starts from a small open model that can.

What It Costs​

  • Software: nothing. Python, uv, NumPy, PyTorch and matplotlib are free and open source.
  • Accounts and keys: none. No tutorial in this track calls a paid service, and the text and the model files it downloads need no sign-in.
  • A GPU: not needed. The Fundamentals use tiny examples that run on a computer's ordinary processor, the CPU. A GPU only saves time when a product line trains a real model. On my Mac, the small model on this page trained 2.7 times as fast on the GPU as on the CPU: 38,281 tokens a second against 14,001.
  • Disk space: the largest download in the plan is the training text for the Main LLM, at 2.23 GB.
  • Time: training is the one step that takes real time. The model on this page trained for 20 minutes. At the speed I measured, one pass over the whole training text would take that model about four hours.

Tools You'll Use​

ToolWhat it's for
uvCreates the project with Python 3.15, adds packages and runs your code
NumPyGrids of numbers, from tutorial 13
PyTorchTensors, automatic gradients and the GPU, from tutorial 22
matplotlibCharts of losses and of what attention looks at
A code editor, such as Visual Studio CodeWriting the code

The next tutorial, Set Up Python for the Tutorials, gets uv and Python 3.15 ready, creates the one project that every later tutorial adds a file to, and runs a first script.

Frequently Asked Questions​

Is an LLM the same as AI?​

No. AI is the whole field of making computers do things that seem to need intelligence. An LLM is one kind of AI system: a neural network that was trained to predict the next token of a text.

What's the difference between an LLM and a chat assistant?​

The LLM is the model: text in, next-token probabilities out. A chat assistant is an application around a model. It turns the conversation into one long text in the format the model was trained on, runs the loop that picks tokens, and stops when the model produces its end marker. The Chat Assistant product line builds such an application.

Why does an LLM give a different answer each time?​

Because the next token is picked by chance, weighted by the probabilities. The tiny model on this page wrote five different sentences from one prompt. It wrote the same five again on a second run only because the script fixes its random numbers with a seed.

What does a number such as 124M in a model's name mean?​

The number of parameters. M stands for million and B for billion, so GPT-2's smallest version, with 124,439,808 parameters, is called 124M.

Do I need to be good at maths?​

School maths is enough to start: adding, multiplying and percentages. The track teaches the rest at the point where it's needed, with numbers small enough to check by hand: vectors and matrices in tutorial 14, slopes in tutorial 16 and the chain rule in tutorial 17. Every formula appears next to the same thing in plain words and in the line of code that computes it.

Can I build something like ChatGPT on my laptop?​

No, and this track doesn't pretend you can. You'll build the same kind of model from the same parts, and train a small one that writes short, simple stories. A model that answers questions on any subject needs far more parameters, text and computing power than a laptop has. What the small model gives you is the understanding, because every part of it is a part of the big ones too.

How is this different from using the Hugging Face Transformers library?​

That library hands you finished models and tokenizers in a few lines of code, which is the right tool when you want to build an application. The series Hugging Face Transformers Tutorial for NLP in Python teaches it. This track builds what is behind those few lines.

Conclusion​

A large language model does one thing: for the text so far, it gives every token in its vocabulary a probability of coming next. Writing is a loop around that: pick a token, add it, ask again. The hand-written table ran that loop in a few lines of Python, and it also showed its limit, a fish that barks, because it only saw the last word. The small transformer showed what learned parameters add. After 20 minutes on a laptop its loss had fallen from 8.37 to 1.71, and it gave swim to the fish and fly to the bird. The rest of this track builds every part between the text and those probabilities, by hand first.

Next: Set Up Python for the Tutorials (coming soon) gets uv and Python 3.15 ready, creates the one project that every tutorial adds to, and runs and times a first script.

Additional Resources​