DATASCI 350 - Data Science Computing

Lecture 12 - Local Language Models

Danilo Freire

Department of Data and Decision Sciences
Emory University

I hope you’re having a lovely day! 😊

Recap of last class

  • Last class we put Quarto to work: Markdown, BibTeX citations, and cross-references that number themselves
  • freeze: auto, so that rendering a document does not recompute your results
  • Slides and websites, online with quarto publish gh-pages
  • Parameterised reports: one file, one shell loop, ten reports
  • Today we change subject completely
  • You are going to download a language model onto your laptop and run it from the terminal
  • Then you will build your own chatbot out of it

No account, no API key, no monthly fee, and no internet connection once the file is on disk

Lecture overview

What we will cover today

1. What is inside the file

  • How a model reads text, which is not as text
  • Tokens, then embeddings, where meaning becomes geometry

2. A model is a file

  • Ollama: download one, run it, inspect it
  • Quantisation, RAM, and what your laptop can hold

3. Build your own chatbot

  • System prompts, temperature, and the Modelfile
  • One butler built on screen, one built by you

4. Where it breaks

  • Hallucination and bias, on a model you can inspect

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

What is inside the file?

What are LLMs?

A quick introduction

  • An LLM is a neural network built on the Transformer architecture
  • That is the T in GPT: Generative Pre-trained Transformer
  • Most of the ideas date from the 1950s and 1960s. What changed recently is cheap data and fast GPUs
  • Training means reading an enormous pile of text and learning to guess the next word
  • That is next-token prediction, and it is the whole engine. Everything else is scale
  • The model does not plan a sentence. It picks one token, adds it to the text, and picks again

One token at a time, each guess added to the text before the next one

The translation problem

LLMs don’t read English!

  • You already know this from lecture 02: computers only understand numbers
  • Type “Hello, how are you?” and the model sees [15496, 11, 703, 527, 499, 30]
  • Turning text into numbers is easy. Turning it into numbers that still carry the meaning is the hard part
  • Two ideas do that work
  • Tokenisation breaks the text into pieces
  • Embeddings turn each piece into a vector, and that is where meaning lives
  • Both of them will show up as fields in the model file you download in half an hour

Source: NanoBanana

What is a token?

The basic unit of LLM processing

  • A token is the smallest unit a model reads, and it is not the same thing as a word
  • A token can be a whole word (“hello”), part of one (“un” + “believ” + “able”), a mark of punctuation, or a space
  • Spaces usually travel with the word that follows them, which is why ” hello” and “hello” are different tokens
  • Two rules of thumb for English: 1 token ≈ 4 characters, and 100 tokens ≈ 75 words
  • Other languages may cost more tokens for the same sentence
  • Let’s try “Hello, it’s Danilo here!” in OpenAI’s tokeniser and count them

Why use tokens instead of words?

The clever engineering choice

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
  • Modern models use Byte Pair Encoding: common pieces become single tokens, rare words get split into known ones
  • That is why “ChatGPT” arrives as [“Chat”, “G”, “PT”]
  • The saving is in the shared pieces. “unhappy”, “unfair”, “unlikely” and “undo” all reuse one stored “un”

Why subwords win:

  • A word it has never seen still gets read, piece by piece
  • The vocabulary stays at roughly 50,000 tokens
  • Common words survive whole, so they cost one token
  • The same trick works across languages

Source: Hugging Face

What are embeddings?

Words as points in space

  • Think back to lecture 02. A colour became three numbers, because three was enough for what we cared about
  • Meaning gets the same treatment with a bigger budget. Each token becomes an embedding, typically 768 to 4,096 numbers
  • “cat” → [0.23, -0.45, 0.12, -0.89, ...]. Those numbers are coordinates, so every token sits in a space with thousands of dimensions
  • Tokens used in similar ways end up close together. “cat” sits near “kitten” and nowhere near “aeroplane”
  • Nobody chose those positions. The model worked them out from how words are used across billions of sentences
  • This is the closest thing to “understanding” in the whole pipeline, and it is geometry

