Chapter 1 · Foundations

Generative AI & LLM Foundations

By the end of this chapter you will be able to read a sentence like "we run a 7B parameter model at temperature 0.2 with an 8K context window" and know exactly what every single word means — and why someone chose those numbers.

No prior AI knowledge assumed History included Retail examples 18 interview drills Reading time ~55 min

1.1 Why this chapter exists

Most AI tutorials start by throwing words at you: transformer, embedding, token, inference, temperature. You nod along, and three paragraphs later you realise you have not actually understood a single thing — you have just learned which words go next to which other words.

This chapter does the opposite. We introduce one idea at a time, and every new term gets defined before it is used. Nothing here assumes you have trained a model, studied statistics, or read a research paper.

There is one running example throughout the whole course: an online retail store. Not because retail is special, but because it is concrete. Every abstract idea ("what is a token?") lands better when it is attached to something real ("how many tokens does a product description cost me, and what is the bill?").

[i] How to read this chapter

Coloured boxes have consistent meanings across the entire course, so you can skim for what you need:

The colour language used in every chapter
BoxMeans
DefinitionA precise definition of a term. Blue.
HistoryWhen it appeared and what came before. Amber.
RetailHow it shows up in a real store. Teal.
Why betterAdvantages over the previous approach. Green.
GotchaA trap that catches people in production. Red.
InterviewHow this gets asked, and a model answer. Orange.

Plain-English restatements appear in light blue strips after any dense passage. If you only read those, you will still come away with the shape of the idea.

1.2 Step zero: what a "model" actually is

Before generative AI, before neural networks, before anything — what is a model?

A model is a function that turns an input into an output, where the rules were learned from examples rather than written by a programmer.

That distinction is the whole game. Consider a store that wants to flag orders as fraudulent. The traditional way is to write the rules by hand:

Hand-written rulesjavascript
function isFraud(order) {
  if (order.amount > 5000) return true;
  if (order.billingCountry !== order.shippingCountry) return true;
  if (order.accountAgeDays < 1) return true;
  return false;
}

A human decided the number 5000. A human decided that a country mismatch matters. Every rule is traceable to a person's judgement. This works, and for many problems it is still the right answer — it is fast, free, and completely explainable.

It also breaks down fast. Real fraud depends on hundreds of interacting signals with no clean thresholds. A $50 order can be fraud; a $9,000 order can be a loyal customer buying a sofa. Nobody can hand-write that.

So instead you show a program 100,000 past orders, each labelled "fraud" or "fine", and let it discover the pattern itself. The output of that process — the learned rules, frozen and reusable — is the model.

Hand-written rules versus a learned model Top row: a programmer writes rules directly into a program which produces answers. Bottom row: labelled example data plus a training process produces a model, which then produces answers. TRADITIONAL: a human writes the rules Programmer thinks hard if (amount > 5000) explicit code Answer Explainable, but cannot scale MACHINE LEARNING: the rules are discovered from data Labelled data 100,000 orders each: fraud / fine Training adjust numbers until predictions match THE MODEL a big pile of learned numbers Answer The model is the frozen result of training. Training happens once and is expensive; using the model happens billions of times and is cheap. Everything in this course is about that blue box: how it is built, what it can do, and how to run it in production.
Figure 1.1 — The essential difference. In traditional software a human encodes the logic. In machine learning the logic is discovered from labelled examples and stored as a model. Note that training and using are two separate activities — a distinction that becomes very important for cost.
In plain English: a model is a program whose rules were learned from examples instead of typed by a person. Training is how you make it. Using it is a separate, much cheaper thing.

1.3 Generative AI, defined

The fraud model above answers a closed question: fraud, or not? It picks from a fixed list of possible answers. That is discriminative AI — it discriminates between categories.

Now imagine asking instead: "write a product description for this waterproof hiking boot." There is no list to pick from. The answer is a sentence that has quite possibly never been written before. The model must produce new content, not select from options.

[def] Generative AI

Generative AI is any AI system that produces new content — text, images, audio, code, video — rather than choosing a label from a fixed set of options.

The technical distinction: a discriminative model learns the boundary between categories. A generative model learns the shape of the data itself, well enough to produce convincing new samples of it.

The difference is easiest to feel with a concrete pair:

Discriminative: picks

Question: "Is this review positive or negative?"

Possible answers: exactly 2.

Output: positive

Retail use: routing angry reviews to support, tagging products into categories, flagging fraud.

Generative: produces

Question: "Reply to this negative review."

Possible answers: effectively infinite.

Output: "I'm really sorry the boots arrived scuffed. I've arranged a replacement..."

Retail use: product copy, support replies, search summaries, chat assistants.

[retail] Where each one belongs in a real store

A common and expensive mistake is reaching for generative AI when a discriminative model would do. If you need to sort 20,000 products into 40 categories, a small classifier costs a fraction of a cent per item and gives a consistent answer every time. Asking a large language model to do it costs perhaps 200x more and may return a slightly different category name on Tuesday than it did on Monday.

Rule of thumb: if the set of valid answers fits in a dropdown menu, you probably do not need generative AI.

1.4 Untangling AI vs ML vs NLP vs GenAI

These four terms get used interchangeably in job ads and press releases, which is unhelpful, because they are not synonyms — they are nested categories that partially overlap.

Nested relationship of AI, machine learning, deep learning, generative AI and NLP Concentric rounded rectangles. Artificial Intelligence is the outermost, containing Machine Learning, which contains Deep Learning, which contains Generative AI. Natural Language Processing is drawn as an overlapping oval crossing several layers, because NLP is a problem area rather than a technique. ARTIFICIAL INTELLIGENCE Any machine doing something we'd call "intelligent". Includes hand-written rules. Term coined 1956. MACHINE LEARNING Rules learned from data, not written by hand. From ~1959. DEEP LEARNING ML using many-layered neural networks. Took off ~2012. GENERATIVE AI Deep learning that produces new content. Mainstream from ~2018 onward. LARGE LANGUAGE MODELS (LLMs) Generative AI specialised in text. GPT, Claude, Gemini, Llama. NLP Natural Language Processing A PROBLEM AREA, not a technique: "make computers handle language" Cuts across all the rings: 1950s grammar rules to today's LLMs.
Figure 1.2 — The nesting. Every LLM is generative AI; all generative AI is deep learning; all deep learning is machine learning; all machine learning is AI. NLP is the odd one out — it is a goal ("handle human language"), not a method, so it overlaps every ring. A 1960s hand-coded grammar parser was NLP without being machine learning at all.
Artificial Intelligence
The broadest term. Any machine performing a task we would call intelligent. A chess program using hand-written rules qualifies. Coined at the Dartmouth workshop in 1956.
Machine Learning
A subset of AI where behaviour is learned from data. Term popularised by Arthur Samuel in 1959. Includes simple methods like linear regression and decision trees.
Deep Learning
A subset of ML using neural networks with many layers. Existed in theory for decades but became practical around 2012 when GPUs made training affordable.
NLP
Natural Language Processing. The field concerned with making computers work with human language. Not a technique — you can do NLP with rules, with classical ML, or with LLMs.
Generative AI
Deep learning models that generate new content. The subset we care about most.
LLM
Large Language Model. Generative AI specialised for text. The subject of most of this course.

[!] The mistake that gets made in meetings

People say "let's use AI for this" when they mean "let's call an LLM API". Those are wildly different in cost and reliability. Sentiment analysis on a million reviews is an NLP task that a small classical model handles for a couple of dollars. Routing it to an LLM turns that into a four-figure bill and a slower pipeline. Being precise about which ring you are in is a cost decision, not pedantry.

1.5 A short history: how we got here

