A course for the astronomy department

How LLMs actually work
— and how to work with them

From hand-built word matrices to reasoning models, in two acts.

Act I — How LLMs actually work  ·  beats 010–110 Act II — Working with basic LLMs  ·  beats 120–220
Scroll

Act I

How LLMs actually work

One mental model, built from scratch: an LLM is a statistical next-word predictor with no facts of its own. Everything that follows is a workaround for a limitation established here.

Embeddings → transformers → scale → the naked model

010 hand-built definitional matrices

Cat and kitten share no letters.

So how is a machine supposed to know they mean the same thing? The 80s–90s answer: write the meaning in by hand.

A hand-built definitional matrix

wordis-animal?is-small?is-alive?
cat111
kitten111
rock000
volcano000
aardvark101
abacus010
abandon…???

…449,993 more rows to hand-fill. Consistently. For all of English.

Key idea

You cannot hand-write the meaning of every word as a matrix of yes/no features.

020 old-school NLP & sentiment

Every definition right — meaning missed.

Keyword dictionaries got real trading work done on scraped tweets — until the sentence structure fought back.

I really like Apple, they’re high-performing
+1positive — correct
they’re not as high-performing as they used to be
+1 ?same keywords, opposite meaning
Key idea

A keyword dictionary can have every word’s definition right and still miss the meaning of the sentence.

030 word2vec & GloVe

Meaning is the company a word keeps.

Two competing recipes learned it automatically from all the text there is — from opposite ends of the same spectrum.

word2vec — predict the neighbors Mikolov et al., Google, 2013

…the catsatonthemat while…
slide a small window along the text train a shallow net to predict a word’s neighbors the weights are the embeddings
predictivelocalno explicit matrix

GloVe — factorize the counts Pennington, Socher & Manning, Stanford, 2014

whole-corpus co-occurrence counts

two skinny matrices of word vectors

count-basedglobalweighted least-squares

Two roads to nearly the same place — skip-gram was later shown to be an implicit factorization of the same co-occurrence statistics.Levy & Goldberg, 2014

The early research questions — how big a window? strip “a” and “the”? collapse want / wanting / wanted to one stem? — come back later, as tokens.

Key idea

A word’s meaning is captured by the company it keeps — the words it co-occurs with.

040 what embeddings bought us

Meaning becomes geometry.

Every word is now ~300 numbers — related words cluster, and you can do arithmetic on meaning itself.

Vector space (2-D shadow of ~300 dims)

man woman king queen same vector cat · kitten · tigerjaguar · panther

king − man + woman ≈ queen

subtract the vectors cosine similarity vs. the whole vocabulary
search leapt too:  hurricane ≈ tropical cyclone
Key idea

Meaning becomes geometry — related words cluster, and you can do math on meaning.

050 the polysemy limit

Four banks, one blurred vector.

A static embedding saw every context and averaged them all together — that ceiling is what the next architecture had to break.

“I was banking on getting to the bank before it closed, so I drove along the riverbank and took the turn so hard the car banked left.”

reliance money river tilt

one grey averaged embedding — “bank”

Key idea

A single embedding per word can’t tell the riverbank from the bank where you withdraw money.

060 transformers → next-word prediction

“Attention is all you need” — 2017

Words look at each other, so a word's vector finally depends on its sentence — and the whole enterprise becomes predicting the next word.

Mask a word; predict it from everything else

The cat sat on the ___
mat0.62
rug0.19
floor0.11
moon0.01
predict → unmask → predict again — an autocomplete that can talk
Static embeddingsone vector per wordword2vec / GloVe · 2013–14
ELMo — contextual, firsta word’s vector depends on its sentence — built on a bidirectional LSTM, no transformerPeters et al. · early 2018
BERT — contextual, dominantsame idea on a transformer encoderDevlin et al. · late 2018
Said honestly: contextual embeddings fixed the bank problem — and the transformer is what made them cheap and scalable, not what invented them.
Key idea

Attention lets words look at each other; masked / next-word prediction turns that into a text generator.

070 the scaling bet

The bet: more data, nothing else.

OpenAI wagered that the same architecture, fed more text, would just keep getting better.

GPT-1“terrible”
+ more data
GPT-2“way better”
+ more data
GPT-3“actually pretty good”