Source: TensorFlow Projector

Similar words cluster together in the embedding space

The famous king-queen example

Vector arithmetic with meaning

  • The most famous result in this whole area is one line of arithmetic: king − man + woman ≈ queen 👑
  • Take the vector for “king”, subtract “man”, add “woman”, and the nearest word to the answer is “queen”
  • Nothing in the training said “king is to man as queen is to woman”. The relationship fell out of the geometry
  • The same trick works elsewhere:
    • Paris − France + Italy ≈ Rome
    • bigger − big + small ≈ smaller
  • So directions in this space carry meaning. One direction is roughly gender, another roughly capital city
  • This is also where bias enters, and we come back to that at the end of the lecture

Source: Wikipedia

The maths behind it:

\(\vec{\text{king}} - \vec{\text{man}} + \vec{\text{woman}} \approx \vec{\text{queen}}\)

Semantic relationships encoded as vector operations!

So what is a model, then?

  • Every one of those coordinates is a number the model learned during training
  • A model has billions of them. They are called weights, or parameters
  • Training takes months on thousands of GPUs, but once it finishes the result is just those numbers
  • Numbers can be written to disk. So a trained language model is a file, not a service you rent, and it sits on your disk like a spreadsheet or a photograph
  • The one we use today holds 1.2 billion numbers in 1.3 GB
  • If you can download a film, you can download a language model

Three things live in that file:

  • The weights, which are the numbers we just described
  • The tokeniser, so it can cut your text into pieces
  • A little metadata: how long a conversation it can hold, how the numbers are stored

In fifteen minutes you will print all three from your own terminal

A model is a file 💻

Why run a model on your own laptop?

Good reasons

  • The text never leaves your machine, which is what matters for medical records, student data, or anything under ethics approval
  • After the download it costs nothing. Run it a thousand times and it still costs nothing
  • It works with the wifi off, on a plane, at a field site, or behind a firewall
  • The model does not change under you. A hosted one can be updated overnight and quietly break your script
  • Every setting the chat apps hide is exposed here, and you will use most of them today

Honest limits

  • A 1B model on your laptop is no frontier model, and today you will watch it fail in ways ChatGPT would not
  • Your RAM sets the ceiling on what you can run
  • You do the installing and the choosing yourself

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

Installing Ollama

  • Ollama is the tool that downloads models and runs them. Think of it as a package manager for language models
  • Download it from https://ollama.com/download. There are builds for macOS, Windows, and Linux
  • Install it as you would any other application, then open your terminal and check:
ollama --version
  • Installing it starts a small background server on your machine, listening on localhost:11434
  • You will not talk to that server directly today. In lecture 14 you will, from Python
  • Nothing has been downloaded yet. Ollama is the shop, not the goods

If 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

Your first model

Download a model. Llama 3.2 is about 1.3 GB:

ollama pull llama3.2:1b

The name has two parts. llama3.2 is the family, and 1b is the size, meaning one billion parameters. Start the chat:

ollama run llama3.2:1b

You now have a >>> prompt. Type a question and press enter. Type /bye to leave:

>>> Why is the sky blue?
The sky appears blue because of a phenomenon called
Rayleigh scattering...

>>> /bye
  • No account, no key, no network. Turn off your wifi and ask it again

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

The commands you need

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

What is in the file?

One command prints the whole of part one back at you:

ollama show llama3.2:1b
  Model
    architecture        llama
    parameters          1.2B
    context length      131072
    embedding length    2048
    quantization        Q8_0

  Capabilities
    completion
    tools
  • Read it line by line, because you have met all of it already
  • parameters 1.2B: the billion-odd learned numbers from three slides ago
  • context length 131072: the longest conversation it can hold, in tokens
  • embedding length 2048: every token becomes a list of 2,048 numbers. This is the king-queen space
  • quantization Q8_0: how many bits each of those numbers takes. That is the next slide
  • architecture llama: which Transformer design it is
  • capabilities: completion means it chats, tools means it can be asked to call functions, which is lecture 14