You cannot judge whether a technique is good without knowing what it replaced. This timeline is not trivia — each entry exists because the previous approach hit a wall, and knowing which wall tells you when the old approach is still perfectly fine.

  • 1950s-80s Rule-based language systems. Linguists hand-wrote grammar rules. ELIZA (1966) simulated a therapist using pattern matching alone. Wall hit: human language has endless exceptions. Every rule added broke two others.
  • 1990s Statistical NLP. Instead of rules, count things. If "New York" appears together far more often than chance would predict, treat it as a unit. This powered early machine translation. Wall hit: counting words ignores meaning. "Bank" by a river and "bank" with money were the same token.
  • 2003-2013 Neural language models and word embeddings. Represent each word as a list of numbers, positioned so similar words sit close together. Word2Vec (2013) made this famous. Wall hit: each word got exactly one vector regardless of context.
  • 2014-2016 RNNs, LSTMs and sequence-to-sequence. Networks that read text one word at a time, carrying a memory forward. Powered Google Translate from 2016. Wall hit: strictly sequential, so training could not be parallelised, and memory of early words faded across long inputs.
  • 2017 The Transformer. The paper Attention Is All You Need (Vaswani et al., Google) dropped recurrence entirely in favour of attention. Training could now parallelise across a whole sequence. This is the architecture under every modern LLM, and Chapter 2 takes it apart piece by piece.
  • 2018 Pre-training becomes the recipe. BERT (Google) and GPT-1 (OpenAI) showed you could pre-train once on enormous unlabelled text, then adapt cheaply to specific tasks. This is the birth of the foundation model idea.
  • 2020 Scale as a strategy. GPT-3, at 175 billion parameters, could perform tasks it was never explicitly trained on, purely from instructions written in the prompt. "Prompting" became a skill worth having.
  • 2022 Instruction tuning and RLHF. InstructGPT, and then ChatGPT in November 2022, showed that teaching a model to follow instructions helpfully mattered more to users than raw size did.
  • 2023-present The production era. Long context windows, multimodality, tool calling, strong open-weight models, and a shift in the interesting problems — from "can it do this?" to "can it do this reliably, cheaply and safely at scale?" Most of this course lives here.
In plain English: we went from hand-written grammar rules, to counting words, to representing words as numbers, to reading text sequentially, to reading it all at once with transformers, to pre-training giant models once and reusing them everywhere.

1.6 Foundation models

Before 2018, each task meant its own model. Want sentiment analysis? Collect labelled reviews and train a sentiment model. Want product categorisation? Start again from scratch with a new labelled dataset. Every task paid the full cost of data collection and training.

The foundation model flipped that economic structure on its head.

[def] Foundation model

A foundation model is a large model trained on a broad sweep of general data, deliberately designed to be adapted to many different downstream tasks rather than built for one. The term was coined by Stanford's Center for Research on Foundation Models in 2021, though the practice began with BERT and GPT-1 in 2018.

Task-specific models versus one adaptable foundation model Left side: three separate labelled datasets each feed their own expensive training run, producing three narrow single-purpose models. Right side: one very large general text corpus trains a single foundation model once, which is then cheaply adapted into the same three capabilities through prompting. BEFORE: one model per task 50k reviews 80k products 30k tickets Train weeks Train weeks Train weeks Sentiment Category Routing AFTER: one model, many tasks Trillions of words of general text no labels needed FOUNDATION MODEL trained once, by someone with a data centre Sentiment a prompt Category a prompt Routing a prompt Adding a fourth task costs one more prompt, not another training run. The trade you are making: you no longer control the training data, the model is far larger than any single task needs, and you pay per call forever rather than once up front. Section 1.8 returns to when that trade is the wrong one to make.
Figure 1.3 — The economics shifted. The expensive general training happens once, by someone else, and you rent the result. What used to be a multi-week project with a data-labelling budget becomes an afternoon spent writing a prompt.

[retail] Why this matters for a store

A mid-size retailer could never justify training a language model from scratch. Collecting hundreds of thousands of labelled examples per task is out of reach. Foundation models mean that same retailer can ship product-description generation, review summarisation and a support assistant in a single quarter, because the linguistic heavy lifting was already paid for by someone else.

1.7 Parameters and weights: what is actually inside

We keep saying a model is "a big pile of learned numbers". Let us be precise, because two terms — parameters and weights — get used loosely and you should know the difference.

[def] Parameters and weights

Parameters are all the numbers inside a model that were adjusted during training. When someone says "a 7B model", they mean 7 billion parameters.

Weights are the largest category of parameter — the multipliers on connections between neurons. The other category is biases, small offsets added after multiplying. In everyday speech people say "weights" to mean all the parameters, and "downloading the weights" means downloading the whole model.

Here is the smallest honest example. Predict a shipment's cost from weight and distance:

A model with exactly three parameterspython
# w1 and w2 are weights; b is a bias. Three parameters total.
def shipping_cost(weight_kg, distance_km, w1, w2, b):
    return w1 * weight_kg + w2 * distance_km + b

# "Training" means finding good values for w1, w2 and b
# by looking at thousands of past shipments.
shipping_cost(weight_kg=2.0, distance_km=300,
              w1=1.20, w2=0.008, b=2.50)
# -> 1.20*2.0 + 0.008*300 + 2.50 = 7.30

That is genuinely all a parameter is: a number that gets multiplied or added, whose value was tuned so predictions match reality. A large language model is the same idea at a different quantity — billions of them, arranged in layers. There is no extra magic ingredient, only scale and structure.

Parameter counts, and what they cost you to run
Model Year Parameters Memory at 16-bit Where it can run
Word2Vec2013~50M~0.1 GBA laptop
BERT-base2018110M~0.2 GBA laptop
GPT-220191.5B~3 GBA decent GPU
GPT-32020175B~350 GBA cluster
Llama 3 8B20248B~16 GBOne good GPU
Frontier models2024+undiscloseddata-centre scaleAn API call

The arithmetic worth memorising: parameters times 2 bytes equals gigabytes of memory at 16-bit precision. An 8B model needs roughly 16 GB just to hold the weights, before any working memory for the actual conversation. This one calculation decides whether you can self-host or must rent an API.

In plain English: parameters are the dial settings inside the model, learned during training. More parameters generally means more capability, and definitely means more memory and cost. Double the parameter count to get gigabytes needed.

1.8 Large vs small language models

There is no official parameter count at which "small" becomes "large" — the boundary moves every year. What stays constant is the shape of the trade-off.

Small language models (SLMs)

Roughly under 10B parameters. Phi-3, Llama 3 8B, Mistral 7B, Gemma.

  • Runs on one GPU, sometimes a good CPU
  • Fast: low latency, high throughput
  • Cheap per call, and cost is predictable
  • Can run on-premises, so data never leaves
  • Weaker at multi-step reasoning
  • Narrower world knowledge

Large language models (LLMs)

Hundreds of billions of parameters. GPT-4 class, Claude Opus, Gemini Ultra.

  • Needs a cluster; realistically an API
  • Slower per response
  • 10 to 100 times the cost per call
  • Usually means data leaves your network
  • Strong multi-step reasoning
  • Broad world knowledge

[retail] Choose per task, not per company

The mature pattern is a mixed fleet. A store handling 50,000 assistant messages a day might route like this:

Model routing by task in a retail assistant
Task Volume per day Model size Why
Detect intent: browse, track order, or return 50,000 Small Simple classification. Speed and cost dominate.
Rewrite a follow-up into a standalone query 20,000 Small Mechanical rewriting. No deep reasoning needed.
Re-rank 50 search results for relevance 15,000 Mid Needs judgement, but the task is bounded and repetitive.
Explain a complex return-policy edge case 800 Large Low volume, high stakes, genuine reasoning required.
Draft new product descriptions 200 Large Quality is customer-visible and semi-permanent.

