How machines
learned to talk
Zero scary math in the main line — one school formula, tops. (Press D on any slide for an optional deeper layer, with the maths, when you want it.) A live demo for every big idea, and your first AI API call before you leave.
I sat in these seats — TCE CSE, class of 2009.
Karthikeyan NG. The seventeen years since: heading engineering at a fintech in Dubai, two startups founded, two books on machine learning, a TEDx stage, eighteen hackathon wins.
Not listed: the hundreds of things I built that failed — which taught me more than everything above.
Full story on the course site. That's all the bio you get — we have twelve hours, and you're here to build.
12 hours. 6 things you'll build.
S1 · First AI script
Your own API key, your own code calling a frontier model. Today.
S2 · Eval harness
A tester that measures whether AI answers are right — like an engineer, not a fan.
S3 · Vision app
Upload a photo, ask questions about it. AI that reads documents and images.
S4 · Chat with your notes
An AI that answers from your study material — the #1 real-world pattern (RAG).
S5 · Tool-using assistant
AI that calls a calculator, searches, reads files — and knows when not to be an agent.
S6 · Capstone demo
You attack each other's apps, patch the holes, and demo a real product — and the shape of a final-year project.
Everything runs on free tiers, in the browser. No installs, no credit cards, no excuses.
Two kinds of AI: judges vs creators
The line that matters
Discriminative AI draws boundaries: spam or not, cat or dog, fraud or genuine. Input → label. It ran the world 2012–2022.
Generative AI produces new content: essays, images, code, answers. Input → new stuff. It's why you're in this room.
Same underlying math family — the difference is what the model is trained to output.
AI, ML, GenAI, LLM — who lives inside whom
—
—
App ≠ model
ChatGPT / Gemini app = the product you open. GPT-5.6 / Gemini 3.5 = the model inside it (names as of mid-2026 — they change monthly). Like WhatsApp vs the phone network — today in lab you skip the app and talk to the network directly.
ChatGPT is autocomplete at scale.
That one idea goes surprisingly far.
Every large language model repeatedly does this core operation: given context, assign scores to possible next tokens, choose one, append it, and continue. A token is a chunk of text — not necessarily a word; the tokens slide shows why. Sampling, attention, and tool or retrieval layers determine how useful the loop becomes.
Essays, poems, code, and exam answers emerge from that loop plus learned representations, attention, training, and tool or retrieval layers around the model. The metaphor is useful — but it is not a claim that the system is simple or always correct.
Sounds too simple to write poetry? Good. Let's catch the smallest version in the act →
Play the model: guess the next word
Shout your guess before the reveal. Your brain has been doing next-token prediction since you learned Tamil.
Those odds aren’t magic — you just count words.
The exact same three steps as Claude
1read the last word
2look up one row in the table
3sample the next word
1read the whole conversation
2one forward pass, billions of knobs
3sample the next token
Step 3 is identical — sampling is sampling. What changes is step 2, and training: counting hits a wall (vocabularyN rows), so an LLM learns a function instead of memorising a table.
Same idea, more machine: Markov published it in 1906, it ran your phone's autocomplete by 2010, transformers arrived in 2017.
Watch the network think
Honest scale: this toy has 21 neurons — frontier models have hundreds of billions of knobs and attention between every pair of tokens. But the choreography is exactly this: numbers in, numbers between, probabilities out, one token appended. Repeat.
Why the same question gives different answers
The model rolls dice
It doesn't always pick the #1 token — it samples from the distribution. Temperature reshapes those dice.
Low T → sharpens the peaks. Deterministic, safe, boring. Use for facts, code, extraction.
High T → flattens the field. Creative, surprising, riskier. Use for stories, brainstorms, names.
This is why your friend's ChatGPT answer ≠ yours. Nobody is lying. It's dice.
The model's last layer does not emit probabilities. It emits one raw score per token in the vocabulary — a logit. Logits are unbounded: +8.2, −1.4, 0.03. To turn a list of scores into a list of probabilities that sums to 1, you run softmax: exponentiate everything, then divide by the total.
p(token i) = exp(zi / T) / Σj exp(zj / T) z = logits · T = temperatureNow look where T sits: it divides the logits before the exponential. That one placement explains the whole slider. T < 1 stretches the gaps between scores apart, so exp() exaggerates the leader — the peak sharpens. T > 1 squeezes the gaps together, so the field flattens. T → 0 makes the top logit infinitely dominant, which is why temperature 0 is just argmax: always take the highest-scoring token, same answer every time. Temperature isn't a mysterious creativity dial. It is one division.
top-k
Before sampling, throw away everything except the k highest-scoring tokens, then renormalise. Caps how weird the choice can get, no matter what T says.
top-p (nucleus)
Keep the smallest set of tokens whose probabilities add up to p (say 0.9). Adapts: a confident step keeps 2 candidates, an open-ended one keeps 50.
Why you'll meet them
They're parameters on the same API call you make in the lab. In practice: set temperature for facts vs. flavour, leave top-p near the default, and change one at a time.
Sampling is also why temperature 0 is not fully deterministic in production: floating-point addition on GPUs isn't associative, so batching can reorder sums and flip a near-tie. Close to reproducible, never guaranteed.
Wait — is it just searching a giant database?
No. And here's the proof: ask for something that has never been written by anyone, anywhere.
Nothing is stored, nothing is looked up
No sentences are saved as sentences — no articles, no answer bank. It computes every reply fresh, token by token, from learned patterns.
Fine print: text the internet repeats a million times can get burned into the knobs — but ask for anything new and it must compute.
Which raises the real question
If not lookup… where do those probabilities come from? Next slide: you'll build the answer with your own hands.
What's inside a model? Just knobs.
You remember y = wx + b
Those w and b are parameters — adjustable knobs. You're tuning them by eye to reduce the error. Training is exactly this, automated: guess → measure error → nudge knobs → repeat.
A “model” is nothing but a file full of learned knob values. You: 2 knobs, one line. Gemini: knobs in the hundreds of billions to a trillion — the labs won't say exactly — tuned on most of the internet.
Those probabilities in the guessing game? They come out of these knobs.
You just reduced an error by eye. A lab training for four months cannot do that — so what number do they actually watch? One: the loss. At every step the model predicts a distribution over the next token, and the true next token is known. Loss is how much probability the model put on the right answer, scored so that being confidently wrong hurts most:
loss = −log p(the token that actually came next) averaged over billions of guessesPut 0.9 on the correct token and you lose 0.11. Put 0.1 on it and you lose 2.3. Put 0.001 on it and you lose 6.9. Confidently wrong is punished roughly twenty times harder than merely unsure — which is exactly the behaviour you want to train out.
Perplexity is that same number made human: exp(loss). Read it as "how many equally likely options is the model effectively choosing between?" Perplexity 1 means it always knows. Perplexity 50 means it's flailing among fifty. A modern model on ordinary English sits in the low single digits. That single falling curve, watched for months across thousands of GPUs, is the entire feedback signal of pretraining.
Worth knowing: loss keeps improving smoothly long after the model stops feeling smarter — and it says nothing about whether answers are true, safe, or useful. That gap is why Session 2 exists. Pretraining measures loss; engineers measure evals.
Training vs using: the cookbook rule
Training — writing the cookbook
Happens once, in the lab. Read trillions of tokens, nudge the knobs, for months, at hundreds of crores of cost. Ends with a frozen file.
Inference — cooking from it
Every time you chat. Your prompt flows through the frozen knobs, tokens come out in seconds. The book doesn't change while cooking.
Models don't read words. They read tokens.
Tokens are learned letter-chunks (~¾ of an English word each), and the meter runs in tokens, not words. Press the four language buttons: the same sentence needs far more chips once you leave English — and English is the only one that gets cheap multi-letter merges. That is not a Tamil problem. Tokenizer vocabularies are learned from English-heavy text, so Hindi, Arabic, Thai, Swahili and most of the world pay the same tax three times over: on price, on speed, and on how much of their own language fits in the context window. The real gap depends on the tokenizer — you'll measure Gemini's with count_tokens in the lab.
You saw this machine on the pre-class page — here it is in one loop
Every word of every ChatGPT answer went through this exact loop. A 500-word answer ≈ 650 loops. The two middle stages — embeddings and attention — are the ones you drove with a real model on the pre-class page; the panel below is the two-paragraph version.
Embeddings — meaning as coordinates. Before anything else happens, each token is turned into a long list of numbers: thousands of dimensions, of which a picture can show two. Tokens used in similar contexts land near each other — idli sits beside dosa, and both are a continent away from GPU. Because meaning is now geometry, it supports arithmetic: the famous party trick is king − man + woman ≈ queen. These are learned rows of a table, not hand-written; direction carries the meaning, and the same idea becomes a search engine over your own notes in Session 4.
Attention — every token looks at every other. Coordinates alone cannot tell you what “it” refers to in “the trophy didn’t fit in the suitcase because it was too big”. So each token weighs every other token in the context and blends in what matters: “it” leans on trophy; change big to small and the same mechanism re-weights instantly toward suitcase. That mechanism is the T in GPT — the Transformer, from the 2017 paper “Attention Is All You Need”. Two honest footnotes: attention is order-blind (a set has no order), so position is added into each embedding first — positional encoding, today usually RoPE; and “every token looks at every other” costs n² — double the context, quadruple the work, which is why a 1M-token window was a headline and why Session 4 retrieves three paragraphs instead of pasting the textbook.
Want the live versions? The pre-class page how-llms-work.html has the embedding map and the attention heat-map running on a real model (chapters on embeddings and attention); Session 4 re-teaches embeddings with the Gemini embedding API and real cosine numbers.
If autocomplete can pass your exam,
your exam was never testing understanding.
You just watched the core loop, not the whole product: next-token prediction plus learned representations, attention, training, and sometimes tools. If a model can top a question paper, ask whether the paper measured recall and pattern rather than transferable understanding.
Disagree? Good. Bring it to the break — strongest counter-argument gets named on the closing slide.
The loop is old. The scale is new.
Quantity became quality. Keep scaling the same next-token loop and abilities nobody explicitly programmed start appearing — emergence; researchers still argue how sudden it really is. (And since 2024, labs also train models to think step-by-step before answering — scale isn't the whole story.)
How big did it get? ChatGPT reached roughly a billion monthly users by mid-2026 — the fastest consumer app in history to that mark. (Figure as reported by the company; treat it as an order of magnitude, not a data point.)
The demo above has one slider, parameters. Reality has three, and they have to move together: parameters (how many knobs), data (how many tokens you train on), and compute (how many GPU-hours you can pay for). Around 2020 researchers found these trade off in a smooth, boringly predictable way — scaling laws. Loss falls as a power law in each one. That predictability is the real reason billions got invested: you could forecast the capability of a model that did not exist yet.
The correction that changed the industry came in 2022. Everyone had been building models that were too big and too under-fed. The Chinchilla result showed that for a fixed compute budget you should scale parameters and training tokens together — roughly 20 training tokens per parameter. A smaller model trained on far more data beat a much larger one trained on less. Overnight, "make it bigger" stopped being the strategy.
Then: bigger
2018–2022. Parameter counts as the headline. Under-trained giants.
Now: better-fed and cheaper to serve
Compute-optimal sizing, far more data, heavy filtering and dedup of that data — and models built for the cost of answering, not just training.
Next: think longer
The data wall is real — high-quality human text is finite. So the newest axis isn't training at all, it's spending compute at answer time. That's slide 20 — reasoning models.
Keep the shape of the argument, not the constants. The exact ratio has been revised more than once and depends on how you count. What has held for six years: capability follows compute in a predictable curve, and the curve is smooth even when the abilities that pop out of it feel sudden. That's the honest version of "emergence."
A freshly trained model won’t answer you. It just keeps writing.
Straight out of pretraining you get a base model. Ask it a question and it does not reply — it carries on writing, because continuing text is the only game it has ever played. The informal name for a model in that raw state is feral: all of the internet’s knowledge, none of its manners. Try it:
A brilliant parrot of the whole internet — not an assistant. So how did it learn to answer instead of continue? →
Finishing school, in three steps
Pretraining
Read everything. Trillions of tokens, one game: predict the next one. Produces raw intelligence with zero manners.
Months · insanely expensive
Instruction tuning
Show it good behaviour. Many examples of “question → helpful answer” until it learns the assistant format.
The parrot learns to reply, not continue
RLHF
Teach it taste. Humans rank answers; the model is tuned toward what people prefer — helpful, harmless, honest.
Reinforcement Learning from Human Feedback
ChatGPT's 2022 breakthrough wasn't a smarter brain — it was better finishing school on top of the same loop.
Reasoning models: think longer, not just train bigger
Since late 2024 there's a third way to buy intelligence. Dial 1 was scale — a bigger brain. Dial 2 was finishing school — better manners. Dial 3: let the model spend tokens thinking before it answers. A scratchpad you usually don't see, then the reply.
What thinking buys
Hard math, multi-step logic, tricky debugging. On the scratchpad it tries a path, spots its own mistake, and backs up — it catches its errors before you ever see them.
Still next-token prediction — just aimed at itself first
What thinking costs
10–50× more tokens — real money, real seconds. Rule of thumb: easy question → fast model. Genuinely hard reasoning → thinking model.
Never pay thinking prices for “what's the capital of Tamil Nadu?”
Same autocomplete, one new habit: it learned to use scratch paper. (Frontier flash models expose this “thinking” mode — more tokens before the answer, so more accuracy and more cost.)
Why ChatGPT ≠ Gemini ≠ Claude
Three kitchens, same recipe book, different biryani: different training data, different finishing school, different house rules (system prompts) and tools bolted on. The map as of mid-2026:
| Lab | Flagship family (names as of mid-2026 — they change monthly) | Weights | Worth knowing |
|---|---|---|---|
| OpenAI | GPT-5.6 (Luna · Terra · Sol) | Closed | Started the ChatGPT era |
| Google DeepMind | Gemini 3.5 Flash · Pro | Closed | 1M-token windows · our free lab |
| Anthropic | Claude Fable 5 · Sonnet 5 · Opus 4.8 | Closed | Safety lab · coding + long docs |
| Meta | Llama | Open | Weights you can download |
| Open-weights wave | Gemma 4 · Qwen · DeepSeek | Open | Frontier-chasing open models |
“Open weights” = you download and run the model yourself — we do that with Ollama in Session 5. Note who is on that last row: the frontier is not one company or one country any more. Open-weight models out of China, France and the US now trade places at the top every few months, and because you can download them, the gap between “a lab has this” and “you have this” is a weekend. In today's lab you'll taste the kitchens: identical prompt, three models. Names change monthly; the mechanics don't.
Look at the naming across all three kitchens: Flash and Pro. Haiku and Opus. mini and full. Every lab sells the same two-tier menu, and the free tier you'll use today is always the small one. Three techniques make a small model punch far above its size — and they're the reason your lab is free.
Mixture of Experts (MoE)
Instead of one dense block of knobs, the model holds many "expert" sub-networks and a router that wakes only a couple per token. A model can have a trillion total parameters but activate perhaps 3% of them for any given token. Huge knowledge, small bill. This is why "parameter count" stopped predicting cost or speed.
Distillation
Train a giant, expensive teacher model, then train a small student to imitate its full output distribution — not just the right answer, but how the teacher spread its doubt. The student inherits much of the judgement at a fraction of the size. Essentially every "mini"/"Flash"/"Haiku" model is a distilled child of a bigger sibling.
Quantization
A knob stored as 16 bits can often be stored in 8 or 4 with little quality loss. Four-bit weights make a file a quarter the size, so it fits in less memory and moves faster. This is exactly why a capable model can run on a laptop in Session 5 — and where the quality does drop, it drops on the hard, rare cases first.
Now the practical consequence, which is the whole point of knowing this: "which model?" is not a question about intelligence, it's a routing decision. The mature production pattern is hybrid — the small fast model handles the routine 90% of traffic, and you escalate only the hard 10% to the expensive one. You'll make exactly that trade with real numbers in Session 6.
Also why benchmark tables mislead: a Flash-class model and a Pro-class model can score within a point or two of each other on a public benchmark while differing 10–20× in price and several-fold in latency. The gap shows up on your hard cases, which is a thing only your own eval set can tell you.
Famous failures — you explain them
Click a card only after the class has guessed the mechanism.
“How many r's in strawberry?” → “2”
Models kept getting this wrong for years. Using today's ideas — why?
Tokens. The model sees str·aw·berry as chunks, not letters. It literally cannot see the r's. Today's models finally pass — because labs drilled them on exactly this. The mechanism (tokens, not letters) hasn't changed.
847 × 923 = confidently wrong
A plain model, no calculator tool: it aces the explanation but flubs the arithmetic. Why?
Prediction ≠ calculation. It predicts digits that look plausible. Fix: hand it a calculator — tool use, Session 5.
Turn search off — clueless about yesterday's match
It knows last year in detail but not last night. Why?
Knowledge cutoff. Training ended months ago. Fix: give it search or your documents — RAG, Session 4.
Invents a convincing fake citation
Real journal, real-sounding authors, paper doesn't exist. Why?
Hallucination. It optimizes for “sounds likely,” not “is true.” Fix: evaluation + grounding — Session 2 is our lie detector.
None of these are bugs. They're direct consequences of next-token prediction — each with an engineering fix you'll build in this course.
The context window: its entire working memory
If it isn't in the window, it doesn't exist — the model's entire universe is one box measured in tokens. Try filling it:
The twist: it remembers nothing between turns. The app re-sends everything, every turn.
That’s the whole illusion of “chat memory” — the app quietly stuffs the entire conversation back into this window each time you hit send, which is why long chats get slow and forgetful.
And when your knowledge doesn’t fit? That’s Session 4: RAG — the pattern behind most real AI products.
Good objection — and the answer is the single most useful piece of plumbing to know. If the app really re-ran a 50,000-token conversation through the whole network on every turn, chat would be unusable. It doesn't, because of the KV cache.
Remember attention: each token computes a key and a value that later tokens look at. For text already in the context, those keys and values never change — token 4,001 does not alter what token 12 was. So the model computes them once and keeps them. Answering therefore splits into two very different phases:
Prefill — read the prompt
Chew through every input token at once, in parallel, and store all their keys/values. Heavy, but done once. This is your time to first token — the pause before anything appears.
Decode — write the answer
Each new token attends to the cached keys/values instead of recomputing them. One cheap step per token. This is your tokens per second — the steady stream you watch.
Two metrics, not one
"Latency" is really these two numbers. A long prompt hurts the first; a long answer hurts the second. They have different fixes, so engineers never average them.
Three real-world facts fall straight out of this, and you'll meet all three later in the course:
Long chats get slow and expensive because the cache grows. It costs GPU memory proportional to context length, and it's per-conversation — which is a large part of what you're paying for.
The cache dies when your request ends, so a fresh call re-reads everything from scratch. That's why providers sell context caching: pin a long unchanging prefix (your system prompt, a big document) on their side and pay roughly 10% to reuse it. Same idea, rented. It's a headline cost lever in Session 6.
Put the stable part of your prompt first. Prefix caching only works up to the first byte that differs, so a prompt built as [fixed instructions][fixed document][changing question] is dramatically cheaper than one that varies at the top. Prompt order is a cost decision, not just a style one.
So the honest version of the slide above is: it re-sends everything, but it doesn't re-read everything. The illusion of memory is real; the re-computation is not.
Eight words you own now
Active recall: say the definition out loud before clicking.
Token
···
The chunk models actually read. You pay per token; Tamil costs more than English.
Embedding
···
Token → coordinates in meaning-space. Similar meaning = nearby points.
Attention
···
Every word weighs every other word to resolve meaning — the Transformer's engine.
Prediction
···
One task only: score every possible next token. The whole loop, repeated.
Sampling
···
Pick from the scores with temperature dice — why answers differ run to run.
Tuning
···
Pretraining → instruction tuning → RLHF: parrot goes to finishing school.
Parameter
···
One learned knob. A model = a file of billions of them. No sentences stored, no lookup.
Inference
···
Using the frozen model. It doesn't learn from your chat — and it has no memory between turns.
If you can explain these eight to your roommate tonight, Session 1 worked.
What actually happens when you call an API
Key = your identity
It says who's asking and whose quota to use. Treat it like a password.
429 = slow down
Typical free-tier limit ≈ 10 requests/min — check the live limits page. Our notebook auto-retries politely.
Latency is honest
1–3 s = the GPUs literally running one loop per token of your answer.
Your lab kit, and the rhythm
Lab handout
Parts A → E, top to bottom. Exact steps, checkpoints, and stretch goals — you never have to wonder “what now?”
Colab notebook
Cells pre-written, you run and edit. File → Save a copy in Drive first, every time.
Cheatsheet
One page per session — key terms + the code that matters. Keep it open in a tab; it's your revision material too.
Everything lives at
intrepidkarthi.com/genai
Bookmark it — every deck, handout, notebook and cheatsheet, all six sessions.
10 min
show me
don't skip!
The rhythm — every lab, all weekend
1. Pairs — both partners have a key · one drives per part · swap at each checkpoint.
2. Hit a ✓ checkpoint → wave me over, show it.
3. Stuck > 5 minutes → ask the pair beside you first, then me.
4. Finished early → stretch goals. There is always more.
Checkpoints are how I know nobody's silently left behind — they're for you, not for marks. Using an AI assistant to write your lab code? Allowed — encouraged. One rule: your eval set judges its code too.
Lab 3 needs two photos on your laptop — put a receipt + a page of your handwriting in Drive now, while you have a minute.
Lab 1: your first AI API call
gemini-flash-lite-latest is our free workhorse — the alias keeps you on the newest Flash Lite automatically — today that's Gemini 3.5 Flash Lite. Lite runs with minimal thinking by default, so your free quota lasts the whole lab. The free model in your lab today still beats last year's flagship.
Rules of the lab
Work in pairs — both have a key, one drives per part, swap at each checkpoint. Stuck > 5 min? Ask the pair beside you first, then me. Finished early? Stretch goals on the handout.
Three things before the next session
Your 10 questions — written in Part E
You wrote these in Part E: 10 questions on a subject you know cold — DSA, cricket stats, Ilaiyaraaja discography — each with a one-word or one-number answer (a name, a year, a score — not a sentence) saved in a text file. That file is live ammunition for the lie-detector lab, next session. Missing it? Two minutes. Write it now.
Coming up: you catch it lying
In the next session's lab you'll interrogate the model on your expert topic until it confidently states something false — then measure how often, with numbers. Best catch gets bragging rights.
Next session — after a short stretch
Talking to AI, and Catching Its Lies — prompt engineering that actually works, and how engineers measure AI quality with numbers instead of vibes. Keep your laptops open and your API keys warm.
You've learned the trick.
Next: you learn to drive it.
Stretch, refill water, and find me if anything from this session is still fuzzy:
Deck + lab + cheatsheet are in the course repo. Keys are secrets — never commit them.