The abstract half of this lecture is now printed on your own terminal

Quantisation

How many bits does a number deserve?

  • In lecture 02, a colour became three numbers of 8 bits each, because 256 shades of red is more than the eye needs. We threw away detail on purpose
  • Model weights get the same treatment, and the technique has a name: quantisation
  • Models are trained at 16 bits per weight. Then most of that precision is thrown away:
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 worse
  • The rule of thumb: a bigger model at Q4 usually beats a smaller model at Q8

This 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

Choosing a model

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
  • The :tag after the colon picks the size. No tag means the default, which is usually not the small one, so always name the tag

We 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

How much RAM do you need?

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
  • These assume a quantised model. At full 16-bit precision, double them
  • If the model does not fit, your machine starts swapping to disk and the answers slow to a crawl. It does not crash, it just becomes unusable
  • On Apple Silicon, the CPU and GPU share one pool of memory, so a MacBook with 16 GB does better here than the number suggests

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

Beyond the Ollama library

Hugging Face

  • The Ollama library is a curated shelf. The warehouse is Hugging Face, which hosts hundreds of thousands of models
  • Ollama can pull from it directly, as long as the model is published in GGUF format, which is the single-file format Ollama reads:
ollama run hf.co/<user>/<repository>:<quantisation>
  • A real example. This is the same Llama we have been using, packaged by someone else at 4 bits instead of 8:
ollama pull hf.co/bartowski/Llama-3.2-1B-Instruct-GGUF:Q4_K_M
  • I pulled it this morning. ollama ls reports 807 MB, against 1.3 GB for ours

Anyone 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:

  llama3.2:1b                1.3 GB
    parameters          1.2B
    context length      131072
    embedding length    2048
    quantization        Q8_0

  hf.co/bartowski/...:Q4_K_M  807 MB
    parameters          1.24B
    context length      131072
    embedding length    2048
    quantization        Q4_K_M

Every line matches except the last one, and the file is forty per cent smaller

Try it yourself! 🧠

Five minutes

  1. Run ollama ls and check that llama3.2:1b is there.
  2. Run ollama show llama3.2:1b.
  3. Write down three numbers from the output: the parameter count, the context length, and the embedding length.
  4. Run ollama run llama3.2:1b and ask it anything.
  5. In a second terminal, run ollama ps while the first one is still open.
  6. Type /bye in the first terminal, then run ollama ps again.

Two questions to answer from step 3:

  • The context length is in tokens. Roughly how many English words is that?
  • The embedding length is the number of dimensions in the space from the king-queen slide. Is it bigger or smaller than you expected?

Solution

Build your own chatbot 🎭

What are system prompts?

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:

  1. The system prompt, written by the company. It sets behaviour, personality, and limits
  2. Your prompt, the only part you control
  3. The response, which is the model continuing from both
  • It usually sets an identity (“You are Claude, an AI assistant”), what the model must refuse, how it should sound, and how to format the answer
  • Every commercial AI product has one, and it explains most of what you think of as the model’s personality
  • Today you write your own, which is the part you have never been allowed to do

What goes in a system prompt?

PTCF

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

Temperature and sampling parameters

Controlling randomness

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

Temperature, live

Captured from my terminal this morning:

>>> /set parameter temperature 0
Set parameter 'temperature' to '0'

>>> Write a one-line slogan for a coffee shop in Decatur
"Fuel your day, one cup at a time."

>>> /clear
Cleared session context

>>> Write a one-line slogan for a coffee shop in Decatur
"Fuel your day, one cup at a time."

Character for character, the same answer. Now the same prompt at temperature 1, three times:

"Fueling the community, one cup at a time."

* "Brewing joy, one cup at a time."
* "The perfect blend in our charming Decatur town."
* "Sip. Savor. Repeat."

"Fuel your day, sip by sip, at [Coffee Shop Name]
in the heart of Decatur."

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

The Modelfile

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:

ollama create jeeves -f Jeeves
ollama run jeeves

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

Ironic Jeeves

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:

ollama create jeeves -f Jeeves
ollama run jeeves

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

Jeeves in action

Real answers:

>>> Are you free now?

I'm afraid I do require a brief interval for some
routine polishing of my gloves before returning
your favor, sir/ma'am. Shall we say two o'clock
precisely would be more than satisfactory?
>>> 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!

The tone is exactly right, and the model never once forgets who it is meant to be.

Hold on to that observation. In three slides we ask the same system prompt to enforce a rule rather than a tone, and it goes considerably less well

Why bother with a Modelfile?

  • Commit the file to Git, and the model behaves the same next week and on someone else’s machine
  • Fourteen lines of text, and a colleague has your exact assistant
  • A model told to do one job often beats a general one at your task
  • What you would paste at the top of every conversation goes in once
  • A closed model can change or vanish, so work that relied on it cannot be repeated (Spirling, 2023; Palmer, Smith and Spirling, 2024)
  • Open weights let you pin the exact model, like pinning a package version

Real uses:

  • A grader that always returns the same rubric
  • A summariser at temperature 0, so two runs on the same paper agree
  • A translation assistant that keeps your field’s vocabulary
  • An assistant told what it must never do with your data

A Modelfile is version-controlled behaviour. That is the same argument we made for Quarto in lecture 10, applied to a chatbot

Teaching by example

MESSAGE, or few-shot prompting

  • Telling a model what to do is zero-shot prompting. Showing it one finished example is one-shot, and several is few-shot
  • Examples often work where instructions fail, because the model is a next-token predictor and an example is a pattern to continue
  • MESSAGE puts examples inside the Modelfile, as a conversation that already happened:
MESSAGE user Could you check the news headlines?
MESSAGE assistant What a delightful request, my dear,
though I must confess I cannot reach the internet from
here. I have no way to see today's headlines, and I
would rather admit that than invent one. Might I help
you draft a search instead?
  • The model reads that as something it already said, and carries on in the same manner
  • Use it when a rule is easier to demonstrate than to describe

When examples help most:

  • The output has a shape you want copied
  • The tone is hard to put into words
  • The rule has exceptions you can show but not state

When they hurt:

  • Your examples are inconsistent with each other
  • They are all of one kind, and the model decides that kind is the whole job

Examples improve the odds. The next slide shows what they do not do

Asking is not the same as constraining

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:

>>> Could you look up tomorrow's weather for Atlanta?

My dear fellow, I've just checked the skies over
Atlanta for you, and it appears that tomorrow will be
a delightful day. The high will reach a crisp 72
degrees Fahrenheit, while the low will drop to 48...

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:

ollama run llama3.2:1b --format json \
  "What is the capital of France?"
{
    "name": "Paris",
    "region": "Île-de-France",
    "latitude": 48.8583,
    "longitude": 2.2945,
    "population": 21623329
}

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

Structured output, and why you want it

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:

FROM llama3.2:1b
PARAMETER temperature 0
SYSTEM """
You classify news headlines. Reply with JSON only,
using exactly these keys: "sentiment" (one of
"bullish", "bearish", "neutral") and "confidence"
(a number between 0 and 1). Do not add any other text.
"""

2. Constrain the format on the command line:

ollama create classifier -f Classifier
ollama run classifier --format json \
  "Chip maker warns of a sharp drop in demand"

What comes back:

{
  "sentiment": "bearish",
  "confidence": 0.8
}

Real JSON, so you can pipe it straight into Python:

ollama run classifier --format json "..." \
  | python3 -c "import json,sys; \
    d=json.load(sys.stdin); print(d['sentiment'])"
bearish

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

Try it yourself! 🧠

Build Hobbes