Routing those 50,000 intent calls to a large model instead of a small one can be the difference between a modest monthly bill and one twenty times larger, for an identical user experience. This is the highest-leverage cost decision in most LLM applications. Chapter 5 covers how to implement the routing layer.

1.9 Pre-trained vs fine-tuned models

Training a modern LLM happens in stages. Knowing the stages tells you which lever to pull when the model is not doing what you want.

  1. Pre-training: learning language itself The model reads an enormous amount of text and repeatedly plays one game: predict the next word. No human labels are needed, because the text supplies its own answers — hide the next word, guess it, check, adjust. Do this trillions of times and grammar, facts, reasoning patterns and style all get absorbed. This costs millions of dollars and takes months.
  2. Supervised fine-tuning: learning to be useful A raw pre-trained model only continues text. Ask it a question and it might reply with a list of more questions, because that is a plausible continuation of a document. So it is trained further on curated pairs of instruction and good response. Now it answers rather than continues.
  3. Alignment (RLHF and successors): learning to be preferred Humans compare pairs of model outputs and pick the better one. The model is tuned toward the preferred style: helpful, honest, willing to say "I don't know", and declining harmful requests. Reinforcement Learning from Human Feedback is what separated ChatGPT from GPT-3 in users' eyes, despite similar underlying capability.
  4. Your fine-tuning: optional, and usually skipped You can continue training on your own examples to teach a consistent output format or house style. Modern practice uses parameter-efficient methods such as LoRA (2021), which trains a small add-on adapter instead of all the weights, cutting cost by orders of magnitude.

[!] The most common expensive mistake

Teams reach for fine-tuning to fix a knowledge problem. "The model doesn't know our products, so let's fine-tune it on our catalogue." This almost always disappoints.

Fine-tuning is good at teaching form: tone, output structure, house style, the shape of a specialised task. It is unreliable at teaching facts, because facts baked into weights cannot be updated when a price changes, cannot be cited back to a source, and blur together with similar facts. When the need is "the model must know our data", the right tool is retrieval, covered in Chapter 4. The rule to remember: fine-tune for behaviour, retrieve for knowledge.

Choosing between prompting, retrieval and fine-tuning
What you need Reach for Cost shape Updates when data changes
A different tone or output format Prompting first; fine-tuning only if it must be perfect every time Near zero, then moderate Instant
The model must know your live catalogue Retrieval (RAG) Low per call Instant, just reindex
A highly specialised task with thousands of examples Fine-tuning High up front, low per call Requires retraining
To cut cost on a huge-volume simple task Fine-tune a small model High up front, very low per call Requires retraining
In plain English: pre-training teaches the model language. Instruction tuning teaches it to answer. Alignment teaches it to be pleasant and safe. Your own fine-tuning teaches it your format — but never rely on it to teach facts.

1.10 Tokens and tokenization

Here is a fact that surprises people: a language model has never seen a word. It works entirely with numbers. Tokenization is the translation layer between the text you write and the numbers the model consumes.

[def] Token and tokenization

A token is the smallest chunk of text a model handles as a single unit. Roughly a word, but frequently a piece of one.

Tokenization is the process of cutting text into those chunks and mapping each to an integer ID from a fixed vocabulary.

Why not just use words?

The obvious design is one token per word. It was tried, and it fails in three ways.

  1. The vocabulary explodes English has millions of word forms once you include names, plurals, typos and product codes. Every distinct word needs its own row in a lookup table, and that table becomes enormous.
  2. Unknown words break everything Your catalogue contains "Hydroflask", "size-12EE" and "Ryobi". A word-level model that never saw them in training has literally no representation, and must fall back to a useless placeholder.
  3. Obvious relationships are lost "Walk", "walking" and "walked" become three unrelated entries. The model has to learn each independently instead of sharing what it knows about "walk".

The other extreme — one token per character — solves those problems but creates a worse one: sequences become very long, and the model must spend its capacity learning that "c-a-t" spells a word before it can learn anything about cats.

[+] Subword tokenization: the compromise that won

Modern models use subword tokenization. Common words stay whole; rare words get split into meaningful pieces. "Walking" becomes "walk" + "ing", so the relationship to "walk" is preserved. "Hydroflask" becomes "Hydro" + "fl" + "ask" — never seen before, still representable. Byte Pair Encoding, borrowed from a 1994 compression algorithm and applied to NLP by Sennrich et al. in 2015, is the dominant method. WordPiece (BERT) and SentencePiece are close relatives.

How a sentence becomes token IDs A product query is split into subword tokens. Common words stay whole while the unusual brand name is split into three pieces. Each token is then mapped to an integer ID, and those integers are what the model actually receives. STEP 1 — the raw text you typed waterproof Hydroflask bottles under $40 STEP 2 — split into subword tokens waterproof Hydro fl ask bottle s under $ 40 amber = one word, split into 3 tokens STEP 3 — look up each token's ID. This is all the model ever sees. [3919, 30980, 1489, 1029, 15112, 82, 1234, 3, 1272] 9 tokens for 5 words. The brand name cost 3 tokens on its own — unusual words are always more expensive.
Figure 1.4 — Tokenization in three steps. Notice that the model never receives letters or words, only the integer IDs on the black strip. Everything the model "knows" about language is a statistical relationship between those integers.

Tokens are the unit of billing, speed and memory

Tokens are not an implementation detail you can ignore. They are the unit in which you pay, the unit that limits how much the model can read, and the unit that determines how long a response takes.

[retail] Counting the real cost of one feature

Suppose the store wants an AI summary on every product page: three bullet points distilled from customer reviews. Here is the arithmetic that decides whether this ships.

Token accounting for one product-page summary
Component Approximate tokens Note
System prompt (the instructions) 120 Paid on every single call
20 customer reviews 2,400 Around 120 tokens per review
Product title and specifications 180 Codes and dimensions tokenize badly
Total input 2,700 What you send
Output (three bullets) 90 Usually billed at a higher rate than input

Now multiply. A catalogue of 20,000 products is 54 million input tokens for a single full pass. At a mid-range model's pricing that is a meaningful but survivable one-off cost — and a catastrophic one if you regenerate it on every page view.

The lesson: generate once, cache the result, and regenerate only when the reviews actually change. The naive implementation, which calls the model on every page load, costs thousands of times more for an identical user experience. Caching is covered properly in Chapter 8.

[!] Four tokenization traps that bite in production

  • Non-English text costs more. Tokenizers are trained mostly on English. The same sentence in Hindi, Thai or Japanese can consume two to three times the tokens, so an international storefront costs more per customer for identical content.
  • Structured data is expensive. JSON, SKUs and dimension strings like 42.5cm x 18.2cm fragment into many tokens. Sending raw JSON when a compact sentence would do is a common and invisible waste.
  • Models cannot reliably count letters. Asking "how many r's are in strawberry" is hard precisely because the model sees token IDs, not letters. This is not a reasoning failure; it is a representation limit.
  • Every model tokenizes differently. The same text is a different token count on different providers, so cost estimates do not transfer when you switch models.
In plain English: the model reads numbers, not words. Text gets chopped into subword chunks called tokens, and those tokens are what you pay for, what fills the memory limit, and what determines speed. Roughly: 1 token is about 4 characters, or about 0.75 of an English word.

1.11 Context and the context window

Now the single most misunderstood idea in the whole field. Get this one right and a great deal of confusing LLM behaviour suddenly makes sense.

[def] Context and context window

Context is everything the model can see at the moment it generates the next token: your system instructions, the conversation so far, any retrieved documents, and the response it is part-way through writing.