Hold onto this intuition on purpose — it breaks, audibly, in beat 210.

Key idea

Pour enough text into next-word prediction and it becomes shockingly capable.

080 post-training into a chatbot

Why does it answer instead of continue?

A raw next-word predictor just continues your text. A second training layer retargets it at answering you.

Base modelnext-word predictor — continues whatever you type

+

Post-training — the InstructGPT recipetrained to answer the question, not continue the text
1 SFT — ~13k hand-written ideal answers 2 reward model — ~33k human rankings 3 RLHF

=

An assistant that answers youOuyang et al., OpenAI 2022 — the direct ancestor of GPT-3.5 / ChatGPT

“~10,000 Q&A pairs” is the right order of magnitude for step 1 — but it wasn’t just Q&A pairs; it was a small pile of human answers plus reinforcement learning from human rankings. And it’s a knob the company controls — remember that at style control.

Key idea

Post-training turns “continue the text” into “answer the question.”

090 statistical truth, not knowledge

There are no facts in here.

Nothing in training makes the model correct — it speaks English the way English was spoken, and most of that text happened to be true.

“Humans use only ___ of their brains”

10%0.64false
a fraction0.22
all0.10true
half0.04

If the most-repeated version in the corpus is wrong, the wrong thing is the most likely token.

the naked LLM — Carson’s name for the bare model; the central character from here on

It isn’t confidently wrong — because it was never confidently right.

Key idea

A naked LLM has no facts; it’s a statistical next-word predictor that’s truthful only because most of its training text was.

Actionable

Distrust unsourced factual claims from a bare model — and drop the word “hallucination.”

100 temperature & creativity

One distribution, reshaped.

Temperature doesn't add a second distribution on top — it stretches or squashes the one the model already produced, then you sample.

“my dad went to the store to buy ___” softmax(logits / T)

milk68%
beer15%
cigarettes12%
flowers4%
a longsword0.5%
a tiny volcano0.2%
low — sharpen, deterministichigh — flatten, wild

For this room: it’s literally the temperature in a Boltzmann distribution — low T freezes into the ground state, high T populates the excited states.

Creativity is not remixing

“The ___ lapped the milk from the bowl.” Even if jaguar never once appeared there in the whole corpus, the model can still land on it — jaguar’s vector sits right next to cat’s. Structured novelty, not random words.

Key idea

Output varies because you sample from a probability distribution that temperature reshapes before sampling.

Actionable

Raise temperature for novelty; lower it to pull the single most-likely, near-deterministic answer.

110 — the hinge

The naked model — where ChatGPT started

Launch-day ChatGPT was a next-word predictor with post-training bolted on. Remember how that felt:

Amazing

  • perfect, coherent English
  • writes you a poem on demand
  • anything you wanted, fluently

Frustrating

  • states things that are just not true
  • falls apart on complex instructions
#1 it says untrue things
#2 it drops complex instructions

Those two frustrations are the to-do list for the entire rest of this talk.

Key idea

The naked model is fluent and coherent but has no facts and struggles with complicated, multi-part instructions.

Act II

Working with basic LLMs

Practical technique for the two frustrations. The through-line: context is everything — nearly every fix is “put the right tokens in the window.”

Tokens → the window → grounding → tools → model literacy → chain of thought

120 tokens

Models don’t read words.

They read tokens — learned sub-word chunks, the same instinct as stemming from beat 030. This is the unit everything else is priced in.

geology geo logy
≈ characters ÷ 4 = tokens  OpenAI’s own rule of thumb learned per model — byte-pair encoding, ~100–200k vocabulary

Exact splits vary by tokenizer — “something like geo + logy,” not a guaranteed split.

Key idea

A token is a learned, semantically meaningful chunk of text — not necessarily a whole word.

Actionable

Estimate tokens as characters ÷ ~4; expect the count to differ per model.

130 the conversation illusion

The conversation is an illusion.

The single most important reframe of Act II — watch what actually happens as you chat.