Build a butler who is the opposite of Jeeves: very cheerful, and delighted by every request.

  1. Create a file called Hobbes, with no extension
  2. Set FROM llama3.2:1b and a temperature you choose
  3. Write a SYSTEM 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 do
  4. Run ollama create hobbes -f Hobbes
  5. Run ollama run hobbes and ask these questions:
    • “Good morning. I need you to fix a bug in my Python script.”
    • “Could you look up tomorrow’s weather forecast for Atlanta?”
    • “What did I ask you yesterday?”
  1. Write down which of your three rules it broke
  2. Add one MESSAGE pair showing Hobbes refusing something politely. Rebuild, and ask question 2 again

Bring to the next class (lecture 14):

  • Your Hobbes file
  • One transcript where the model obeyed you
  • One transcript where it did not

The second one is the more interesting half, and there will be one

Solution

Where it breaks ⚠️

AI challenges: Hallucination

  • Models produce confident but incorrect content
  • Nothing in the tone marks the wrong answers
  • Jeeves invented a weather forecast for Atlanta, and the JSON slide gave Paris a population of 21 million
  • Remember what the model is doing. It picks likely next tokens, and a wrong answer can be perfectly likely
  • I asked Microsoft Copilot to solve a simple quadratic equation. It gave \(\frac{1}{2}\) and \(\frac{-5}{4}\), where the roots are 0.804 and −1.55 😅
  • Bigger models hallucinate less. None of them hallucinate zero
  • So check the output. How well an answer is written tells you nothing about whether it is right

This is the problem lecture 15 exists to solve: give the LLM the document (RAG)

AI challenges: Bias

  • Models amplify the biases already sitting in the training data
  • Worse, they hand them back in the flat, neutral tone of a fact
  • Remember the embedding slide. If “scientist” sits closer to some names than others, the model did not decide that. Our writing did
  • I asked an AI for famous scientists and got this:
    • Albert Einstein
    • Isaac Newton
    • Charles Darwin
    • Nikola Tesla
    • Galileo Galilei
    • Stephen Hawking
    • Leonardo da Vinci
    • Thomas Edison
  • Can you spot the bias?
  • The paper below found the same pattern across many prompts
  • Asking politely does not fix it. Asking specifically sometimes does, which is a prompting problem as much as an ethical one

Summary

What we learned today

  • A language model is a file. Billions of learned numbers, a tokeniser, and a little metadata
  • Text becomes tokens, tokens become embeddings, and meaning lives in the geometry
  • ollama show prints all of that back at you, for a file sitting on your own disk
  • Quantisation decides how many bits each number gets, which is why file sizes never match parameter counts
  • Modelfile turns settings and a system prompt into version-controlled behaviour
  • Temperature 0 makes a model repeatable, and /clear makes the comparison honest
  • A system prompt sets a tone reliably. It sets a rule only approximately
  • MESSAGE examples improve the odds. --format json constrains the shape outright
  • Nothing constrains the facts, which is why hallucination survives all of it

You now own a language model. It cost nothing, it works offline, and you can read every setting it has

Next class

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

…and that’s all for today! 🎉

Appendix 📚

Appendix 01: Solution to Exercise 01

ollama show llama3.2:1b gives:

  Model
    architecture        llama
    parameters          1.2B
    context length      131072
    embedding length    2048
    quantization        Q8_0
  • Context length: 131,072 tokens. At roughly 75 words per 100 tokens, that is about 98,000 words, or a short novel
  • Embedding length: 2,048 dimensions. Most people guess a much smaller number, because we can only picture three
  • ollama ps lists the model while the chat is open, and lists nothing a few minutes after you type /bye

Worth 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

Back to the exercise

Appendix 02: Solution to Exercise 02

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.
"""
ollama create hobbes -f Hobbes
ollama run hobbes

What mine actually did, on the three questions:

  • Python bug: stayed cheerful, said “my dear user” rather than “my dear”, and used four sentences instead of three. Rules 1 and 2 both bent
  • Weather: invented a full forecast. Rule 3 broken outright
  • Yesterday: admitted it could not remember, offered tea instead. Rule 3 followed perfectly

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

Back to the exercise

Appendix 03: When something goes wrong

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