The context window is the hard maximum number of tokens that can fit. Exceed it and something must be dropped.

[!] The model has no memory

This is the part that trips everyone up. An LLM does not remember your previous message. It is a stateless function: text in, text out, nothing retained between calls. When a chatbot appears to remember that you asked about hiking boots, it is because your application re-sent the entire conversation with the newest message appended. Every single turn. The illusion of memory is a feature your code implements, not something the model provides.

How conversation history is resent on every turn Three successive chat turns. Turn one sends only the system prompt and the first question. Turn two resends all of turn one plus its answer, along with the new question. Turn three resends everything again, showing that the payload grows with every exchange. TURN 1 — about 150 tokens sent system prompt "waterproof boots?" TURN 2 — about 420 tokens sent, turn 1 repeated in full system prompt "waterproof boots?" previous answer "under $100?" TURN 3 — about 760 tokens sent, everything repeated again system prompt "waterproof boots?" previous answer "under $100?" answer 2 Total cost grows with the square of the conversation length, not linearly. A 20-turn conversation does not cost 20 units. Because each turn resends everything before it, the running total lands closer to 210 units. This is why long chats become slow and expensive, and why production systems summarise or trim old turns instead of resending them forever. Chapter 9 covers the strategies.
Figure 1.5 — Statelessness in practice. The model re-reads the whole conversation on every turn. That single fact explains why it appears to remember, why long chats slow down, and why costs escalate faster than teams expect.

How context windows grew, and what it cost

Context windows have expanded dramatically. This is one of the clearest capability jumps of the last few years.

Context window growth over time
Model Year Context window Roughly equivalent to
GPT-220191,024Two pages
GPT-320202,048Four pages
GPT-3.520224,096Eight pages
GPT-420238,192Sixteen pages
Claude 22023100,000A short novel
GPT-4 Turbo2023128,000A long novel
Gemini 1.5 Pro20241,000,000+A dozen novels

Why did this take so long? Because of how attention works, doubling the context originally quadrupled the computation required. Chapter 2 explains the mechanism. Getting to a million tokens took genuine architectural innovation, not just bigger machines.

[!] A big window is not a licence to fill it

Three reasons a million-token window does not mean you should send a million tokens:

  • You pay per token. Filling a 128K window on every request costs roughly thirty times more than sending a well-chosen 4K.
  • Latency scales with input. The model must read everything before writing its first word. Huge contexts mean visibly slower responses.
  • Accuracy degrades in the middle. Research published in 2023 (Lost in the Middle, Liu et al.) found models reliably use information at the very start and very end of a long context, while facts buried in the middle are frequently missed.

This last finding is why retrieval beats stuffing. Sending 8 carefully selected paragraphs produces better answers than dumping 400 mediocre ones, and costs a fraction as much. That insight is the entire justification for RAG, which Chapter 4 builds from scratch.

[retail] Budgeting a context window

Treat the window as a fixed budget to allocate deliberately. For a support assistant on an 8K model:

A worked context budget for a retail support assistant
Allocation Tokens Rationale
System prompt and rules400Tone, policy, refusal behaviour
Retrieved policy documents2,000Top 4 chunks, most relevant last
Customer order details600Only the current order
Recent conversation3,000Last 6 turns; older ones summarised
Reserved for the answer1,500Must be left free
Total7,500Deliberately under the 8,192 limit

Note the reserved output space. The context window covers input and output together. A frequent production bug is filling the window with input, leaving the model no room to answer, and getting a truncated response mid-sentence.

In plain English: the context window is the model's desk. Everything it needs must fit on that desk at once, including space to write the answer. Bigger desks exist now, but a tidy desk still beats a cluttered one.

1.12 Inference: what happens when you press send

[def] Inference

Inference is the act of using a trained model to produce an output. Training is building the model; inference is running it. Training happens once and costs millions. Inference happens billions of times and is what you actually pay for in production.

Here is the part that surprises people most. A model does not compose a sentence, or plan an answer, or decide what it is going to say. It does exactly one thing:

[+] The only thing a language model does

Given a sequence of tokens, predict a probability for every possible next token. That is it. Everything else — conversation, reasoning, translation, writing code — is that one operation repeated in a loop.

Generating a ten-word answer means running the model roughly thirteen separate times. Each run produces one token, which is appended to the input, and then the whole thing runs again. This is called autoregressive generation: the model's own output feeds back in as input.

  1. Tokenize the input Your text becomes token IDs, as in section 1.10. "Best boots for rain" becomes something like [6435, 16512, 329, 6290].
  2. Run a forward pass Those IDs travel through every layer of the network. Chapter 2 opens this box; for now treat it as a very large mathematical function.
  3. Produce logits The output is one raw score per token in the vocabulary. For a 50,000-token vocabulary that is 50,000 numbers, one for every word the model could say next. These raw, unnormalised scores are called logits.
  4. Convert logits to probabilities A function called softmax squeezes those raw scores into probabilities that sum to 1. Now you have a genuine probability distribution over the vocabulary.
  5. Sample one token Pick a token from that distribution. How you pick is where temperature and top-p come in, which is the next section.
  6. Append and repeat Add the chosen token to the sequence and go back to step 2. Stop when the model emits a special end-of-sequence token, or when you hit your maximum output length.
The autoregressive generation loop A cycle diagram. Token IDs enter the model, which outputs one raw score per vocabulary word. Softmax converts these to probabilities, one token is sampled, appended to the sequence, and the loop repeats. Below, a worked example shows the probability distribution for the next word after the phrase "these boots are fully". Token IDs [6435, 16512] Forward pass through all layers Logits 50,000 raw scores Softmax to probabilities Sample one token append the new token and run the whole thing again Worked example: what comes after "these boots are fully"? waterproof 0.61 lined 0.21 sealed 0.09 refundable 0.04 purple 0.008 ...49,995 more 0.04 total Every one of the 50,000 vocabulary tokens gets a probability, including absurd ones. The model does not "know" the right answer — it produces a ranked distribution, and the sampling rules decide what to take.
Figure 1.6 — One generation step. The loop at the top runs once per token produced. The bars show the actual output of a single step: a ranked probability distribution over the entire vocabulary, from which exactly one token is chosen.

Why this loop shapes everything about performance

Once you understand that generation is a loop with one model run per token, several production behaviours stop being mysterious.

Performance consequences of the generation loop
Term What it means Why the loop causes it
Time to first token Delay before anything appears The model must read the entire input once before producing anything. Long prompts mean long waits.
Tokens per second Speed after output starts One full model run per token. Larger models run each loop more slowly.
Output length dominates latency Long answers take proportionally longer A 500-token answer needs 500 sequential runs. You cannot parallelise it, because each token depends on the one before.
Streaming Words appear as they are generated Tokens are produced one at a time anyway, so they can be sent as they arrive rather than held back.
Batching Serving many users at once A GPU can run the loop for many independent requests simultaneously, which is why hosted APIs are cheaper than self-hosting for spiky traffic.

[retail] Streaming is a product decision, not a technical one

Consider a support assistant that takes 6 seconds to produce a 300-token answer.

Without streaming

The customer stares at a spinner for 6 seconds, then the whole answer appears at once. Many users assume it has hung and click away at around 3 seconds.

With streaming

The first words appear after roughly 0.4 seconds and the rest flows in. The total time is identical, but it feels immediate and abandonment drops sharply.

Identical latency, completely different experience. This is why almost every customer-facing AI feature streams. Chapter 12 covers the implementation with Server-Sent Events and WebSockets.

In plain English: the model writes one token at a time, in a loop, and cannot skip ahead. Long inputs delay the start; long outputs stretch the finish. Streaming does not make it faster, it makes the waiting invisible.