A “Could the lensing excess be halo substructure?”
B “Substructure could produce it if…”
C “Or is it just survey selection?”
D “Selection alone could account for…”
100,000 tokens of the old framing
50 tokens: your new idea
a fresh model— has never seen a single word before
→ generates B → generates D → generates E → swamped by the old idea
You say A. The model answers B. So far, exactly what it looks like.
You say C. But what actually goes in is A, B, C — the whole transcript, stacked together.
Every turn, everything you have ever said is replayed from the top to produce the next reply.
And it’s replayed into a model that has never seen a single word before. There is no memory in the human sense — the model is stateless.(Token caching exists; ignore it — stateless is the useful mental model.)
An hour in, this is why the model won’t let go of your old framing: a next-word predictor weighing 100,000 tokens of the old idea against 50 of the new one.
Key idea

A → AB → ABC… the whole transcript is re-fed every turn to a model that has never seen a word before.

Actionable

To unstick a model, don’t argue at the end of a long thread — reset or prune the history.

140 context window & context rot

A million tokens — not a million good ones.

The window has a cap, and performance is not uniform across it. This is the master lever of the whole act.

2022: ~8k tokenstoday: 1M+

Lost in the middle

positional effect — Liu et al., 2023 recall of the buried fact worst in the middle start position of the fact end

Context rot

all 18 frontier models degraded — Chroma Research, 2025 advertised limit performance wobbling long before the cap 1k total input length 1M
Is the cap a hard wall? Not mathematically — it’s trained sequence length + O(n²) attention cost + money. Providers cap it where quality and compute stop being worth it. Embedding models are the opposite: genuinely hard-capped (classic BERT: 512 tokens).
Key idea

A bigger context window is not uniformly good context — recall sags in the middle and quality degrades as it fills: context rot.

Actionable

Keep the window lean and relevant; don’t dump everything in.

150 style control & few-shot

Style lives in the weights and in the window.

You can spot "LLM voice" instantly — but the model isn't stuck with it, and the overlooked lever is yours.

SOURCE 1Pretraining datathe Q&A-shaped text it happened to see
SOURCE 2Post-trainingthe company’s “be concise / be verbose” layer — their knob, not yours
SOURCE 3 — the overlooked oneIn-context examplesit’s still a next-word predictor: whatever voice fills the window, it continues
a rough draft in your voice, not Claude-speak

The Shakespeare gambit: you have a million tokens — spend 300,000 of them on the actual works of Shakespeare and it gets very, very good at Shakespeare.

for weaker / local models, decompose:
step 1emit a style-guide template
step 2fill it from your sample
step 3write to the filled guide
The term, precisely: few-shot prompting, a.k.a. in-context learning — from the GPT-3 paper, literally titled “Language Models are Few-Shot Learners” (Brown et al., 2020). No weights change; it all happens in the forward pass.
Key idea

Style lives both in the weights and in the window — and you can override the weights by putting examples in the window.

Actionable

Paste 3+ samples of the target voice. For weak models, decompose: template → fill → write.

160 — grounding facts in the window

Context is everything.

Don't ask the weights for facts. Find the true fact and put it in the window.

Ask the weights

your questionnaked LLMhope & pray

The paper is one of tens of thousands in the training data — drowned out. Maybe the true fact is the most likely token. Maybe.

Paste the source

the paper itself+your questiongrounded answer

Download the paper, paste it in, ask about that. Infinitely more likely to be right — the fact is sitting in the window.

#1 — discharged it says untrue things → supply the truth yourself
Key idea

Supply the source instead of hoping the weights memorized it. The context you build is what you live or die on.

Actionable

Paste the paper / the data and ask about that, rather than asking the model from memory.

170 tool calling & the orchestrator

naked LLM + tool + orchestrator

Grounding by hand is manual. Now automate it — this is the architecture behind every assistant you actually use.

Ask a naked model “what is 14.7 ÷ 16.9?” It has almost certainly never seen that exact string — and knowing what words mean is not the same as ever having conceptualized arithmetic. You get a plausible, wrong number.
So don’t feed the question straight in. Something sits in the middle and hijacks it. Carson’s name for that middle layer: the orchestrator.
The orchestrator extracts the math part and hands it to something that is actually good at math: a calculator.
The calculator returns 0.8698… — a real, computed fact. No probability distribution involved.
The original question plus the calculator’s answer go into the context window; the LLM does the one thing it’s actually good at — phrasing the reply.
Three characters, worth naming: the naked LLM, the tool, the orchestrator. Every modern assistant is this diagram with more tools.
YOU what is 14.7 ÷ 16.9 ? fed straight in… “≈ 0.92” plausible — and wrong naked LLM next-word predictor orchestrator hijacks the request calculator an actual tool extract: 14.7 ÷ 16.9 0.8698… question + 0.8698… “14.7 ÷ 16.9 ≈ 0.8698” THE NAKED LLM THE ORCHESTRATOR THE TOOL

