Lesson 01 · 35 minutes
Build a model that predicts the next word
- Count which token follows which in a text and use the counts as a model
- Generate new text by sampling one token at a time
- Explain what temperature changes in sampling
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your company wants a chatbot on its help page. A manager has read that such systems "think" and "understand", and asks you to say in plain words what the chatbot really does. The manager must decide what it may do on its own. You will answer with a working model that you build yourself. It is small, but it does the same job as the big ones: it predicts the next token of a text. Then you build a second model on a new text, without help.
The idea
A token is a small piece of text that the model treats as one unit. Here a token is a word or a full stop. Lesson 2 shows what real tokens look like.
A language model is a function. It takes the text so far and gives back a probability for each possible next token. A program then picks one token, adds it to the text and asks again. That loop is all of text generation.
- Text → Tokens: cut the text into pieces
- Tokens → Model: the model reads all tokens so far
- Model → Choice: it gives a chance to each next token
- Choice → Text: one token is picked and added
Our model is a bigram model. It looks at one token only (the last one) and uses a table of counts: how often each token followed it in a training text. A real LLM replaces the table with a neural network (you met the idea in "How AI works", lesson 8). The network looks at thousands of earlier tokens, not one. The loop around it is the same. Lesson 4 says how such a network is made, and lesson 9 looks inside it.
Sampling is the choice of the next token. You can always take the most likely token, or you can draw one at random in proportion to the probabilities. Temperature sets how sharp the draw is:
| Temperature | Effect |
|---|---|
| 0 | Always the most likely token. The output is the same on every run. |
| Low (0.3) | The likely tokens get most of the chance. |
| 1 | The probabilities are used as they are. |
| High (3) | The chances move towards equal. The output wanders. |
Worked example
1. Make the training text
Write a short text about security work. cat > corpus.txt <<'EOF' writes the lines that follow, up to the line EOF, into the file corpus.txt. wc -w (word count) counts the words in a file.
mkdir -p ~/krlab/llms-and-agents
cd ~/krlab/llms-and-agents
cat > corpus.txt <<'EOF'
the analyst reads the log. the analyst finds the alert. the alert shows a failed login. the failed login came from a new address. the analyst blocks the address. the analyst writes the report. the report names the cause. the team reads the report. the team fixes the cause. the team patches the server. the server runs the patch. the patch closes the hole. the hole let the attacker in. the attacker stole the password. the password opened the server. the analyst reads the log again.
EOF
wc -w corpus.txt86 corpus.txt2. Count what follows what
Create bigram.py. It uses four tools of Python that are new here:
open("corpus.txt").read()reads a whole file as one string, and.lower()makes it lower case.re.findall(pattern, text)returns every piece of the text that matches the pattern. The pattern[a-z]+|\.means "a run of letters, or one full stop".- A
Counteris a dictionary that counts. Adefaultdict(Counter)makes a newCounterthe first time that you use a key. zip(tokens, tokens[1:])walks through the tokens in pairs: each token with the one after it.
follows["the"] holds one counter: how many times each token came after the.
import random
import re
from collections import Counter, defaultdict
text = open("corpus.txt").read().lower()
tokens = re.findall(r"[a-z]+|\.", text)
# count which token follows which
follows = defaultdict(Counter)
for a, b in zip(tokens, tokens[1:]):
follows[a][b] += 1
print("tokens in the text:", len(tokens))
print("different tokens:", len(set(tokens)))
print("after 'the':", dict(follows["the"]))
print("after 'analyst':", dict(follows["analyst"]))python3 bigram.pytokens in the text: 102
different tokens: 35
after 'the': {'analyst': 5, 'log': 2, 'alert': 2, 'failed': 1, 'address': 1, 'report': 3, 'cause': 2, 'team': 3, 'server': 3, 'patch': 2, 'hole': 2, 'attacker': 2, 'password': 2}
after 'analyst': {'reads': 2, 'finds': 1, 'blocks': 1, 'writes': 1}This table is the whole model. It has 102 tokens, not 86: each of the 16 full stops counts as a token. After the, the token analyst is the most likely next one (5 of 30 cases).
3. Generate text with temperature 0
Add two functions at the end of the file, and one test line. next_token picks the follower. counts.most_common(1) gives the item with the highest count. generate repeats the pick, starting from a given token. random.Random(seed) makes a random generator that gives the same draws each time you give it the same seed. rng.choices(names, weights) draws one name, and a bigger weight gives a bigger chance. x ** y is x to the power y. [ ... for n in names ] is a comprehension: it builds a list by doing the same sum once for each name.
def next_token(word, temperature, rng):
counts = follows[word]
if temperature == 0:
return counts.most_common(1)[0][0]
names = list(counts)
weights = [counts[n] ** (1 / temperature) for n in names]
return rng.choices(names, weights)[0]
def generate(start, length, temperature, seed):
rng = random.Random(seed)
out = [start]
for _ in range(length):
out.append(next_token(out[-1], temperature, rng))
return " ".join(out).replace(" .", ".")
print(generate("the", 18, 0, 1))python3 bigram.py | tail -1the analyst reads the analyst reads the analyst reads the analyst reads the analyst reads theWith temperature 0 the model is stuck in a loop. analyst is the most likely token after the, and reads is the most likely after analyst, so the path never leaves. Run it again: you get the same text. A model with no randomness is a function in the plainest sense.
4. Look at the odds
This is the hardest step of the lesson. If the code is too much at once, read the output first and come back to the code later.
The line counts[n] ** (1 / temperature) is the temperature. A small temperature makes large counts matter even more. A large one flattens them. sorted(..., key=weights.get, reverse=True)[:4] sorts the names by weight, largest first, and keeps the first four. { n: ... for n, c in ... } is the same idea as a comprehension, but it builds a dictionary. Delete the print(generate(...)) line, and add this at the end.
def show_odds(word, temperature):
counts = follows[word]
weights = {n: c ** (1 / temperature) for n, c in counts.items()}
total = sum(weights.values())
top = sorted(weights, key=weights.get, reverse=True)[:4]
print(f"temperature {temperature}:", {n: round(weights[n] / total, 2) for n in top})
print("chance of the next token after 'the' (top 4)")
for t in (0.3, 1.0, 3.0):
show_odds("the", t)python3 bigram.py | tail -4chance of the next token after 'the' (top 4)
temperature 0.3: {'analyst': 0.53, 'report': 0.1, 'team': 0.1, 'server': 0.1}
temperature 1.0: {'analyst': 0.17, 'report': 0.1, 'team': 0.1, 'server': 0.1}
temperature 3.0: {'analyst': 0.1, 'report': 0.09, 'team': 0.09, 'server': 0.09}At 0.3 the model picks analyst more than half of the time. At 3.0 all 13 followers are nearly equal. (A real LLM does the same sum on the scores of its network, not on counts.)
5. Sample at three temperatures
Add the loop at the end of the file. Each temperature runs with two seeds.
print()
for t in (0, 0.7, 2.0):
print(f"temperature {t}:")
for seed in (1, 2):
print(" ", generate("the", 18, t, seed))python3 bigram.py | tail -9temperature 0:
the analyst reads the analyst reads the analyst reads the analyst reads the analyst reads the analyst reads the
the analyst reads the analyst reads the analyst reads the analyst reads the analyst reads the analyst reads the
temperature 0.7:
the analyst writes the log. the team patches the analyst writes the patch. the server. the
the password opened the analyst writes the server. the team fixes the report. the password opened the
temperature 2.0:
the log again. the cause. the hole. the hole. the analyst finds the alert shows
the password opened the analyst writes the server. the team fixes the report. the password opened theRead the text with care. Every pair of neighbouring tokens appears in the training text, so each step looks right. The sentences as a whole do not hold together: "the password opened the analyst writes the server". The model has no plan and no idea of true or false. It only knows what tends to follow what. An LLM is a much better predictor, but its output has the same nature: likely text, not checked fact. Lesson 5 measures what this means.
6. The finished file
This is the whole file bigram.py as it stands after the steps above. The lab files of the course hold it.
The finished file: bigram.py
bigram.py
import random
import re
from collections import Counter, defaultdict
text = open("corpus.txt").read().lower()
tokens = re.findall(r"[a-z]+|\.", text)
# count which token follows which
follows = defaultdict(Counter)
for a, b in zip(tokens, tokens[1:]):
follows[a][b] += 1
print("tokens in the text:", len(tokens))
print("different tokens:", len(set(tokens)))
print("after 'the':", dict(follows["the"]))
print("after 'analyst':", dict(follows["analyst"]))
def next_token(word, temperature, rng):
counts = follows[word]
if temperature == 0:
return counts.most_common(1)[0][0]
names = list(counts)
weights = [counts[n] ** (1 / temperature) for n in names]
return rng.choices(names, weights)[0]
def generate(start, length, temperature, seed):
rng = random.Random(seed)
out = [start]
for _ in range(length):
out.append(next_token(out[-1], temperature, rng))
return " ".join(out).replace(" .", ".")
def show_odds(word, temperature):
counts = follows[word]
weights = {n: c ** (1 / temperature) for n, c in counts.items()}
total = sum(weights.values())
top = sorted(weights, key=weights.get, reverse=True)[:4]
print(f"temperature {temperature}:", {n: round(weights[n] / total, 2) for n in top})
print("chance of the next token after 'the' (top 4)")
for t in (0.3, 1.0, 3.0):
show_odds("the", t)
print()
for t in (0, 0.7, 2.0):
print(f"temperature {t}:")
for seed in (1, 2):
print(" ", generate("the", 18, t, seed))Your turn
Build the same model on a new text, and use it. There is no code here: change bigram.py and use its functions as they are.
- Save this text as
corpus2.txt(one line). Changebigram.pyso that it reads that file.
the server logs the request. the firewall blocks the request. the server logs the error. the user sends the request. the firewall logs the block. the user reads the error. the admin reads the log. the admin fixes the firewall. the firewall stops the attack. the attack hits the server.- Print the number of tokens, the number of different tokens, and the counter that follows
the. - Generate text with
generate("the", 8, 0.7, 2). A random draw is fixed by the seed, so every reader gets the same text.
Last, say in two sentences what the manager should learn from your model. Use the words "next token" and "no check of facts".
Check yourself
Why does the model repeat "the analyst reads" at temperature 0?
At temperature 0 the program always takes the most likely follower. analyst follows the most often, and reads follows analyst most often. The path returns to the and never takes another branch.
You raise the temperature from 0.7 to 3. What happens to the output, and is it more correct?
The chances move towards equal, so unlikely followers appear more often and the text wanders. It is not more correct. A higher temperature gives more variety and more errors. A lower one gives more repeats.
Our model looks at one token. What changes when a model looks at the last 1,000 tokens?
It can use far more context: the topic, the question, the style, a fact stated earlier. The prediction becomes much better. The loop stays the same: predict, pick, append, repeat. The table of counts cannot do this, because 1,000 tokens never repeat exactly. That is why real models use a neural network.
The model never saw "the attacker stole the log". Can it write it?
Yes. the attacker and stole the and the log all appear, and each pair is allowed on its own. The model joins pieces that it has seen. This is why a language model can say things that no document contains, true or false.
Field notes
- A real model predicts from the whole text before the cursor, so whatever you put into the prompt moves the odds. Prompt injection, a main topic of the Core courses, uses exactly this: text from an attacker sits in the same stream as your instructions.
- Temperature 0 gives the most likely token at each step. It does not give the most likely whole answer, and it is not proof of truth. Use it for repeatable tests and for tasks with one right answer, such as extraction and classification.
- Sampling randomness makes a failure hard to reproduce. When you test a model for security, record the seed, the temperature and the exact prompt. Run a case several times and report a count ("4 of 5"), not a single result.
- Settings such as temperature are not security controls. A low temperature makes an attack that works more repeatable, not less likely.
- Training text is the model's whole world. Anything in it, wrong or hostile, changes the odds. This is the base of data poisoning, which a later course covers.