1.13 Temperature, top-p and top-k

Step 5 of the loop said "sample one token from the distribution". That word sample is doing a lot of work. These three settings control how the choice is made, and they are the dials you will actually touch in production.

The simplest strategy, and why it is not enough

The obvious approach is to always take the highest-probability token. This is called greedy decoding. It sounds ideal — always pick the best option — but it produces noticeably poor text.

The reason is subtle: the best word at each individual step does not add up to the best sentence. Greedy decoding gets stuck in loops ("the product is very very very good"), produces bland phrasing, and cannot recover from an early wrong turn because it never considers alternatives.

[def] Temperature

Temperature reshapes the probability distribution before sampling. Values usually run from 0 to 2.

  • Low (0 to 0.3) — likely tokens become even more likely. Focused, predictable, repetitive.
  • Medium (0.7 to 1.0) — the distribution is left roughly as the model produced it. Balanced.
  • High (1.2 to 2.0) — flattens the distribution, giving unlikely tokens a real chance. Creative, and eventually incoherent.

The name comes from physics, specifically the Boltzmann distribution in statistical mechanics: heat a system and its particles occupy a wider spread of states. Same mathematics, same intuition.

The same prediction at three different temperatures Three bar charts side by side using the same five candidate words. At temperature 0.2 the top word takes almost all the probability. At 0.8 there is a clear favourite but real variety. At 1.5 all five words have comparable probability. TEMPERATURE 0.2 focused, near-deterministic waterproof .94 lined .05 sealed .01 refundable .00 purple .00 Nearly always the same word. Right for facts, extraction and classification. TEMPERATURE 0.8 balanced, natural waterproof .61 lined .21 sealed .09 refundable .04 purple .01 Usually the top word, but with genuine variety. Right for chat and general writing. TEMPERATURE 1.5 flattened, unpredictable waterproof .31 lined .25 sealed .19 refundable .15 purple .10 "boots are fully purple" is now plausible. Rarely what you want in retail.
Figure 1.7 — Temperature does not change what the model predicts. The underlying ranking is identical in all three panels. Temperature only changes how sharply that ranking is enforced when one token is chosen.

Top-k and top-p: trimming the candidate list

Temperature rescales probabilities but never removes a candidate. Even at a low setting, "purple" keeps a tiny chance — and across thousands of generations, tiny chances happen. Top-k and top-p solve that by cutting the list before sampling.

[def] Top-k sampling

Keep only the k most likely tokens, discard everything else, and sample from what remains. With k = 3 only "waterproof", "lined" and "sealed" survive. Introduced for neural text generation around 2018.

[def] Top-p sampling, also called nucleus sampling

Keep the smallest set of tokens whose probabilities add up to p. With p = 0.9, walk down the ranked list accumulating probability and stop at 90%. Proposed by Holtzman et al. in 2019, and now the more common default.

Why top-p generally beats top-k

The weakness of top-k is that it is rigid. A fixed k cannot adapt to how confident the model is, and confidence varies enormously between one token and the next.

Top-k struggles

Confident moment. After "the capital of France is", the model is 99% sure of "Paris". With k = 40 you keep 39 irrelevant alternatives and give them a combined chance of being chosen.

Uncertain moment. After "my favourite colour is", dozens of answers are equally valid. With k = 3 you have needlessly amputated the variety.

Top-p adapts

Confident moment. "Paris" alone already covers 90% of the probability, so the candidate set is just one token. No nonsense can be selected.

Uncertain moment. Reaching 90% now takes 25 tokens, so the set widens automatically. The cut-off follows the model's own confidence.

[!] Do not tune both at once

Temperature and top-p interact in ways that are hard to reason about. The widely followed convention is to change one and leave the other at its default. Most teams adjust temperature and leave top-p at 1.0, or set temperature to 1.0 and tune top-p. Turning both dials at once makes behaviour difficult to explain when something goes wrong at 2am.

[retail] Settings by task, with reasoning

Recommended sampling settings for retail AI features
Feature Temperature Why
Extracting a size or colour from a query 0.0 One correct answer exists. Any variation is a bug.
Classifying intent 0.0 to 0.2 Must be repeatable, or your analytics become meaningless.
Re-ranking search results 0.0 to 0.3 The same query should give the same ordering to every customer.
Answering a policy question 0.2 to 0.4 Grounded in documents. Wording may flex; facts may not.
Conversational assistant 0.6 to 0.8 Repetitive phrasing feels robotic across a long chat.
Drafting product descriptions 0.8 to 1.0 You want distinct copy for 500 similar t-shirts.
Brainstorming campaign slogans 1.0 to 1.3 A human filters the output, so unusual ideas are the point.

The pattern is simple: the closer a task is to a fact, the lower the temperature. The closer it is to taste, the higher.

1.14 Deterministic vs non-deterministic generation

[def] Determinism

A process is deterministic if identical input always produces identical output. It is non-deterministic if the same input can produce different results on different runs.

Standard software is deterministic and we rely on that completely. Call calculateTax(100) a thousand times and you expect the same answer a thousand times. Language models break that expectation by default, and that has real consequences for testing, debugging and customer trust.

Where the randomness comes from

The model itself is deterministic. Feed the same tokens through the same weights and you get the same probability distribution every time, down to the last decimal. The randomness lives entirely in step 5 of the loop: sampling. Drawing from a distribution is a dice roll, and a different roll gives a different token, which changes all subsequent context, which changes everything after it.

[!] Temperature 0 is not a determinism guarantee

This trips up experienced engineers, and it is a favourite interview question. Setting temperature = 0 means "always take the most likely token", which sounds perfectly deterministic. In practice you can still get different outputs from identical requests. Three reasons:

  • Floating-point arithmetic is not associative. On a GPU, thousands of calculations run in parallel and finish in a non-guaranteed order. Adding the same numbers in a different order can change the final digit, which is enough to flip which of two near-tied tokens ranks highest.
  • Ties have to be broken somehow. When two tokens have genuinely equal probability, the winner depends on implementation details you do not control.
  • The provider's system changes underneath you. Silent model updates, altered batching strategies, or different hardware in the serving fleet all shift results. Your code did not change; the substrate did.

Practical guidance: temperature 0 gives you high consistency, not a mathematical guarantee. Design systems that tolerate occasional variation rather than assuming it cannot happen.

How to get closer to reproducibility

  1. Set temperature to 0 The single largest factor. Removes deliberate randomness from sampling.
  2. Pass a seed if the provider supports one A fixed seed makes the random draws repeatable. Several APIs expose this, often alongside a system fingerprint that tells you when the backend changed.
  3. Pin the exact model version Use a dated or versioned model identifier rather than a moving alias. An alias like "latest" will silently change under you, and your carefully tested prompts will behave differently overnight.
  4. Constrain the output format Requiring strict JSON with a fixed schema eliminates most surface variation. The prose may wobble; the structure will not.
  5. Cache aggressively The most reliable way to return the same answer twice is to not ask twice. Store the result against a hash of the input.

[retail] When variation is a bug and when it is a feature

Variation is a bug

  • Two customers get different prices for one product
  • The same query returns a different result ranking each refresh
  • A returns-policy answer changes wording on the facts
  • Intent classification flips, corrupting your funnel analytics

Variation is fine, or wanted

  • Greeting messages that would feel canned if identical
  • Product descriptions across a range of similar items
  • Marketing copy suggestions for a human to choose between
  • Conversational phrasing across a long support chat

The test to apply: would a customer be upset to learn someone else got a different answer? If yes, drive temperature to 0 and cache the result.

In plain English: the model's thinking is deterministic; the dice roll that picks each word is not. Temperature 0 makes that roll nearly always land the same way, but hardware and provider changes mean "nearly" is the honest word.