Three flavors of orchestrator

The same LLM, post-trainedretrained to select tools instead of answering
A tiny specialist LLMsmall, fast, does nothing but route
An ordinary model, promptedno special training — you just ask it to orchestrate

Windsurf ran its own in-house orchestration model for coding — until the big labs got so good at it that the in-house model couldn’t keep up.

Key idea

naked LLM + tool + orchestrator — the orchestrator hijacks the request, calls the tool, and puts the result into the context window.

Actionable

Think in terms of routing work to tools, not doing everything inside the chat window.

180 search & RAG

Give the orchestrator a search bar.

Search is tool calling and grounding fused — it fetches the real page and builds a better context window automatically.

question“what tuners does my bass ship with?”
orchestrator“this needs a real source”
search toolmanufactures queries, runs them
the real pagethe manufacturer’s spec sheet
context windowquestion + page summary
grounded answera true fact about the world
RAG — retrieval-augmented generation. Know the word. the double power: better tools and a better window

Forward pointer: when we get to serious work on scientific data, this is exactly what you’ll build locally — your own RAG over your own documents.

Key idea

Retrieval augments generation — pull the real source into the window at question time.

Actionable

Route questions that need a live or authoritative source through search / retrieval; later, build your own RAG.

190 why code beats prose

Ask for the program, not the answer.

Code is the highest-leverage tool there is — and a big part of your job is recognizing when to reach for it.

In its head

“How many R’s in strawberry?”

“2”  ✗

It doesn’t see letters — it sees tokens. Even spelling it out and counting, it would still botch it: it doesn’t know things.

Through code

“Write a program that counts letters, then use it on strawberry.”

>>> "strawberry".count("r")
3

3  ✓

Still using the LLM. Still not doing the work yourself. Infinitely better answer.

~450,000English words — vast, ambiguous
~1,000core Python constructs — tiny, constrained, and paired with what-it-does in the training data
Key idea

Code is constrained and functional, so the model is both better at it and more capable through it.

Actionable

For anything code is good at — counting, math, parsing — ask the model to write and run the program, not to do it from memory.

200 model-shopping literacy

How to eyeball a model.

The specific models die in six months. The rubric — size, memory, quantization, benchmarks — survives.

A 70B model, by precision memory = parameters × bytes per parameter

FP32 ≈ 280 GB FP16 / BF16 ≈ 140 GB ← native — honest “uncompressed” INT8 ≈ 70 GB 4-bit ≈ 40–48 GB — and it still keeps ~92–95% of quality + ~10–15 GB of KV-cache & activations at inference

Where the memory sits matters

GPU memorycompute lives here
fat pipe
modelfits? fast.
system RAMspillover
bus-speed throttle
modelspills? crawls.

Quantization = lossy compression you all know PCA — same idea

Semantic information isn’t linear in precision, so you can throw away bits and lose far less quality than size. Degradation is non-uniform — read the model card’s published numbers.

FP32FP16 / BF16Q8_0Q5_K_MQ4_K_M — the sweet spot
Rule of thumb, not law: a well-quantized bigger model usually beats a smaller unquantized one at the same memory footprint — a 70B at 4-bit (~40 GB) generally beats a 13B at FP16 (~26 GB). It holds until quantization gets aggressive enough (2–3 bit) to break the model.
Key idea

Parameters × precision = memory; quantization trades precision for size with sub-linear quality loss.

Actionable

When picking a local model, check size and quantization level, and compare published accuracy — a quantized 36B can beat a heavily-quantized 120B.

210 the scaling era ends

The free lunch ends.

Callback to beat 070, inverted: the more-data-forever bet stopped paying — and the field changed levers.

Capability per generation (qualitative)

the dream largest pretrain ever — OpenAI: not a “frontier model” capability GPT-1 2018 GPT-2 2019 GPT-3 2020 GPT-4 2023 GPT-4.5 2025

