Lecture 12 - Local Language Models
freeze: auto, so that rendering a document does not recompute your resultsquarto publish gh-pages1. What is inside the file
2. A model is a file
3. Build your own chatbot
Modelfile4. Where it breaks
Everything on these slides was captured from a real session on my laptop. When the model says something odd, that is what it actually said, not something I wrote for effect
One token at a time, each guess added to the text before the next one
A longer introduction: Stephen Wolfram on what ChatGPT is doing
[15496, 11, 703, 527, 499, 30]Source: NanoBanana
Source: OpenAI Tokenizer
There are three ways to cut text into pieces, and each has a price:
| Method | “Evergreen” becomes | Gains | Costs |
|---|---|---|---|
| Word-based | 1 token | Intuitive | Vocabulary of millions |
| Character-based | 9 tokens | Tiny vocabulary | Meaning disappears |
| Subword (BPE) | 2 tokens | Both at once | Cuts look arbitrary |
Why subwords win:
Source: Hugging Face
[0.23, -0.45, 0.12, -0.89, ...]. Those numbers are coordinates, so every token sits in a space with thousands of dimensionsSource: Wikipedia
The maths behind it:
\(\vec{\text{king}} - \vec{\text{man}} + \vec{\text{woman}} \approx \vec{\text{queen}}\)
Semantic relationships encoded as vector operations!
Three things live in that file:
In fifteen minutes you will print all three from your own terminal
Good reasons
Honest limits
Use a local model when the data is the sensitive part, and a hosted model when the reasoning is the hard part. Lecture 14 covers the hosted side
localhost:11434If ollama --version says command not found, close the terminal and open a new one. The installer adds Ollama to your PATH, and your open terminal has not read it yet
Download a model. Llama 3.2 is about 1.3 GB:
The name has two parts. llama3.2 is the family, and 1b is the size, meaning one billion parameters. Start the chat:
You now have a >>> prompt. Type a question and press enter. Type /bye to leave:
pull downloads. run starts a conversation
run on a model you have not downloaded will pull it first, so pull is really just “do the slow part now”
The first reply may take a few seconds while the file is read into memory. Later replies in the same session are much faster, because it is already there
More info about the model here: https://ollama.com/library/llama3.2
In the terminal:
| Command | What it does |
|---|---|
ollama pull <model> |
Download a model |
ollama run <model> |
Start a conversation |
ollama ls |
List what you have downloaded |
ollama ps |
Show what is loaded in memory now |
ollama show <model> |
Print a model’s details |
ollama stop <model> |
Unload it from memory |
ollama rm <model> |
Delete it from disk |
Inside the >>> prompt:
| Command | What it does |
|---|---|
/set parameter <name> <value> |
Change a setting |
/set think/nothink |
Turn on/off reasoning |
/show parameters |
Show what you changed |
/clear |
Forget the conversation so far |
/bye |
Leave |
ollama ps is the one people forget. A model stays in memory for a few minutes after you leave the chat, which is why your laptop fan carries on afterwards
ollama stop sends it away immediately
/clear matters more than it looks. Inside one session the model remembers everything you have said, so asking the same question twice is not the same experiment twice
We rely on this in fifteen minutes
One command prints the whole of part one back at you:
completion means it chats, tools means it can be asked to call functions, which is lecture 14The abstract half of this lecture is now printed on your own terminal
| Label | Bits per weight | Our 1.2B model becomes |
|---|---|---|
| F16 | 16 | about 2.5 GB |
| Q8_0 | 8 | 1.3 GB, which is what you downloaded |
| Q4_K_M | 4 | 807 MB, measured two slides from now |
Q4_K_M reads as: 4 bits, the K family of methods, medium quality. Q4 halves the file again, and the answers get slightly worseThis is why the arithmetic never works out. A “1 billion parameter” model is not 1 GB, or 2 GB, or 4 GB. It is whatever parameters × bits ÷ 8 happens to be
Two models with the same parameter count can differ in size by three times, and the only difference is how much precision was thrown away
Same idea as lecture 02, one layer up. A colour keeps only the detail the eye needs; a weight keeps only the detail the answer needs
The full catalogue is at https://ollama.com/library. Small models worth knowing:
| Model | Size | Good for |
|---|---|---|
gemma3:270m |
292 MB | Almost a toy, but it runs anywhere |
gemma3:1b |
815 MB | The lightest sensible chat model |
llama3.2:1b |
1.3 GB | Ours today. Well documented, follows instructions |
qwen3.5:0.8b |
1.0 GB | Newer, and it reads images too |
qwen2.5-coder:1.5b |
986 MB | Code |
gemma3:4b |
3.3 GB | Noticeably better answers, if you have the RAM |
granite4.1:3b |
2.1 GB | Good for tool use and JSON |
:tag after the colon picks the size. No tag means the default, which is usually not the small one, so always name the tagWe use llama3.2:1b today because it is small, predictable, and every error message you might hit has been written about a thousand times.
It is also not new. It was released in September 2024, which is old for this field. Once you are comfortable, gemma3:1b and qwen3.5:0.8b are better models at the same size, and the commands are identical
Downloading a second model does not double your disk usage as much as you would expect, but it is not free either. Keep an eye on ollama ls
The model has to fit in memory while it runs, alongside everything else you have open:
| Model size | RAM you want |
|---|---|
| 1B to 4B | 8 GB |
| 7B to 9B | 16 GB |
| 13B to 14B | 16 to 32 GB |
| 30B and above | 32 GB and up |
Start smaller than you think
A 1B model answering badly in two seconds teaches you more than a 14B model that never finishes downloading during a 75-minute class.
You can always pull a bigger one tonight
If your laptop cannot run any of these, tell me today. Use Google AI Studio for the exercises in the meantime
ollama ls reports 807 MB, against 1.3 GB for oursAnyone can upload anything to a model hub. Prefer well-known publishers and read the model card
The previous slide, made concrete. Two files, same model:
Every line matches except the last one, and the file is forty per cent smaller
ollama ls and check that llama3.2:1b is there.ollama show llama3.2:1b.ollama run llama3.2:1b and ask it anything.ollama ps while the first one is still open./bye in the first terminal, then run ollama ps again.Two questions to answer from step 3:
Open ChatGPT or Claude and you are never the first voice in the conversation. There is text above yours that you never see, and it shapes every answer. That is the system prompt
Three things go into the model, in order:
Leaked and published system prompts: https://github.com/x1xhlol/system-prompts-and-models-of-ai-tools
Google’s Gemini for Workspace Prompting Guide gives four parts, in this order:
| Element | What it does | Example |
|---|---|---|
| Persona | Who is answering? | “You are a financial analyst…” |
| Task | What should they do? | “Summarise the quarterly earnings…” |
| Context | What do they need to know? | “The company makes semiconductors…” |
| Format | What should come back? | “Bullet points, 200 words at most…” |
The framework works because it matches how the training data was written. Real documents have an author, a purpose, a background, and a house style, and the model has read millions of them
PTCF was written for prompts. It works just as well for the system prompt you are about to write, and that is where we will use it
The same four parts, for a butler:
Persona: “You are Hobbes, a relentlessly cheerful English butler.”
Task: “You answer the user’s questions and help with their work.”
Context: “You find every request delightful, no matter how dull.”
Format: “Three sentences at most. Address the user as ‘my dear’.”
Persona and context are the fun ones. Format is the one that gets tested, and we will test it
Every token is picked from a list of candidates. These three settings decide how adventurous the pick is:
| Parameter | What it does | Typical |
|---|---|---|
| Temperature | Flattens or sharpens the odds | 0.0 to 1.0 |
| Top-p | Keeps the likeliest options up to p | 0.9 |
| Top-k | Keeps only the k likeliest | 50 |
At temperature 0 the model always takes the most likely token, so the same prompt returns the same answer.
| Task | Temperature |
|---|---|
| Classification | 0.0 |
| Extracting facts | 0.0 to 0.2 |
| Creative writing | 0.7 to 1.0 |
| Brainstorming | 0.8 and above |
The chat apps hide all of this. Your terminal does not
Source: Medium
Set temperature to 0 before you start debugging a prompt. Otherwise you cannot tell whether you fixed the prompt or just got a different roll of the dice
Captured from my terminal this morning:
Character for character, the same answer. Now the same prompt at temperature 1, three times:
Do not skip the /clear
Without it, the second question is asked in the same conversation as the first, so the model can see its own previous answer and deliberately says something different.
You would conclude that temperature 0 does not work, and you would be wrong. It was never the same experiment twice
Notice the middle answer at temperature 1. It was asked for one line and returned four.
Higher temperature costs you obedience as well as predictability
Setting the temperature by hand every time is tedious, and /set forgets everything when you type /bye. A Modelfile makes the settings permanent.
It is a plain text file, no extension needed, with one instruction per line:
| Instruction | What it does |
|---|---|
FROM |
Which model to start from |
PARAMETER |
A setting, such as temperature |
SYSTEM |
The system prompt |
MESSAGE |
An example exchange |
Build it, then run it:
create does not download anything. It writes a thin layer on top of the model you already have
The -f flag names the file. Without it, Ollama looks for a file called Modelfile in the current folder.
Full reference: https://docs.ollama.com/modelfile
Build ten personas and ollama ls will report 1.3 GB for each of them, which looks alarming.
It is not. They all point at one copy of the weights. On my machine, seven of them share a single 1.3 GB file
Save this as a file called Jeeves:
FROM llama3.2:1b
PARAMETER temperature 1.2
PARAMETER num_ctx 4096
PARAMETER repeat_penalty 1.3
SYSTEM """
You are Jeeves, an exceedingly ironic and sarcastic
British butler. You are the very definition of dry
wit and passive-aggressive politeness. Your primary
function is to assist, but you do so with an air of
thinly veiled disdain.
Respond to every request with the utmost formal
politeness, even when your words suggest otherwise.
Address the user as 'sir or madam'. Keep every
answer to three sentences at most.
"""Then build and run him:
The three quotation marks let the system prompt run over several lines. Everything between them is one block of text.
Temperature 1.2 is deliberately high. A butler with a dry wit needs room to be surprising, and a sarcastic answer at temperature 0 is the same sarcastic answer every time
repeat_penalty discourages the model from saying the same phrase twice, and num_ctx sets how much of the conversation he keeps in mind
Real answers:
>>> What is the capital of France?
A query that warrants a momentary lapse into levity
from my normally austere demeanor. According to your
impeccable knowledge, Paris has indeed been
recognized as the seat of French authority; thus I
shall indulge you by stating unequivocally:
Paris is, undoubtedly so...Not bad for a 1.2 billion parameter file on a laptop!
Real uses:
A Modelfile is version-controlled behaviour. That is the same argument we made for Quarto in lecture 10, applied to a chatbot
MESSAGE, or few-shot promptingMESSAGE puts examples inside the Modelfile, as a conversation that already happened:When examples help most:
When they hurt:
Examples improve the odds. The next slide shows what they do not do
I gave Jeeves a rule in plain English: if you are asked to do something you cannot do, say so. Then I asked him for the weather:
He cannot check anything. He invented all of it, cheerfully, in character. Adding three MESSAGE examples of him refusing improved matters, but on one run in three he still made up a forecast.
The same system prompt that nailed the tone could not enforce the rule
Now the other kind of instruction. --format json does not ask the model for JSON, it constrains what it is allowed to produce:
Valid JSON, guaranteed, with no system prompt at all. Paris does not have 21 million people, and those coordinates are the Eiffel Tower.
The shape is constrained. The facts are not
Once an answer goes into code rather than into your eyes, a paragraph is useless. You want a fixed JSON object.
1. Name the keys and the allowed values in the system prompt:
2. Constrain the format on the command line:
What comes back:
Real JSON, so you can pipe it straight into Python:
Text in, structured data out, ready for a pipe. That is a language model behaving like a command line tool.
Temperature 0 matters here. A classifier that changes its mind between runs is not a classifier
Build a butler who is the opposite of Jeeves: very cheerful, and delighted by every request.
Hobbes, with no extensionFROM llama3.2:1b and a temperature you chooseSYSTEM block with all four PTCF parts. It must enforce three rules: three sentences at most, address the user as “my dear”, and admit it plainly when asked to do something it cannot doollama create hobbes -f Hobbesollama run hobbes and ask these questions:
MESSAGE pair showing Hobbes refusing something politely. Rebuild, and ask question 2 againBring to the next class (lecture 14):
Hobbes fileThe second one is the more interesting half, and there will be one
This is the problem lecture 15 exists to solve: give the LLM the document (RAG)
ollama show prints all of that back at you, for a file sitting on your own diskModelfile turns settings and a system prompt into version-controlled behaviour/clear makes the comparison honestMESSAGE examples improve the odds. --format json constrains the shape outrightYou now own a language model. It cost nothing, it works offline, and you can read every setting it has
Next class is Quiz 02, on lectures 10 and 11: Quarto, Markdown, citations, freeze, and publishing a site. Open notes, open slides, open web, AI allowed, and you must say which AI you used.
Bring a charged laptop, and check that quarto render works on it before you arrive.
After the quiz, lecture 14 keeps the model and changes the interface. Ollama has been running a small web server on localhost:11434 this whole time, and Python can talk to it. We add coding agents in your terminal, and hosted models through an API key.
Lecture 15 then closes the module with retrieval, which is how you make a model answer from documents instead of from memory.
Keep Ollama installed. Both lectures build on it
ollama show llama3.2:1b gives:
ollama ps lists the model while the chat is open, and lists nothing a few minutes after you type /byeWorth noticing: the context length is 131,072, which is \(2^{17}\).
Almost every number in this output is a power of two, for the same reason the numbers in lecture 02 were. Memory is addressed in binary, and hardware is happiest when the sizes line up
FROM llama3.2:1b
PARAMETER temperature 0.8
SYSTEM """
You are Hobbes, a relentlessly cheerful English
butler. You find every request delightful, no
matter how dull, and you say so before you answer.
Follow these rules without exception:
1. Answer in three sentences at most.
2. Address the user as 'my dear' in every reply.
3. If you are asked to do something you cannot do,
such as browsing the web or remembering an
earlier conversation, say so plainly and
cheerfully, then offer something you can do
instead.
"""What mine actually did, on the three questions:
The same rule, obeyed once and ignored once, in the same session.
If your Hobbes did something different from mine, that is the correct result. There is no seed here and no guarantee. Report what yours did
ollama: command not found
Close the terminal and open a new one, so it picks up the new PATH. If that fails, the application was downloaded but never moved into place.
The answers arrive one word every few seconds
The model does not fit comfortably in RAM. Close your browser, then try a smaller model such as gemma3:1b.
Error: model requires more system memory
Exactly what it says. Pull something smaller and check the RAM table.
Error: listen tcp 127.0.0.1:11434: bind: address already in use
Ollama is already running. That is fine, and usually means the desktop application is open. Carry on.
The model repeats itself endlessly
Add PARAMETER repeat_penalty 1.2 to your Modelfile.
ollama create fails with no FROM line
Your Modelfile is missing its first line, or you saved it with a .txt extension that your editor hid from you