1.15 Hallucinations

The most talked-about failure mode of language models, and the most misunderstood.

[def] Hallucination

A hallucination is output that is fluent, confident and plausible, but factually wrong or entirely invented. The term entered wide use around 2018 in machine translation research, and became mainstream vocabulary after 2022.

Why hallucination is not a bug

This is the crucial insight, and it changes how you design around the problem.

A language model was trained to produce plausible continuations of text. It was never trained to produce true statements. Truth and plausibility overlap heavily, which is why models are useful at all — but they are not the same thing, and when they diverge the model follows plausibility every time.

[!] The model cannot tell that it does not know

When you ask about a product that does not exist, the model does not perform a lookup, fail to find it, and report the absence. There is no lookup. It generates the most statistically plausible continuation of your question — and a confident product description is far more plausible, given its training data, than "I have no record of that." Fluency is not evidence of knowledge, and confidence is not calibrated to accuracy.

The main varieties

Type 1

Factual fabrication

Inventing specifications, prices, dates or people. "The Trailmaster X2 has a 12-hour battery" for a product with no published battery figure.

Type 2

Source fabrication

Citing documents, studies or policy sections that do not exist. Particularly dangerous because a citation reads as evidence.

Type 3

Contextual contradiction

Contradicting the documents you supplied. You provide a 30-day returns policy and the answer says 90 days.

Type 4

Instruction drift

Quietly ignoring a constraint. You asked for three bullet points under ten words and received five paragraphs.

[retail] What a hallucination actually costs

These are not hypothetical. Each of these has a direct commercial consequence:

Hallucination scenarios and their business impact
Scenario Consequence Severity
Assistant invents a 90-day returns window You must honour it or face a complaint you will lose High
Description claims a jacket is waterproof when it is shower-resistant Returns, negative reviews, potential advertising-standards issue High
Assistant quotes a discount that does not exist Revenue loss or a public argument at the checkout High
Summary references a review nobody wrote Erosion of trust once a customer notices Medium
Slightly wrong dimensions in generated copy Occasional mismatched expectations Medium

Note that every high-severity row involves the model stating a policy or specification — precisely the things that live in your database and should never be generated from memory.

How to reduce hallucination, in order of effectiveness

You cannot eliminate hallucination, because it is inherent to how the model works. You can make it rare and, more importantly, make it detectable.

  1. Ground the model in retrieved facts By far the biggest win. Instead of asking "what is our returns policy?", retrieve the actual policy document and ask "using only the text below, answer the question." The model shifts from recalling to reading. This is RAG, and Chapter 4 is devoted to it.
  2. Give explicit permission to refuse Add to your system prompt: "If the provided context does not contain the answer, say you do not know." Models will not do this by default, because refusing is a less plausible continuation than answering. You have to make it an instruction.
  3. Require citations Ask for the source of each claim. This helps in two ways: it nudges the model toward supported statements, and it makes unsupported ones visible to you and the user.
  4. Lower the temperature Higher temperatures sample lower-probability tokens, and lower-probability tokens are more likely to be wrong. For factual tasks, stay near zero.
  5. Never let the model produce authoritative numbers Prices, stock levels, order status and delivery dates should be inserted from your database into the response template, not generated. If a number matters, it should never pass through the sampling step.
  6. Validate the output programmatically Check that any product mentioned exists in your catalogue. Check any quoted price against your database. Automated verification catches what prompting cannot.

[+] The architectural principle

Use the model for what it is genuinely good at — understanding a messy question, and phrasing an answer clearly — and use your database for what it is good at: knowing facts. A well-designed retail assistant uses the LLM as a language interface over trustworthy data, never as the source of truth itself. Most production hallucination incidents trace back to violating that boundary.

In plain English: the model is a fluent guesser, not a database. It guesses very well, which is exactly what makes wrong guesses dangerous. Give it the facts to read, let it refuse, and never let it invent a number.

1.16 Model bias and limitations

[def] Model bias

Bias is a systematic skew in a model's output that reflects patterns in its training data rather than the reality you want represented. It is not occasional randomness; it is a consistent lean in a particular direction.

Bias is not a moral failing of the model, and it is not something a vendor forgot to switch off. A model trained on human text absorbs the statistical regularities of that text, including the ones we would rather it did not.

Where bias comes from

Source

Training data skew

The internet is not a balanced sample of humanity. It over-represents English, wealthy countries, younger writers and certain professions.

Source

Historical patterns

Text written over decades encodes the assumptions of those decades. The model learns "how people wrote about this", not "how it ought to be".

Source

Annotator preferences

Alignment involves humans ranking outputs. Their collective taste in tone, directness and formality becomes the model's default voice.

Source

Frequency effects

Common things are predicted more readily than rare ones. Well-documented brands get described confidently; niche ones get invented.

[retail] How bias shows up in a store, concretely

  • Gendered product assumptions. Asked to write copy for a cordless drill, the model reaches for "he"; for a scented candle, "she". Multiply that across 20,000 product descriptions and you have published a pattern nobody approved.
  • Uneven quality across your catalogue. Descriptions for well-known brands read fluently and accurately. Descriptions for small suppliers are vaguer and more prone to invention, because the model has less to draw on.
  • Language and region gaps. Your English storefront gets natural copy. The same prompt in a less-represented language produces stilted text, costs more in tokens, and hallucinates more often.
  • Name-based assumptions. Support replies can subtly shift in formality based on the customer's name, which is both unfair and a genuine compliance risk.
  • Western-default framing. Seasonal copy assumes December is winter, which is wrong for half your customers.

The honest limitations list

Separate from bias, these are structural limits worth knowing before you promise something to a stakeholder.

What language models are structurally bad at, and why
Limitation Underlying reason What to do instead
Arithmetic and precise counting Predicting plausible digits is not calculating Call a calculator or your database
Knowing current facts Training data has a cut-off date Retrieve live data and pass it in
Counting characters in a word It sees tokens, not letters Do it in code
Knowing what it does not know No internal confidence signal you can trust Ground in documents and validate outputs
Long chains of strict logic Errors compound across steps Break into verified stages, or use code
Genuine consistency at scale Sampling introduces variation Temperature 0, caching, templates
In plain English: the model learned from human writing, so it inherited human patterns, including unhelpful ones. Test your outputs across the full range of customers you actually serve, not just the ones the internet writes about most.

1.17 Grounded generation

Everything in this chapter has been building to this idea. It is the single most important architectural pattern in applied generative AI, and it is the bridge into the rest of the course.

[def] Grounded generation

Grounded generation means giving the model the facts it needs inside the prompt, and instructing it to answer only from those facts. The model stops being a source of knowledge and becomes a reader and explainer of knowledge you supply.

The same question, two architectures

Ungrounded

Prompt: "What is our returns policy for sale items?"

The model searches its weights for something plausible. It has read thousands of returns policies during training and produces an average of them.

Answer: "Sale items can usually be returned within 14 days provided tags are attached."

Problem: confident, reasonable, well-written, and possibly nothing to do with your actual policy. There is no way to check it and no source to point at.

Grounded

Prompt: your policy text, followed by the question and the instruction to use only that text.

The model reads the supplied passage and answers from it, the way a person would answer while looking at the page.

Answer: "Sale items are final and cannot be returned unless faulty. [Source: returns-policy section 4.2]"

Result: correct, checkable, attributable, and it updates the moment you change the document.

The shape of a grounded prompttext
# SYSTEM
You answer customer questions about returns.
Use only the CONTEXT below.
If the context does not contain the answer, say:
"I don't have that information — let me connect you to an agent."
Cite the section for every claim you make.

