…
…
AI Fundamentals · Lesson 17 / 31 · Language models
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Elena asked the assistant "Where can I download my enrollment letter?" twice and got two different sentences. Now she asks: "Does this assistant just write whatever it likes?" In this lesson you will build a toy language model from five short lines in the help desk log and use it to show Elena the answer.
At the end of the lesson you will have the table below. It is a small count table built from five lines: after each word, which word came next, how many times, and with what probability. For now, do not worry about where the numbers come from; you will build the table yourself during the lesson.
| After this word | Next word (count) | Probability |
|---|---|---|
| where | can (3) | 1 |
| can | i (5) | 1 |
| i | download (4), find (1) | 0.8 · 0.2 |
| download | my (4) | 1 |
| my | letter (3), transcript (2) | 0.6 · 0.4 |
| find | my (1) | 1 |
| how | can (2) | 1 |
In this lesson you will:
In lesson 4 we saw that the assistant does not look at the school's records when it answers. It tends to write the continuation it has seen most often in the texts it read. We left that as a seed: after "the deadline is", whichever date came most often is the one the assistant said. Today we open up how that seed works. Elena's question comes from exactly here: if the assistant writes what it has seen most often, why does it not give the same answer every time?
To answer, we first need to be clear about what job the language model inside the assistant actually does. Then we will try that job on a model small enough to run by hand.
A language model is a model that predicts which word comes next in a text. That is all. If you give it a start such as "Where can I download my", it predicts the word most likely to follow, for example "enrollment". A long answer is not written in one go, either: the model predicts one word, adds it to the end of the text, then looks at the longer text and predicts the next word. A three-sentence answer is a chain of dozens of small predictions.
Real models read text as word pieces rather than whole words; we will see that in the next lesson. Today we work with whole words to keep things simple.
A tool you use every day does this job too.
Example 1 (outside the case): Phone keyboard. When you type "See you tomorrow, good" three suggestions appear above the keyboard: "night", "luck", "morning". The order of the suggestions is not random; it comes from the messages you wrote before. If you usually wrote "night" after "good", that word moves to the front.
Why does the keyboard put "night" first after the word "good"?
Let's name a very common misunderstanding: "the assistant looks the answer up somewhere." It does not. It does not open a document and fetch the relevant line like a search engine; it predicts every word by looking at the text written so far.
Let's turn "the most likely word" into a number. For that we need a pile of text. We took five short lines from the help desk log (fictional sample data), written in lowercase without punctuation:
1. where can i download my letter
2. where can i download my transcript
3. where can i find my letter
4. how can i download my letter
5. how can i download my transcript
("letter" is short for enrollment letter.) Now we look at every pair of neighboring words in each line. The first line has five pairs: "where → can", "can → i", "i → download", "download → my", "my → letter". Counting the pairs of all five lines in one table gives the count table from the start of the lesson. For example, the word "my" appears in all five lines and has a word after it each time: three times "letter", twice "transcript".
Probability comes from these counts: divide the count of each next word by the total number of words that followed that word. After "my", 5 words came in total and 3 of them were "letter": 3 / 5 = 0.6. The remaining 2 / 5 = 0.4 belongs to "transcript". It is the same division you made when you computed accuracy in lesson 9: part over whole. The probabilities in a row always add up to 1.
Example 2 (case): The table of five lines. The table at the start of the lesson came from exactly these five lines. The cell below has a short program that builds the table. You do not need to understand it line by line: it splits the lines into words, counts every pair, and prints the continuations of every word. When you run it, you see seven lines such as i -> {'download': 4, 'find': 1}.
Try it now· not graded; doesn't affect progress
Now work out one row yourself.
In the table of five lines, what is the probability that "transcript" comes after the word "my"?
Once the table is ready, writing text is a simple loop: look at the last word of the text, find that word's continuations in the table, pick one, add it to the text, and repeat with the new last word. Stop when you reach a word that has no continuation. In our five lines "letter" and "transcript" always came at the end of a line, so nothing followed them; when the model reaches them, it goes quiet.
Let our first model always pick the most likely word. Follow the code below step by step. The line max(continuations, key=continuations.get) picks the continuation with the biggest count.
Run the code line by line: see which line runs next, the variable boxes and the output.
table = {
"where": {"can": 3},
"can": {"i": 5},
"i": {"download": 4, "find": 1},
"download": {"my": 4},
"my": {"letter": 3, "transcript": 2},
"find": {"my": 1},
"how": {"can": 2},
}
last = "where"
text = last
while last in table:
continuations = table[last]
last = max(continuations, key=continuations.get)
text = text + " " + last
print(text)While you step through, watch the last box: "where" → "can" → "i" → "download" → "my" → "letter". "letter" has no row in the table, so the condition while last in table becomes false and the loop stops. Output: where can i download my letter. If you change the start to "how" and trace again, you get how can i download my letter; the model only ever saw "can" after "how".
Put the steps of the loop in order.
Put one round of the model that writes text from the count table in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
When the model starts with "where", which sentences can it write, and what is the chance of each? A continuation is made of several steps, and every step has its own probability. The probability of the whole continuation is found by multiplying the probabilities of the steps. For "where can i download my letter": "where → can" 1, "can → i" 1, "i → download" 0.8, "download → my" 1, "my → letter" 0.6. Product: 1 × 1 × 0.8 × 1 × 0.6 = 0.48. A step with probability 1 changes nothing; only the steps where the model has a choice make the number smaller.
Why multiply? Think of 100 tries. In 80 of them the model goes from "i" to "download"; of those 80 tries, 60% go on from "my" to "letter", which is 48 tries. So 0.48 of all tries end with this sentence. Every choice cuts the share of the previous step a little more.
Example 3 (case): Continuations that start with "where". Walking the same path for every choice gives all four continuations:
| Continuation | Steps | Probability |
|---|---|---|
| where can i download my letter | 1 × 1 × 0.8 × 1 × 0.6 | 0.48 |
| where can i download my transcript | 1 × 1 × 0.8 × 1 × 0.4 | 0.32 |
| where can i find my letter | 1 × 1 × 0.2 × 1 × 0.6 | 0.12 |
| where can i find my transcript | 1 × 1 × 0.2 × 1 × 0.4 | 0.08 |
The four probabilities add up to 1: if the model starts with "where", it surely writes one of these four sentences. The most likely one is "download my letter", but the chances of the others are not zero.
A model that always picks the most likely word writes the same sentence every time: if you give it "where", you get where can i download my letter in every try. Real assistants often do not work this way. They do sampling: at every step they pick not the most likely word but a word with a chance in proportion to its probability. If the probability of "download" is 0.8, then in about four tries out of five "download" is picked and in one "find".
You can think of it as a die. The die gives a number between 0 and 1. After "i", if the die lands below 0.8 the word is "download"; at 0.8 or above it is "find". At the next choice a new die is rolled: after "my", below 0.6 is "letter", 0.6 or above is "transcript". Same prompt, different dice, different answer. That is the answer to Elena's question.
Real assistants have a setting that narrows or widens this chance; it is called the randomness setting (temperature). When the setting is low, the choice stays close to the most likely word and the answers look very much alike; when it is high, less likely words are also picked often and the answers vary. There is no randomness in the block below: you roll the dice. roll1 decides the choice after "i", roll2 the choice after "my".
Change roll1 first, then roll2. Which die decides which word, and how many different sentences can the model write?
Pick a value; predict the output first, then look.
1roll1 = 0.52roll2 = 0.334# after "i": download 0.8 · find 0.25if roll1 < 0.8:6 verb = "download"7else:8 verb = "find"910# after "my": letter 0.6 · transcript 0.411if roll2 < 0.6:12 item = "letter"13else:14 item = "transcript"1516print("where can i", verb, "my", item)
where can i download my letter
Faded lines didn't run with this value. Four dice combinations gave four different sentences: (0.5; 0.3) "download my letter", (0.5; 0.8) "download my transcript", (0.9; 0.3) "find my letter", (0.9; 0.8) "find my transcript". All four are grammatical and follow the probabilities in the table. "where can i find my transcript" was never written in the data: "find" appears only before "my letter" in line 3, and "transcript" appears only after "download my" and "how can i download my". It could be written because "my" has the same continuations whatever came before it.
Let's also correct a common misunderstanding here: "if it gives different answers, the model is broken or writing random nonsense." No. All four sentences follow the probabilities in the table; the die only decides which likely path is taken. The opposite misunderstanding exists too: "always picking the most likely word is always best." For an official notice it is, because you want the same, consistent text every time. But if you want ten different slogan ideas, a model that always picks the most likely word gives you the same slogan ten times. Which one is good depends on the job.
Sampling raises another question. What can the model write if it starts with "how"? "how → can" 1; "can → i" 1; "i → find" 0.2; "find → my" 1; "my → transcript" 0.4.
Example 4 (case): A sentence that is not in the data. The model can write how can i find my transcript. This sentence is in none of the five lines. Its probability is 1 × 1 × 0.2 × 1 × 0.4 = 0.08, small but not zero. The model did not copy this sentence from somewhere: every pair was seen in other lines ("i find" in line 3, "find my" in line 3, "my transcript" in lines 2 and 5) and the model joined them.
Two misunderstandings fall away here. The first: "If the model wrote a sentence, that sentence is in the data." It is not; by joining pairs the model can build sentences it has never seen. The second is more important: "The most likely continuation is true information." The model knows how often word pairs sit next to each other; it does not know whether a sentence is true in the world. After "i", "download" comes with probability 0.8; that does not show that a letter can really be downloaded. It only shows that "download" was written often in these lines. The way to find out whether a sentence is true is still the same: check the source. We will cover in detail, two lessons from now, why the model sometimes writes wrong information with full confidence.
Match each situation with the sentence that explains it.
For each row, pick its match from the list, then check.
A real assistant is much bigger than our five-line table. Instead of a count table it carries billions of weights of the kind you met in lesson 16; they are learned by reducing error, by asking "what is the next word?" again and again over a very large pile of text. It also looks not only at the last word but at the long text written so far. But the idea is the same: find the probabilities of the next word, pick one, add it, repeat.
Example 5 (case): Elena's answers. Elena asked the same question three times ("Where can I download my enrollment letter?") and got three fictional assistant outputs:
Output1. You can download it instantly from the student information system.
2. Log in to the student information system and download it right away; you do not need to go anywhere.
3. The enrollment letter is downloaded from the student information system and is ready immediately.The related item of the Student Handbook (g-12): "Enrollment letters can be downloaded instantly and free of charge from the student information system." The three answers use different words but say the same thing: the letter is downloaded from the student information system, without waiting.
The three answers are worded differently. Which one is right?
The answer for Elena is ready: the assistant does not write whatever it likes. It picks every word according to probability, with a bit of chance in the pick; that is why it answers the same question in different words. You decide which answer to trust not by looking at the words but by looking at the Handbook.
You can also get the table in Example 3 with code. The program multiplies the step probabilities for every continuation.
probs = {
"where": {"can": 1.0},
"can": {"i": 1.0},
"i": {"download": 0.8, "find": 0.2},
"download": {"my": 1.0},
"find": {"my": 1.0},
"my": {"letter": 0.6, "transcript": 0.4},
}
for verb, p1 in probs["i"].items():
for item, p2 in probs["my"].items():
p = probs["where"]["can"] * probs["can"]["i"] * p1 * probs[verb]["my"] * p2
print("where can i", verb, "my", item, "->", round(p, 2))Outputwhere can i download my letter -> 0.48
where can i download my transcript -> 0.32
where can i find my letter -> 0.12
where can i find my transcript -> 0.08The four numbers add up to 1: a model that starts with "where" surely writes one of these four sentences.
Confusing probability with truth. The sentence "The model said 'download' with 80% probability, so letters can be downloaded" says something the count table does not say. 0.8 shows how often "download" was written after "i" in the lines; it does not show how an enrollment letter is really obtained. The other face of the same mistake is thinking the model is broken when you see a different answer. The correct view: probability explains what is often written, sampling explains why a different answer comes; what is true is always decided by the source.
Next lesson: How is the bigger version of this toy table trained, what pieces does the model split text into, and what can it not know? We will look at how the assistant is trained and where its limits are.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Four order notes from a café (fictional sample data):
Outputone tea please
one coffee please
another tea please
one tea unsweetenedAfter "one", 3 words came and 2 of them were "tea": probability 2 / 3, about 0.67. After "tea", 3 words came too (two "please", one "unsweetened"): the probability of "please" is 2 / 3. The probability of the continuation "one tea please" is 2 / 3 × 2 / 3 = 4 / 9, about 0.44. The chance that this model writes "another coffee unsweetened" is zero: in the notes only "tea" ever came after "another".
Imagine you give the assistant the same prompt five times. A possible breakdown of five tries that start with "where" in our table could look like this:
OutputLow setting: download my letter · download my letter · download my letter · download my letter · download my letter
High setting: download my letter · find my letter · download my transcript · download my letter · find my transcriptWhen the randomness setting is low, the five answers are almost word for word the same, because the most likely word is picked at every step: in our table that means "where can i download my letter". When the setting is high, less likely paths such as "find my letter" or "download my transcript" also show up often. In both cases it is not the setting but the comparison with the source that tells you whether the answer is correct.