Module 2 · Generative AI foundations · Chapter 2 of 24
Generative AI and how LLMs work
23 sections · ~38 min✓ Fact-checked
No prerequisites. Next up: Prompt engineering.
Part 1 · What generative AI is
Discriminative and generative models
Every LLM product, from a support bot to a coding assistant, sends text to a model and gets text back one token at a time. This chapter opens that box.
A discriminative model maps an input to a label or a score. A spam filter reads an email and returns spam or not spam. A sentiment model reads a review and returns a number between 0 and 1. The set of possible outputs is small and fixed, and the model never writes anything new.
A generative model learns the distribution of its training data and samples new data from it. Trained on text, it writes new sentences. Trained on images, it draws new pictures. Audio and code work the same way. There is no fixed list of answers: each run can produce something that did not exist before.
System
Input
Output
Kind
Spam filter
email text
spam or not spam
discriminative
Sentiment scorer
review text
a score from 0 to 1
discriminative
Image captioner
a photo
a new sentence
generative
Chat assistant
a question
a new paragraph
generative
Spam filter
Inputemail text
Outputspam or not spam
Kinddiscriminative
Sentiment scorer
Inputreview text
Outputa score from 0 to 1
Kinddiscriminative
Image captioner
Inputa photo
Outputa new sentence
Kindgenerative
Chat assistant
Inputa question
Outputa new paragraph
Kindgenerative
A large language model (LLM) is a generative model for text. It is a neural network with billions of parameters (learned numbers), trained on one task: given the tokens so far, predict the next token. A token is a chunk of text, often a word or a piece of a word. Answering, summarising, translating and writing code all come from repeating that one prediction.
A foundation model is a large model trained on broad data so that one set of weights can be adapted to many tasks, either by prompting it or by training it further. Most LLMs you will use are foundation models, and some of them, like the one in this chapter, also accept images and audio.
What an application does
An LLM application is ordinary software wrapped around one operation: send text to a model and read the reply. Your code builds a list of messages, each with a role and some content, and sends it over HTTP to a server that holds the model. The server runs the model once per output token until the model signals that it is done, then returns the finished message plus metadata.
The model keeps nothing between calls. It sees only the messages in the current request, so anything it should know, including earlier turns of a chat, has to be sent again each time. This is why prompt size matters for cost and speed.
The request and reply shape used here is the Chat Completions format. Many hosted services and local servers accept it, which means the code in this course runs against any of them after a change of address. The model behind the calls is gemma4:12b, an open-weight model served by Ollama on this machine. Open-weight means the trained parameters are published and you can run them yourself.
Two fields in every reply are worth reading from the start. finish_reason says why generation stopped: stop means the model finished its answer, and length means it hit the max_tokens limit you set. usage counts the tokens that went in and came out, which is what hosted services bill for.
Running a first call
The setup is one uv project with the openai client library and a small shared helper, llm.py, that every later chapter reuses.
The helper reads three environment variables: the server address, an API key and the model name. Defaults point at the local server. On another provider, set the three variables and drop or change reasoning_effort. A default Ollama install listens on port 11434 instead of 11500.
python
import os
from openai import OpenAI
client = OpenAI(
base_url=os.environ.get(
"LLM_BASE_URL", "http://127.0.0.1:11500/v1"
),
api_key=os.environ.get("LLM_API_KEY", "ollama"),
)
MODEL = os.environ.get("LLM_MODEL", "gemma4:12b")
EMBED_MODEL = os.environ.get("EMBED_MODEL", "nomic-embed-text")
def chat(messages, **kw):
kw.setdefault("reasoning_effort", "none")
r = client.chat.completions.create(
model=MODEL, messages=messages, **kw
)
return r.choices[0].message, r
chat returns the message and the full response.
chat sets reasoning_effort to none unless you pass another value. That switches off the model's thinking phase, which lesson 5 explains. The call below sends one user message and prints the text, the finish reason and the token counts.
python
import textwrap
from llm import chat
question = "In one sentence, what is a token?"
msg, r = chat([{"role": "user", "content": question}])
print(textwrap.fill(msg.content, 60))
print(r.choices[0].finish_reason)
u = r.usage
print(u.prompt_tokens, u.completion_tokens, u.total_tokens)
text
A token is a basic unit of text, such as a word, subword, or
character, that is processed by a machine learning model to
represent linguistic information.
stop
223456
Output from one run; yours will differ.
The reply is a sentence, and finish_reason is stop. The prompt used 22 tokens although the question has only seven words, because the server wraps your message in the model's chat format and every piece counts. The next lesson measures that overhead.
Which of these is a generative system: a spam filter, an image captioner, or a sentiment score?
The image captioner: it writes a new sentence for each photo.
The spam filter and the sentiment score choose from a fixed set of outputs, so they are discriminative.
Besides the text, what does one call return that you should check?
finish_reason: stop means the answer is complete, length means it was cut at max_tokens.
usage: prompt, completion and total token counts.
Why must your code resend earlier messages on every call?
The model keeps no state between requests. It sees only the messages in the current one.
Part 2 · Tokens and tokenisation
Why models read tokens
A neural network works on numbers, so text has to become integers first. A tokeniser splits text into tokens, pieces drawn from a fixed vocabulary, and maps each piece to an integer ID. The model reads and writes IDs, and the tokeniser turns the IDs back into text.
Splitting into single characters would make every sequence very long. Splitting into whole words would need a huge vocabulary and would fail on any word it had not seen. Tokenisers settle in the middle with subwords: common words are one token, rare words are several pieces, and unusual strings fall back to single characters or bytes.
Everything you pay for or are limited by is counted in tokens: the price per million tokens, the context window, and the max_tokens cap on a reply. The tokeniser is also specific to each model. The same sentence can be a different number of tokens for two different models, so a count from one tokeniser only estimates another model's count.
Byte-pair encoding
Most LLM tokenisers are built with byte-pair encoding (BPE). BPE began as a data-compression algorithm, and Sennrich and co-authors adapted it in 2015 to split rare words into subword units for machine translation. Training the tokeniser is a counting loop. Start with every word split into characters. Count how often each adjacent pair of symbols occurs. Merge the most frequent pair into one new symbol. Repeat until the vocabulary reaches the wanted size. The ordered list of merges is the tokeniser.
The script below runs that loop on a tiny made-up corpus. The underscore marks the end of a word.
python
from collections import Counter
corpus = ("low low low low lower lower ""newest newest newest widest widest")
words = [list(w) + ["_"] for w in corpus.split()]
def top_pair(words):
pairs = Counter()
for w in words:
pairs.update(zip(w, w[1:]))
return pairs.most_common(1)[0]
def merge(words, pair):
out = []
for w in words:
new, i = [], 0while i < len(w):
if i + 1 < len(w) and (w[i], w[i + 1]) == pair:
new.append(w[i] + w[i + 1])
i += 2else:
new.append(w[i])
i += 1
out.append(new)
return out
for step in range(1, 7):
pair, count = top_pair(words)
words = merge(words, pair)
print(step, pair, count)
print(words[0], words[4], words[6])
Step 1 merges l and o because that pair occurs six times (four in low, two in lower). The pair o, w also occurs six times, and the tie goes to the pair counted first. Step 2 grows it to low. Steps 3 to 5 build est_ from the words newest and widest. After six merges low_ is a single token, while lower is low, e, r, _: a word that is not fully covered by merges is still encoded, from smaller pieces.
Production tokenisers run the same idea at scale. A byte-level BPE starts from the 256 possible byte values instead of characters, so any string in any script can be encoded, and it learns tens of thousands of merges from a huge corpus. Vocabulary sizes come from the next page's run and the model's card: about 1,00,000 and 2,00,000 for two tiktoken encodings, and about 2,62,000 for the model used in this course.
Counting tokens
tiktoken is an open-source library that ships two widely used BPE encodings, cl100k_base and the newer o200k_base. The script counts tokens for the same question in four forms: English, Hindi, Telugu, and Hindi written in the Latin alphabet, and first prints each string's length in characters and in UTF-8 bytes. Set PYTHONUTF8=1 so the Windows console prints the Indic text.
python
import tiktoken
texts = {
"English": "Where is my order?",
"Hindi": "मेरा ऑर्डर कहाँ है?",
"Telugu": "నా ఆర్డర్ ఎక్కడ ఉంది?",
"Romanised": "Mera order kahan hai?",
}
for label, t in texts.items():
print(f"{label:<10} {len(t):>2} chars {len(t.encode()):>2} bytes")
for name in ["o200k_base", "cl100k_base"]:
enc = tiktoken.get_encoding(name)
print(name, "vocabulary:", enc.n_vocab)
for label, t in texts.items():
print(f" {label:<10} {len(enc.encode(t)):>2} tokens")
enc = tiktoken.get_encoding("o200k_base")
ids = enc.encode(texts["English"])
print([enc.decode([i]) for i in ids])
text
English 18 chars 18 bytes
Hindi 19 chars 49 bytes
Telugu 21 chars 55 bytes
Romanised 21 chars 21 bytes
o200k_base vocabulary: 200019
English 5 tokens
Hindi 8 tokens
Telugu 9 tokens
Romanised 7 tokens
cl100k_base vocabulary: 100277
English 5 tokens
Hindi 18 tokens
Telugu 35 tokens
Romanised 7 tokens
['Where', ' is', ' my', ' order', '?']
English takes five tokens in both encodings, one per word and one for the question mark. The Hindi and Telugu sentences, which are about the same length in characters, take 8 and 9 tokens in the newer encoding and 18 and 35 in the older one. The byte counts explain part of it. UTF-8 stores Devanagari and Telugu letters in three bytes each, so the Telugu sentence is 55 bytes against 18 for the English one. A byte-level tokeniser starts from those bytes, and BPE only adds a merge for a pair that is frequent in the text the tokeniser was trained on. Where a script got few merges, its text stays close to raw bytes: cl100k_base spends 35 tokens on 55 bytes, fewer than two bytes per token, so on average each Telugu letter takes more than one token. o200k_base, with twice the vocabulary, needs 9. The same meaning can therefore cost more tokens, more money and more of the context window.
The model's own count
Now the model itself. The script asks the local server for one output token and reads prompt_tokens for each string. An empty message gives the fixed overhead of the chat format, which is subtracted from every count.
python
from llm import chat
texts = [
"Where is my order?",
"मेरा ऑर्डर कहाँ है?",
"నా ఆర్డర్ ఎక్కడ ఉంది?",
"Mera order kahan hai?",
]
def prompt_tokens(text):
_, r = chat([{"role": "user", "content": text}], max_tokens=1)
return r.usage.prompt_tokens
overhead = prompt_tokens("") # an empty message: template only
print("template overhead:", overhead)
for t in texts:
print(prompt_tokens(t) - overhead, t)
text
template overhead: 135 Where is my order?
5 मेरा ऑर्डर कहाँ है?
8 నా ఆర్డర్ ఎక్కడ ఉంది?
7 Mera order kahan hai?
Sentence
Characters
o200k_base
cl100k_base
Local model
English
18
5
5
5
Hindi
19
8
18
5
Telugu
21
9
35
8
Hindi, Latin letters
21
7
7
7
English
Characters18
o200k_base5
cl100k_base5
Local model5
Hindi
Characters19
o200k_base8
cl100k_base18
Local model5
Telugu
Characters21
o200k_base9
cl100k_base35
Local model8
Hindi, Latin letters
Characters21
o200k_base7
cl100k_base7
Local model7
The chat format adds 13 tokens to every request on this server, which explains most of the 22 prompt tokens in the previous lesson. The local model's own tokeniser handles Hindi and Telugu in 5 and 8 tokens, so a tiktoken count would overstate its cost here. Use a model's own count (the usage field) whenever the number matters.
Why does the Telugu sentence cost more tokens than the English one under cl100k_base?
Each Telugu letter is 3 bytes in UTF-8, and cl100k_base has few merges for Telugu, so the text stays close to bytes: 35 tokens for 55 bytes.
The English sentence is 18 bytes and 5 tokens, because whole English words are in the vocabulary.
Predict: will the local model's token count match tiktoken's for the Hindi sentence?
No. The local model needs 5 tokens, tiktoken needs 8 (o200k_base) or 18 (cl100k_base).
Each model has its own tokeniser, so another tokeniser's count is only an estimate.
What does one BPE training step do?
It counts adjacent pairs, merges the most frequent pair into a new symbol, and adds that merge to the list.
Part 3 · Predicting the next token
From scores to probabilities
At each step the model produces one score for every token in its vocabulary. These raw scores are logits. A logit has no fixed scale: it only says that one token is more likely than another. The softmax function turns a vector of logits z into probabilities: each token gets exp(z) divided by the sum of exp(z) over all tokens. The probabilities are positive and add up to 1.
Decoding then chooses one token from that distribution. Greedy decoding always takes the most probable token. Sampling draws a token at random with the given probabilities. The chosen token is appended to the sequence, the model runs again on the longer sequence, and the loop repeats until the model emits a stop token or the max_tokens limit is reached. Because each token depends on all the earlier ones, this is called autoregressive generation.
The script applies softmax to five made-up logits for the word after "The capital of France is", at three temperatures.
python
import numpy as np
tokens = ["Paris", "Lyon", "France", "the", "Rome"]
logits = np.array([6.0, 4.0, 3.0, 2.0, 1.0])
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
print("token " + "".join(f"T={t:<6}"for t in (0.5, 1.0, 2.0)))
for i, tok in enumerate(tokens):
row = [softmax(logits / t)[i] for t in (0.5, 1.0, 2.0)]
print(f"{tok:<8}" + "".join(f"{p:<8.3f}"for p in row))
p = softmax(logits)
order = np.argsort(-p)
cum = np.cumsum(p[order])
print("cumulative at T=1:")
for i, c in zip(order, cum):
print(f" {tokens[i]:<7}{c:.3f}")
text
token T=0.5 T=1.0 T=2.0
Paris 0.9790.8260.553
Lyon 0.0180.1120.203
France 0.0020.0410.123
the 0.0000.0150.075
Rome 0.0000.0060.045
cumulative at T=1:
Paris 0.826
Lyon 0.938
France 0.979
the 0.994
Rome 1.000
Temperature, top-k and top-p
Temperature T divides the logits before softmax. At T below 1 the gaps between logits grow, so the leader takes more of the probability. At T above 1 the gaps shrink and the distribution flattens. As T approaches 0 the choice approaches greedy decoding.
In the table above, Paris has logit 6 and Lyon has 4. At T = 0.5 the gap becomes 4, so the odds of Paris over Lyon go from exp(2), about 7.4, to exp(4), about 55, and Paris rises from 0.826 to 0.979. At T = 2 the gap is 1 and Paris falls to 0.553.
Two filters cut the unlikely tail before sampling. Top-k keeps the k most probable tokens. Top-p, also called nucleus sampling (Holtzman and co-authors, 2019), keeps the smallest set of tokens whose probabilities add up to at least p, then renormalises. With the cumulative column from the run, top-p of 0.95 keeps Paris, Lyon and France, whose total is 0.979, and removes the and Rome. The model's metadata lists default sampling settings of temperature 1, top-k 64 and top-p 0.95, which lesson 5 prints.
Temperature 0 is not a guarantee
Temperature 0 means greedy decoding, but identical output on every run also depends on the server. Batching and the order of floating-point operations can change which token is largest when two are close. Treat it as very repeatable, not as proof.
Probabilities from a real model
Chat Completions can return the log-probabilities of the chosen tokens. A log-probability is the natural log of the probability, so exp recovers it. Ollama's compatibility page marks logprobs as unsupported, but version 0.40.2 on this machine returned them, and this lesson uses only what the run printed. top_logprobs=3 adds the three best alternatives at each step.
python
import math
from llm import chat
prompt = ("Complete the sentence in a few words, no explanation: ""I drink my tea with")
msg, r = chat(
[{"role": "user", "content": prompt}],
logprobs=True, top_logprobs=3, max_tokens=8, temperature=0,
)
print(repr(msg.content))
for step in r.choices[0].logprobs.content:
top = ", ".join(
f"{a.token!r} {math.exp(a.logprob):.3f}"for a in step.top_logprobs
)
p = math.exp(step.logprob)
print(f"{step.token!r:<9} {p:.3f} | {top}")
Output from one run. A later run on this machine printed 0.920 for honey and 0.052 for lemon.
The first token is the only real decision: honey has probability 0.935 and lemon 0.043. Once honey is chosen, and is almost certain, and so are lemon and the full stop. Note the leading spaces: a token often includes the space before the word. The text was the same at temperature 0 in both runs, while the probabilities moved in the second decimal place, which is the effect the note on the previous page describes.
Animated sceneGenerating one token at a time0:16
Watch for each new token being written into the next empty slot
Read it as steps
The loop behind every reply: score, pick, append.
The cells show the prompt's words, not the model's own token pieces, and leave out the leading space of and and lemon. The four filled cells and their probabilities are the run's.
To see temperature at work, the script asks five times for a name at temperature 0 and five times at temperature 1.
python
from collections import Counter
from llm import chat
ask = "Invent a name for a tea stall. Reply with the name only."
prompt = [{"role": "user", "content": ask}]
for temp in (0, 1.0):
answers = [
chat(prompt, temperature=temp, max_tokens=5)[0].content
for _ in range(5)
]
print("temperature", temp)
for name, n in Counter(answers).items():
print(f" {n} x {name}")
text
temperature 05 x The Steeping Leaf
temperature 1.01 x The Steeping Leaf
1 x The Steeped Leaf
1 x The Golden Steep
1 x The Steaming Leaf
1 x Brew & Bloom
Output from one run; yours will differ.
At temperature 0 all five answers were the same. At temperature 1 the first token is sampled, and later tokens follow from it, so one early choice produced five different names.
Calculate: in the five-token table, which token wins at T = 0.5, and why does its probability rise?
Paris wins at every temperature, with 0.979 at T = 0.5.
Dividing by 0.5 doubles the logit gaps, and softmax then gives the leader a larger share.
What does top-p = 0.95 remove in the cumulative column?
Everything after the point where the running total first reaches 0.95: here the and Rome are removed, and Paris, Lyon and France are kept.
Predict: how many distinct answers did temperature 0 give in five calls?
One. All five were The Steeping Leaf, as greedy decoding implies.
Part 4 · Inside the transformer: attention
From tokens to vectors
The tokens' integer IDs are not used directly. An embedding table maps each ID to a vector of learned numbers, and all later layers work on these vectors. The model in this course uses vectors 3,840 numbers wide, read from embedding_length in its metadata.
The network that processes them is a transformer, introduced by Vaswani and co-authors in 2017. Its central operation, self-attention, lets every position look at other positions and take in what is relevant. It has no built-in sense of order, so position information is added. The original paper added fixed sinusoidal vectors. Many current models, including this one by its configuration, use rotary position embeddings, which rotate the query and key vectors by an angle that depends on position.
A transformer is a stack of identical blocks. Each block has an attention step followed by a feed-forward network applied to each position, with residual connections that add each step's input back to its output. This model has 48 blocks. After the last block, the vector at the final position is projected onto the vocabulary to give the logits from the previous lesson.
Self-attention
Each token's vector x is multiplied by three learned matrices to give a query q, a key k and a value v. Read the query as what this token is looking for, the key as what each token offers, and the value as the content that gets passed on.
For a token at position i, the score against position j is the dot product of q for i and k for j, divided by the square root of d, the key width. A softmax over j turns the scores into attention weights that add up to 1, and the output for i is the weighted sum of the value vectors. For all tokens at once this is softmax(Q·Kᵀ / √d)·V.
A causal mask sets the score to minus infinity for every j after i, so the weight is exactly 0. A token may attend to itself and to earlier tokens, never to later ones. This matches generation, where later tokens do not exist yet, and it lets training compute every position's prediction in one pass.
The division by √d keeps scores in a stable range. The script samples random queries and keys and prints the standard deviation of their dot products, without and with the scaling, for three widths.
python
import numpy as np
rng = np.random.default_rng(0)
for d in (4, 64, 1024):
q = rng.normal(size=(10000, d))
k = rng.normal(size=(10000, d))
dots = (q * k).sum(axis=1)
print(d, round(dots.std(), 2), round((dots / np.sqrt(d)).std(), 2))
text
42.01.0648.081.01102431.971.0
Columns: width d, spread without scaling, spread with.
Without scaling the spread grows with √d. Large scores push softmax toward a one-hot output whose gradients are close to zero, which makes training hard. Scaled scores stay near a spread of 1 at any width.
A worked example
The script below runs one attention step on four made-up token vectors of width 4, with seeded random projection matrices. It prints the weight matrix: row i shows how token i spreads its attention over the keys.
python
import numpy as np
rng = np.random.default_rng(7)
tokens = ["The", "chai", "was", "hot"]
d = 4
X = rng.normal(size=(4, d)) # one made-up vector per token
Wq, Wk, Wv = (rng.normal(size=(d, d)) for _ in range(3))
Q, K, V = X @ Wq, X @ Wk, X @ Wv
scores = Q @ K.T / np.sqrt(d)
future = np.triu(np.ones((4, 4), dtype=bool), k=1)
scores[future] = -np.inf # hide later tokens
weights = np.exp(scores - scores.max(axis=1, keepdims=True))
weights /= weights.sum(axis=1, keepdims=True)
out = weights @ V
print("attention weights (rows = query token, columns = key token)")
print(" " + "".join(f"{t:>7}"for t in tokens))
for t, row in zip(tokens, weights):
print(f"{t:<8}" + "".join(f"{w:7.2f}"for w in row))
print("row sums:", weights.sum(axis=1))
print("output shape:", out.shape)
text
attention weights (rows = query token, columns = key token)
The chai was hot
The 1.000.000.000.00
chai 0.060.940.000.00
was 0.050.660.290.00
hot 0.070.480.240.21
row sums: [1. 1. 1. 1.]
output shape: (4, 4)
The upper triangle is 0 because of the mask. The first row is 1.00 on The, since it can see only itself. Every row sums to 1. The weights come from random matrices, so they show the mechanics and not what a trained model would pay attention to.
Animated sceneCausal attention weights0:16
Watch for each row splitting a total of 1 over the tokens it may see
Read it as steps
Each row fills with weights that add up to 1.
The result row reads off the matrix: the token hot puts 0.48 of its attention on chai, more than on itself.
Heads, layers and window layers
One attention step captures one way of relating tokens. A layer therefore runs several attention heads in parallel, each with its own query, key and value matrices, and joins their outputs. This model has 16 query heads per layer.
Stacking 48 blocks lets later layers work on vectors that earlier layers have already enriched with context. Attention cost grows with the square of the sequence length, which makes long inputs expensive. The model's card and metadata describe a mitigation: five sliding-window layers, in which a token attends only to the previous 1,024 tokens, alternate with one global layer that attends to the whole sequence. Of the 48 layers, 40 are sliding-window and 8 are global. Lesson 6 shows what this saves in memory.
Why is the upper triangle of the weight matrix zero?
The causal mask sets scores for later tokens to minus infinity, so softmax gives them weight 0.
A token can only use itself and earlier tokens.
What would happen to the scores as d grows if the division by √d were removed?
Their spread grows with √d: 2.0 at d = 4, about 32 at d = 1024 in the run.
Softmax would then saturate toward one-hot weights.
Why does a layer use several heads?
Each head learns its own query, key and value matrices, so a layer can relate tokens in several ways at once.
Part 5 · From pretraining to a chat model
Pretraining
Pretraining trains a transformer on a very large text corpus with one objective: at every position, predict the next token. The error is measured as cross-entropy loss, the negative log of the probability the model gave to the token that actually came next, and the parameters are adjusted to lower it. The result is a base model.
The script applies that formula to the three probabilities the model gave at the first answer position in lesson 3, as if that position were one position of training text.
python
import math
# probabilities at the first answer position, from lesson 3's run
probs = {"honey": 0.935, "lemon": 0.043, "a": 0.014}
for token, p in probs.items():
loss = -math.log(p)
print(f"next token {token!r:<8} p = {p:.3f} loss = {loss:.2f}")
text
next token 'honey' p = 0.935 loss = 0.07
next token 'lemon' p = 0.043 loss = 3.15
next token 'a' p = 0.014 loss = 4.27
If the training text continued with honey, the model is barely wrong and the loss is 0.07. If it continued with lemon, the loss is 3.15, and with a it is 4.27. A probability of 1 would give a loss of 0. Training averages this number over a very large number of positions and moves the parameters to lower the average, which shifts probability toward whatever the corpus tends to say next. Nothing in the objective asks whether a continuation is true, only whether it is likely given the text.
A base model is a strong text continuer, not an assistant. Given a question, it may continue with more questions, because that is a plausible continuation of a page of questions. Knowledge from the corpus is stored in its parameters, and the training data ends at a date, which lesson 6 returns to.
From base model to chat model
Two further stages turn a base model into a chat model.
Instruction tuning: supervised fine-tuning on examples that pair a prompt with a good response. The model learns the format of answering instead of continuing.
Preference tuning: people, or other models, compare two responses to the same prompt and pick the better one. In reinforcement learning from human feedback (RLHF), described by Ouyang and co-authors in 2022, a reward model is trained on those comparisons and the chat model is optimised against it. Direct preference optimisation (DPO) uses the comparisons without a separate reward model.
A conversation is a list of messages with the roles system, user and assistant. The model reads one flat sequence of tokens, so a chat template renders the list into that sequence, inserting special tokens that mark where each role starts and ends. This is the overhead of 13 tokens measured in lesson 2. The system message carries standing instructions, and the assistant role marks the model's earlier replies when you resend a conversation.
The script prints what the server's metadata says about the model's template and defaults.
The template field is only {{ .Prompt }}, a pass-through, so the special tokens are not visible in this metadata and the chat format is applied elsewhere in the server. This run shows the sampling defaults from lesson 3 and the capabilities of the model: text completion, vision, audio, tool use and thinking.
Thinking models
A thinking model writes reasoning tokens before its answer. On this server they arrive in a separate reasoning field, and the visible answer is in content. Reasoning tokens are real generated tokens. They count toward completion_tokens, toward max_tokens and toward the bill, even though you do not display them.
The script asks one arithmetic question three ways: thinking left on with a small limit, thinking turned off through reasoning_effort, and thinking on with a larger limit.
python
from llm import chat, client, MODEL
q = [{"role": "user", "content": "What is 17 * 24? Give the number."}]
def show(label, msg, r):
reasoning = (msg.model_extra or {}).get("reasoning") or""
print(label)
print(" finish_reason:", r.choices[0].finish_reason)
print(" completion_tokens:", r.usage.completion_tokens)
print(" content:", repr(msg.content))
print(" reasoning chars:", len(reasoning))
def think(max_tokens): # left on: no reasoning_effort sentreturn client.chat.completions.create(
model=MODEL, messages=q, max_tokens=max_tokens)
r = think(40)
show("thinking left on (default)", r.choices[0].message, r)
msg, r = chat(q, max_tokens=40)
show('reasoning_effort="none"', msg, r)
r = think(400)
show("thinking left on, max_tokens=400", r.choices[0].message, r)
text
thinking left on (default)
finish_reason: length
completion_tokens: 40
content: ''
reasoning chars: 89
reasoning_effort="none"
finish_reason: stop
completion_tokens: 4
content: '408'
reasoning chars: 0
thinking left on, max_tokens=400
finish_reason: stop
completion_tokens: 319
content: '408'
reasoning chars: 618
Output from one run; yours will differ.
With thinking on and max_tokens=40, the model used all 40 tokens on reasoning, so content is empty and finish_reason is length. With thinking off it answered in 4 tokens. With a limit of 400 it reasoned for 319 tokens and then answered. Thinking can help on multi-step problems, and it costs latency and tokens on every call, so turn it on only where an eval shows a gain. The amount of reasoning also varies: a second run of the same script reasoned for 120 tokens instead of 319, so leave headroom in max_tokens rather than sizing it from one call.
Hosted reasoning models may not return the reasoning text at all. OpenAI's reasoning guide, for example, says the reasoning tokens are not visible through the API but still take space in the context window and are billed as output tokens. Read usage, not the visible text, to know what a call cost.
Why can a thinking model return empty content?
Reasoning tokens use up max_tokens before the answer starts, so generation stops with finish_reason of length.
Raise the limit or turn thinking off.
What is the difference between a base model and a chat model?
A base model only continues text. A chat model has been instruction-tuned and preference-tuned to answer messages in the roles system, user and assistant.
What does a chat template do?
It renders the list of role-tagged messages into one token sequence with special tokens marking role boundaries.
Part 6 · Context windows and their limits
The context window
The context window is the largest number of tokens a model can handle in one request, prompt and output together. The model card for Gemma 4 12B gives 256K tokens, which is 2,62,144 in the metadata. A server can run a model with a smaller window than the model supports, because the window has a memory cost. The server on this machine reports a loaded context of 32,768 tokens, and lesson 7 uses that figure. Ollama's own default is 4,096 tokens per its FAQ, so this server was configured with a larger one. Depending on the server, a prompt longer than the allocated window is truncated or rejected, so check what your server actually allocates.
The cost is the KV cache. To produce token n + 1, attention needs the keys and values of all earlier tokens at every layer. Recomputing them for each new token would be wasteful, so the server keeps them in memory. The cache grows with every token.
Per layer and per token, the cache holds the keys and values of every key-value head: heads × (key width + value width) × bytes per number. This model has two layer kinds (from /api/show). A sliding-window layer has 8 key-value heads of width 256 for keys and for values. A global layer has 1 key-value head of width 512. With 2 bytes per number (float16, which is Ollama's default cache type unless configured otherwise):
a sliding-window layer stores 8 × (256 + 256) × 2 = 8,192 bytes per token, and only for the last 1,024 tokens;
a global layer stores 1 × (512 + 512) × 2 = 2,048 bytes per token, for all tokens.
Computing the cache
The script reads these fields from the server and sums over all 48 layers, once as if every layer cached every token and once with the window limit.
python
import httpx
info = httpx.post(
"http://127.0.0.1:11500/api/show",
json={"model": "gemma4:12b"}, timeout=60,
).json()["model_info"]
p = "gemma4.attention."
heads = info[p + "head_count_kv"]
sliding = info[p + "sliding_window_pattern"]
window = info[p + "sliding_window"]
BYTES = 2# float16 cache, Ollama's defaultdef per_token(layer):
sfx = "_swa"if sliding[layer] else""
width = (info[p + "key_length" + sfx]
+ info[p + "value_length" + sfx])
return heads[layer] * width * BYTES
print("layers:", len(heads), "sliding:", sum(sliding))
for n in (8_192, 131_072):
layers = range(len(heads))
full = sum(per_token(i) * n for i in layers)
cut = sum(per_token(i) * (min(n, window) if sliding[i] else n)
for i in layers)
print(f"{n:>7} tokens: all layers {full / 2**30:.2f} GiB,"
f" window-limited {cut / 2**30:.2f} GiB")
At 8,192 tokens the cache is 0.44 GiB with the window limit and 2.62 GiB without it. At 1,31,072 tokens it is 2.31 GiB against 42.00 GiB. The sliding-window layers stop growing after 1,024 tokens, so only the 8 global layers scale with context length. That is why this model can offer a long window at modest cost. The next lesson checks this formula against the memory the server reports.
For another context length, multiply: the window-limited total is 40 × 8,192 × min(n, 1,024) bytes for the sliding layers plus 8 × 2,048 × n bytes for the global ones.
Limits of long context
A big window does not mean perfect recall. Liu and co-authors ("Lost in the Middle", 2023) found that models they tested answered best when the relevant passage was at the start or the end of a long prompt and worse when it was in the middle. Put the instruction and the key facts near the edges, and send less rather than more.
Two more limits come from how the model was trained. The first is the knowledge cutoff: the model has seen nothing after its training data ended. The model card gives January 2025 as the cutoff of its training data. The script asks about something newer. According to python.org, Python 3.14.0 was released on 7 October 2025 and 3.15.0 on 9 October 2026.
python
import textwrap
from llm import chat
q = "Which is the newest stable Python version? Answer in one sentence."
msg, r = chat([{"role": "user", "content": q}], max_tokens=60)
print(textwrap.fill(msg.content, 60))
text
As of my knowledge cutoff in January 2025, the newest stable
version of Python is 3.13.
Output from one run; yours will differ.
The answer names 3.13, two releases behind, and states the cutoff itself. Stating the cutoff is the right behaviour for a model that knows its limits, but the fact it gives is still out of date, and a reader who skips the first clause gets a wrong answer.
The second limit is hallucination: the model produces fluent text that matches the pattern of an answer whether or not the fact is stored in it. Nothing in next-token prediction checks a claim against a source. The remedy is to give the model the facts in the prompt and ask it to answer only from them, which is the pattern known as RAG.
Calculate: how much KV memory does this model need for a context of 32,768 tokens, with the window limit?
Sliding layers: 40 × 8,192 × 1,024 = about 336 MB. Global layers: 8 × 2,048 × 32,768 = about 537 MB. Total about 0.87 GB.
This matches the 0.87 GB computed in the next lesson.
Why do sliding-window layers make long context cheaper?
Each one caches only the last 1,024 tokens, so its memory stops growing. Only the 8 global layers keep growing with context length.
A model has a 256K window. Does that make it safe to paste in 200K tokens and expect every detail to be used?
No. Recall can drop for facts in the middle of a long prompt, and the model cannot know events after its cutoff date.
Part 7 · Choosing and sizing a model
What to choose between
Models come in two forms. A hosted model runs on the provider's servers: you send requests, pay per token and never see the weights. An open-weight model has published parameters that you can run yourself, under a licence. Gemma 4 12B is open-weight under Apache 2.0, per its model card. Running it yourself gives control over where data goes and a fixed hardware cost. A hosted model gives the largest models and no operations work.
Size matters, but with limits. Kaplan and co-authors (2020) found that a model's loss falls smoothly, as a power law, as parameters, data and compute grow. Hoffmann and co-authors (2022) found that for a fixed compute budget, parameters and training tokens should grow together. The practical result is that a smaller model trained on enough data can match a larger one, so compare models on your task.
Factor
Question to ask
Quality
How many cases of your own test set does it pass?
Context
Is the window, as allocated, enough for your prompts?
Modalities
Does it accept images or audio if you need them?
Latency
How many output tokens per second, and how soon is the first?
Cost
Price per million tokens, or hardware and power if self-hosted.
Licence
May you use and ship it the way you plan to?
Data residency
Where is the text processed and stored?
Memory: weights plus cache
Quantisation stores each weight in fewer bits. A 16-bit weight takes 2 bytes. An 8-bit weight takes 1 and a 4-bit weight takes half a byte, at some cost in accuracy. The script lists the tensors of the local model by their quantisation type, computes the average bits per weight, then prints the weight size of a 12 billion parameter model at 16, 8 and 4 bits. The bits per type come from ggml, the tensor library behind llama.cpp: a Q4_K block stores 4-bit values plus scales, effectively 4.5 bits per weight, and a Q6_K block effectively 6.5625.
python
import math
from collections import Counter
import httpx
info = httpx.post("http://127.0.0.1:11500/api/show",
json={"model": "gemma4:12b", "verbose": True},
timeout=120).json()
BITS = {"Q4_K": 4.5, "Q6_K": 6.5625, "F32": 32} # per ggml's blocks
count, params = Counter(), Counter()
for t in info["tensors"]:
count[t["type"]] += 1
params[t["type"]] += math.prod(t["shape"])
total = sum(params.values())
bits = sum(n * BITS[k] for k, n in params.items())
print("quantization:", info["details"]["quantization_level"])
for k in params:
print(f" {k:<5} {count[k]:>3} tensors {params[k]:>14,} weights")
print(f"total {total:,} weights, {bits / total:.2f} bits each")
print(f"tensor data: {bits / 8 / 1e9:.2f} GB")
for b in (16, 8, 4):
print(f"{b:>2}-bit weights of 12B parameters: {12 * b / 8:.0f} GB")
text
quantization: Q4_K_M
F32 338 tensors 770,096 weights
Q6_K 45 tensors 2,579,496,960 weights
Q4_K 284 tensors 9,327,083,520 weights
total 11,907,350,576 weights, 4.95 bits each
tensor data: 7.37 GB
16-bit weights of 12B parameters: 24 GB
8-bit weights of 12B parameters: 12 GB
4-bit weights of 12B parameters: 6 GB
The scheme is called Q4_K_M, but not every tensor is 4-bit. Of 11.9 billion weights, 9.3 billion are Q4_K and 2.6 billion are Q6_K: the token embedding and about half of the attn_v and ffn_down matrices, as the full tensor list shows. The small F32 tensors are normalisation and scaling vectors. The average is 4.95 bits per weight and 7.37 GB of tensor data, against about 24 GB in 16-bit form.
The download that /api/tags reports is larger, 7.56 GB, because it also counts a separate file for the vision and audio encoder (0.18 GB in this model's manifest) and the tokeniser stored in the model file. Divide the download size by the parameter count and you get a misleading 5.08 bits per weight.
Memory to run a model is roughly the weights plus the KV cache, plus a smaller runtime overhead. The script adds the cache from lesson 6 at the context the server allocated and compares the sum with the figure the server reports for the loaded model.
context allocated: 32768
weights 7.56 GB + KV cache 0.87 GB = 8.43 GB
memory the server reports: 8.42 GB
Animated sceneWill it fit in 16 GB0:16
Total in memory: 8.43 GB (computed from /api/show on this machine)
Read it as steps
Weights plus cache, from the numbers on this machine.
The sum, 8.43 GB, is within 0.01 GB of the 8.42 GB the server reports, which is consistent with the cache formula and with float16, Ollama's default cache type. A 16 GB machine holds this model with room for the operating system. The two numbers that decide whether a model fits are the size of its weights and the KV cache at the context you allocate.
Speed and modalities
Speed is the number of output tokens per second. Ollama's native endpoint reports eval_count, the output tokens, and eval_duration, the generation time in nanoseconds.
python
import httpx
r = httpx.post("http://127.0.0.1:11500/api/generate", json={
"model": "gemma4:12b", "stream": False, "think": False,
"prompt": "Write two sentences about the Ganga river.",
"options": {"num_predict": 120, "temperature": 0},
}, timeout=300).json()
seconds = r["eval_duration"] / 1e9
print("output tokens:", r["eval_count"])
print("seconds:", round(seconds, 2))
print("tokens/second:", round(r["eval_count"] / seconds, 1))
print("prompt tokens:", r["prompt_eval_count"])
That is about 90 output tokens per second here. Two later runs on the same machine printed 78.0 and 76.5, so read a speed as a range, not a constant. Time to first token and prompt processing speed are separate numbers that matter for long prompts.
The model card lists text, image and audio input, and the capabilities in lesson 5 include vision. A Chat Completions request carries an image as a content part with a base64 data URL. The script draws a green rectangle with Pillow and asks the model to describe it.