# CONTEXT (retrieved from your document store)
[returns-policy 4.1] Unworn items may be returned within 30 days.
[returns-policy 4.2] Sale items are final and cannot be returned
                     unless faulty.
[returns-policy 4.3] Faulty goods are refunded in full at any time.

# USER
Can I return the discounted jacket I bought last week?

Three things are doing the work here. The instruction to use only the context constrains where answers may come from. The explicit escape hatch gives the model a plausible path other than inventing. The citation requirement makes any violation visible.

[+] What grounding buys you

Ungrounded versus grounded generation
Property Ungrounded Grounded
Accuracy on your dataUnreliableHigh
Updates when data changesRequires retrainingImmediate
Can cite a sourceNoYes
Auditable after an incidentNoYes
Works for private dataNoYes
Hallucination riskSubstantialMuch reduced
Token cost per callLowerHigher

The only column where ungrounded wins is cost, and that is a small price for answers you can actually defend.

[!] Grounding is not a guarantee

A grounded model can still contradict its context, particularly when the context is long, when passages conflict, or when the question sits just outside what the documents cover. Grounding moves hallucination from "likely" to "uncommon", not to "impossible". Production systems still validate the output. Chapter 4 covers measuring this properly with faithfulness and groundedness metrics.

The obvious question this raises: how do you find the right documents to put in the context in the first place? With 20,000 products and hundreds of policy pages, you cannot send everything. Answering that question well requires embeddings (Chapter 3), vector search (Chapter 5), and the full retrieval pipeline (Chapter 4).

In plain English: do not ask the model what it remembers. Hand it the page and ask it to read. Everything that follows in this course is machinery for finding the right page to hand over.

1.18 Key takeaways

The ten things worth carrying into every other chapter

  1. A model is learned rules, frozen. Training discovers them once and is expensive; inference applies them billions of times and is what you pay for daily.
  2. Generative means producing, not choosing. If your valid answers fit in a dropdown, a cheaper discriminative model is probably the right call.
  3. The nesting matters commercially. AI contains ML contains deep learning contains generative AI. Reaching for an LLM when classical NLP would do is a hundred-fold cost mistake.
  4. Foundation models changed the economics. Someone else paid for the linguistic heavy lifting; adding a task now costs a prompt, not a training run.
  5. Parameters times two equals gigabytes. That one calculation decides whether you can self-host or must rent an API.
  6. Fine-tune for behaviour, retrieve for knowledge. Baking facts into weights means they cannot be updated, cannot be cited, and blur together.
  7. Tokens are the unit of everything. Billing, latency and the context limit are all measured in them. Roughly four characters each.
  8. The model has no memory. Conversation is an illusion your application creates by resending history, which is why long chats cost more than people expect.
  9. Generation is a loop with a dice roll. One forward pass per token, and sampling is where temperature, top-p and non-determinism all live.
  10. Hallucination is the design, not a defect. The model optimises for plausibility, never truth. Grounding is the fix, and the rest of this course is largely about doing it well.

[i] Vocabulary check

You should now be able to read this sentence and know precisely what every term means and why someone chose those values:

"We run a 7B parameter model at temperature 0.2 with an 8K context window, grounded on retrieved policy chunks, streaming the response."

Seven billion learned numbers, about 14 GB of memory, so it self-hosts on one GPU. Temperature 0.2 means near-deterministic output, appropriate because policy answers must be consistent. An 8K window is the total budget for instructions, retrieved documents, conversation and the answer combined. Grounded means the facts arrive in the prompt rather than from the weights. Streaming means tokens are sent as produced, so the wait feels short.

1.19 Interview drills

Eighteen questions drawn from this chapter, in the form interviewers actually ask them. Try to answer before expanding. The model answers are deliberately concise: what a strong candidate would say in 30 to 60 seconds, plus the follow-up you should expect.

1. What is the difference between generative AI and traditional machine learning?

Traditional ML is usually discriminative: it learns a boundary between categories and picks a label from a fixed set. Generative AI learns the structure of the data well enough to produce new samples that were never in the training set.

Practically, the distinction is whether the answer space is closed or open. Fraud detection has two valid answers, so it is a classification problem. Writing a product description has effectively infinite valid answers, so it needs generation. I would add that reaching for generative AI on a closed-answer problem is a common and expensive mistake.

Expect the follow-up: "When would you deliberately choose the older approach?" Answer: high volume, fixed label set, tight latency or cost budget, or where you need a consistent answer every time.

2. Explain tokens to a non-technical stakeholder, and why they should care.

The model does not read words, it reads numbered chunks called tokens. A token is roughly four characters, or about three quarters of an English word.

They should care because tokens are the unit of billing, the unit that fills the model's memory limit, and the unit that determines speed. If someone asks why a feature costs more in German than English, the answer is tokens. If someone asks why the assistant gets slower deep into a conversation, the answer is tokens.

Expect the follow-up: "Why does non-English cost more?" Because tokenizers are trained predominantly on English, so other languages fragment into more pieces for identical meaning.

3. Does an LLM remember previous messages in a conversation?

No. The model is stateless. Each call is independent, with no memory of anything before it.

The appearance of memory is created by the application resending the entire conversation history on every request. That has two consequences worth planning for: cost grows with roughly the square of conversation length, because each turn resends everything before it; and once history exceeds the context window you must summarise or truncate, which is a design decision, not an automatic behaviour.

Expect the follow-up: "How would you handle a conversation that outgrows the window?" Summarise older turns into a compact synopsis, keep the last few verbatim, and always retain the system prompt.

4. What is temperature, and what would you set it to for a product search feature?

Temperature controls how sharply the model's probability distribution is enforced when sampling the next token. Low values concentrate probability on the most likely tokens; high values flatten the distribution so unlikely tokens get a real chance.

For search or re-ranking I would use 0 to 0.3. The same query should produce the same ordering for every customer, and any variation there is a bug rather than a feature. I would reserve higher temperatures for genuinely creative tasks like drafting marketing copy, where variety is the point and a human reviews the output.

Expect the follow-up: "Would you also change top-p?" No — convention is to tune one or the other, because their interaction is hard to reason about during an incident.

5. Does temperature 0 guarantee identical output every time?

No, and this is a common misconception. Temperature 0 means always take the highest-probability token, which removes deliberate randomness, but it does not guarantee reproducibility.

Three reasons. Floating-point addition on a GPU is not associative, and parallel operations complete in non-guaranteed order, so tiny numerical differences can flip which of two near-tied tokens wins. Ties have to be broken by implementation details you do not control. And providers silently change model versions, batching and hardware underneath you. So temperature 0 gives high consistency, not a mathematical guarantee — design for occasional variation.

This question separates candidates. Most say "yes, deterministic". Knowing why not signals real production experience.

6. What is a hallucination, and why do they happen?

A hallucination is output that is fluent and confident but factually wrong or entirely invented.

The key insight is that it is not a bug. The model was trained to produce plausible continuations of text, never to produce true statements. Those two objectives overlap most of the time, which is why models are useful, but when they diverge the model always follows plausibility. It also has no mechanism for recognising that it does not know something — there is no lookup that can fail. A confident answer is simply a more plausible continuation than an admission of ignorance.

Expect the follow-up: "So how do you reduce it?" Grounding first, explicit permission to refuse, required citations, low temperature, and never letting the model generate authoritative numbers.

7. Our model does not know our product catalogue. Should we fine-tune it?

Almost certainly not. This is the most common expensive mistake in applied LLM work. The rule is fine-tune for behaviour, retrieve for knowledge.

Fine-tuning bakes facts into weights, which creates three problems: you cannot update a price without retraining, the model cannot cite where a fact came from, and similar facts blur together so accuracy is unreliable anyway. Retrieval solves all three — the catalogue stays in a database, updates are instant, and every answer can point at a source. I would reserve fine-tuning for teaching a consistent output format or house style.