“Pre-training as we know it will end… data is the fossil fuel of AI. We only have one internet.”

Ilya Sutskever — NeurIPS 2024
Curatefilter the junk out of what’s left
Synthesizegenerate training data on subjects that actually help
Pay humanscreate new data that never existed
the pollution worry: model collapse when models train on model output  Shumailov et al., Nature 2024 mixture of experts — the words exist; explaining them is cut for time
Key idea

More-data-forever broke; gains now come from better data, not just more of it.

Actionable

Don’t assume each new model is a giant leap from scale alone; weigh the data and technique, not just the size.

220 chain of thought & the cost of thinking

The cost of thinking.

With scale-alone exhausted, this is the current frontier — and the finale ties the whole act together.

“On the street next to my house there are five blue houses and a red one. Jill lives in the yellow house, Bob lives in the green house — which house does Sam live in?”
thinking — these are real generated tokens streaming out

Five blue houses + one red house = six houses on the street…

Jill is in a yellow house — but no yellow house exists on this street. So Jill doesn’t live here.

Same for Bob and the green house. Neither constraint touches this street at all…

So Sam is the one who lives on the street — which house makes him distinct?

Sam lives in the red house.

The mechanism, precisely: chain of thought is not chopping the input into chunks and re-feeding them. The model generates intermediate reasoning tokens — working out loud — before the answer, in one continuous left-to-right generation. Each reasoning step is itself next-word prediction — and that’s why it reaches answers a single pass can’t.Wei et al. 2022 (prompting) → reasoning models RL-trained to think before answering

The knob you get

low
high

High thinking: better results on complex, interdependent instructions — more tokens, more money, more latency. The real payoff isn’t word puzzles; it’s instructions the model can decompose and reconsider.

you pay tokens in + tokens out thinking tokens are billed as output — full price 5–10× more tokens on hard problems

The graph to read for future models illustrative shape

task accuracy diminishing — but real — returns reasoning tokens spent →
#2 — discharged complex instructions → a chain the model can actually attend to
Key idea

Chain of thought = next-word prediction over generated reasoning steps, reaching answers a single pass can’t; you pay in tokens IN and tokens OUT.

Actionable

Turn thinking up for complex, interdependent instructions and down for simple ones; judge models on token-spend vs. performance, not raw size.

where this leaves you

Every beat left a mark.

These bubbles have been accumulating the whole way — at the end of the full course they consolidate into a single fact sheet you take home.

key ideaactionable concept
010Meaning can’t be hand-written as yes/no features.
020Right definitions can still miss the sentence.
030A word’s meaning is the company it keeps.
040Meaning becomes geometry — you can do math on it.
050One vector per word can’t handle polysemy.
060Attention + next-word prediction = a text generator.
070Scale alone made prediction shockingly capable.
080Post-training turns “continue” into “answer.”
090A naked LLM has no facts — truth is a corpus byproduct.
090Distrust unsourced claims; drop “hallucination.”
100Temperature reshapes one distribution before sampling.
100Raise T for novelty; lower it for determinism.
110Fluent and coherent — but no facts, and drops complex instructions.
120Models read learned sub-word tokens, not words.
120Estimate tokens as characters ÷ ~4.
130Every turn replays the whole transcript into a stateless model.
130Unstick by pruning or resetting the history.
140A bigger window is not uniformly good context.
140Keep the window lean and relevant.
150Style lives in the weights and the window.
150Paste 3+ samples of the target voice.
160Context is everything.
160Paste the paper; ask about that.
170naked LLM + tool + orchestrator = every modern assistant.
170Route work to tools.
180RAG pulls the real source into the window at question time.
180Route factual questions through retrieval.
190Code is constrained; the model is more capable there.
190Ask for the program, not the answer.
200Parameters × precision = memory; quantization is lossy compression.
200Compare size, quant level, and published benchmarks.
210Gains now come from better data, not more of it.
210Judge new models by data and technique, not size.
220Reasoning is next-word prediction over generated sub-steps.
220Spend thinking only on complex tasks; read tokens-vs-performance.

Act III — the agentic half (agents, skills, project context, documentation) — is being dictated now. The course closes with the consolidated fact sheet and a pointer to the working-with-llms repo.