Expect the follow-up: "When would you fine-tune?" A narrow repetitive task at very high volume where you want a small cheap model to match a large one, or where output format must be perfect every single time.

8. What is a context window, and what happens when you exceed it?

It is the hard maximum number of tokens the model can consider at once, covering the system prompt, conversation history, retrieved documents and the response being generated.

Exceeding it means something must be dropped, and what gets dropped is your choice to make deliberately. A frequent production bug is filling the window entirely with input, leaving no room for the answer, and getting a response that cuts off mid-sentence. I always reserve explicit output budget when planning the allocation.

Expect the follow-up: "Newer models have million-token windows. Does that solve it?" No — see the next question.

9. If a model has a 1M token context, why bother with retrieval at all?

Three reasons, and they compound.

Cost. You pay per token. Filling a huge window on every request is enormously more expensive than sending a well-chosen few thousand tokens.

Latency. The model reads the entire input before emitting the first token, so large contexts directly degrade time-to-first-token.

Accuracy. The Lost in the Middle research from 2023 showed models reliably use information at the start and end of a long context while frequently missing facts buried in the middle. So eight well-selected paragraphs genuinely outperform four hundred mediocre ones — better answers and lower cost. A big window is a safety margin, not a retrieval strategy.

10. Walk me through what happens when a user sends a message to your chatbot.

At the model level: the text is tokenized into integer IDs. Those run through the network in a forward pass, producing one raw score, a logit, for every token in the vocabulary. Softmax turns those into probabilities. One token is sampled according to the temperature and top-p settings. That token is appended to the sequence and the whole thing repeats, once per output token, until an end-of-sequence token or the length limit.

At the application level, around that: retrieve the conversation history from session storage, run retrieval to fetch relevant documents, assemble the prompt within the context budget, call the model with streaming enabled, validate the output, and persist the new turn.

Strong signal: answering at both levels unprompted. It shows you have built one, not just read about one.

11. Why does response time grow with output length but not much with input length?

Because generation is sequential and reading is parallel. The input is processed in essentially one pass, since the model can attend to all input tokens simultaneously. That gives you time-to-first-token, which grows with input but relatively gently.

Output is different. Each token requires its own full forward pass, and token number 200 cannot be computed until token 199 exists. A 500-token answer means 500 sequential passes that cannot be parallelised. So if you need to cut latency, shortening the requested output is far more effective than trimming the prompt.

Practical follow-up: "How do you make a slow response feel fast?" Stream it. Same total time, dramatically lower abandonment.

12. How would you decide between a small model and a large one?

Per task, never per company. I would map each task against volume, reasoning depth and consequence of error.

High-volume mechanical work — intent classification, query rewriting — goes to a small model, because at tens of thousands of calls a day the cost difference is the entire budget and the task does not need deep reasoning. Low-volume, high-stakes work with genuine reasoning — a complex policy explanation, customer-visible copy — goes to a large model. Getting this routing right is usually the single highest-leverage cost decision in the system.

Bonus point: mention that self-hosting a small model also keeps sensitive data inside your network, which is sometimes the deciding factor regardless of cost.

13. What is grounded generation, and why does it matter commercially?

Grounding means putting the facts the model needs directly into the prompt and instructing it to answer only from those facts. The model shifts from recalling to reading.

Commercially it matters because it makes answers defensible. A grounded answer can cite its source, so you can audit it after a complaint. It updates the instant you edit the underlying document, with no retraining. And it works for private data the model never saw in training. An ungrounded assistant that invents a returns window is a liability you have to honour; a grounded one quotes the policy and points at the clause.

Expect the follow-up: "Does grounding eliminate hallucination?" No. It moves it from likely to uncommon, particularly when context is long or passages conflict. You still validate outputs.

14. A stakeholder asks you to use AI to categorise 50,000 products. How do you respond?

I would push back on reaching for an LLM. Categorisation into a fixed taxonomy is a closed-answer problem, which is classic discriminative classification.

A small trained classifier handles it for a fraction of a cent per item, returns a consistent answer every time, and runs in milliseconds. An LLM would cost orders of magnitude more, run slower, and might return a slightly different category label on different days — which quietly corrupts every downstream report. If we lack labelled training data I might use an LLM once to bootstrap labels, then train a small model on those and serve the small model.

What is being tested: whether you reach for the newest tool reflexively, or pick the right one. The bootstrap answer is the senior move.

15. What is the difference between a foundation model and a fine-tuned model?

A foundation model is trained on a broad sweep of general data and deliberately designed to be adapted to many downstream tasks. A fine-tuned model is a foundation model that has undergone additional training on a narrower dataset to specialise its behaviour.

The significance is economic. Before foundation models, every task needed its own model, its own labelled dataset and its own training run. Now the expensive general training is paid for once by someone else, and adapting to a new task can be as cheap as writing a prompt. That is what made it feasible for a mid-size company to ship language features at all.

16. Where does model bias come from, and how would you test for it in a retail context?

It comes from training data that is not a balanced sample of the world: over-representation of English and wealthy regions, historical writing patterns, the preferences of the humans who ranked outputs during alignment, and frequency effects where well-documented things get described confidently and rare things get invented.

To test it, I would build an evaluation set that deliberately spans the range we actually serve: products across all categories rather than just popular ones, customer names from varied backgrounds, queries in every language we support, and both large brands and small suppliers. Then I would compare output quality across those slices rather than looking only at an aggregate score. Aggregate metrics reliably hide bias, because the well-served majority dominates the average.

Concrete example to cite: gendered pronouns appearing in power-tool versus home-fragrance copy — a pattern nobody approved, published at scale.

17. How would you prevent an assistant from inventing prices?

I would make it structurally impossible rather than trying to instruct it away. Prices should never pass through the sampling step at all.

Concretely: the model produces the language, and the application injects the numbers from the database into a template. If a price must appear inside generated prose, I retrieve it, pass it in the context, require the model to quote it verbatim, and then validate the output programmatically by checking any currency figure against the database before it reaches the customer. Prompting alone is not a control; it is a request.

The principle: use the LLM as a language interface over trustworthy data, never as the source of truth.

18. Your assistant worked fine in testing but hallucinates in production. How do you debug it?

I would work through it in order of likelihood.

First, check whether it is grounded at all. If the answer came from the weights rather than retrieved context, that is the whole problem and everything else is secondary.

Second, check retrieval quality. Very often the model is behaving correctly and retrieval handed it the wrong documents, or nothing at all. Log what was retrieved for the failing queries, not just the final answer.

Third, check context construction. Did history growth push the retrieved documents out of the window? Are the key facts buried in the middle of a long context where they get missed?

Fourth, check what changed. Was the model version pinned? A silent provider update is a genuinely common cause of "it worked last week". And confirm production temperature matches what was tested.

Strong signal: saying "log the retrieved context" early. Most people debug the prompt when the real fault is upstream in retrieval.

[+] How to use these drills

Answer out loud before expanding. Reading a good answer creates a false sense of fluency — the gap only becomes obvious when you try to say it. Aim for a clear 30-second core answer with one concrete example, rather than an exhaustive lecture. Interviewers are listening for whether you have made these trade-offs in practice.

1.20 Where this leads

This chapter deliberately treated the model as a black box: text in, tokens out. That was enough to reason about cost, latency, consistency and hallucination — which is most of what matters day to day.

But several answers ended with "because of how attention works". Why doubling context used to quadruple the compute. Why models read input in parallel but write output one token at a time. Why transformers displaced everything before them in 2017. Chapter 2 opens the box and answers all three from first principles.