05 Β· AI & LLM Systems
LLM fundamentals
What an AI engineer is expected to actually understand. Not backprop math β a correct operating model: enough mechanism to predict behavior, debug failures, and make cost/latency/quality tradeoffs. You must be able to explain hallucination, temperature, and context windows without hand-waving.
01The core loop: next-token prediction
An LLM is a function trained to answer one question, extremely well: given this sequence of tokens, what's the probability distribution over the next token? Generation is that function run in a loop:
context β P(next token) β sample one token β append to context β repeat until stop
Everything strange and wonderful about LLMs falls out of this loop:
- Autoregressive. Each token is generated conditioned on everything before it, one at a time. This is why output streams, why latency scales with output length, and why an early wrong token can steer the whole continuation off course.
- No lookup step. No database, no explicit fact store. Knowledge is compressed into the weights during training as statistical structure β and that compression is lossy, which is the root of hallucination (Β§6).
- "Reasoning" emerges because predicting text written by reasoning humans well requires internal computation that functions like reasoning. Whether to call it that is philosophy; operationally, chain-of-thought works because generating intermediate steps gives the model more serial compute and a scratchpad in its own context (Β§7).
02Tokens, prefill & decode
Models don't see characters or words β they see tokens: subword chunks from a learned vocabulary (BPE-style, ~50β200k entries). "incident" might be one token; "Sentinel" might be two; rare strings, code, and non-English text fragment into more tokens per character.
- Billing and limits are in tokens. Rough English heuristic: 1 token β ΒΎ of a word, ~4 characters. JSON and code are token-inefficient β braces, quotes, and whitespace all cost.
- Token-boundary artifacts explain classic failures: strawberry-r-counting and arithmetic weirdness happen partly because the model literally doesn't see letters or digits individually.
Why input tokens are cheap-ish and output tokens are expensive
Latency splits into two phases with completely different shapes:
Prefill β the prompt
# All input tokens processed
# in PARALLEL, one pass.
attend(tokβ β¦ tokβ) # at once
fast per token β GPU eats the
whole prompt in one gulp.
Cost β prompt size, but the
wall-clock hit is small.
Decode β the output
# Output generated SERIALLY,
# one token per full pass.
while not stop:
next = sample(P(Β·|ctx))
ctx += next # repeatβ¦
slow β dominates wall-clock.
Each token waits for the last.
03Transformer intuition β attention, no heavy math
The problem: to predict the next token, the model must combine information from anywhere in the context β the function name defined 3,000 tokens ago, the "not" that flips a sentence's meaning. Older architectures (RNNs) passed information through a sequential bottleneck; distant context degraded.
Attention is the answer: for every token position, the model computes how relevant is every other token to me right now, and pulls in a weighted blend of their information. Mechanically:
- Each token emits a query β "what am I looking for?"
- Every token offers a key β "what I'm about" β and a value β "what I carry."
- Relevance = queryΒ·key match; the token's updated representation = relevance-weighted sum of values.
It's a soft, learned, content-based lookup over the entire context β done in parallel, not sequentially.
Multi-head, multi-layer: each layer has many attention "heads" learning different relationship types (syntax, coreference β "its" β which noun?, code structure), interleaved with feed-forward layers where much of the stored knowledge seems to live. Stack dozens of layers: early layers resolve local structure, later layers assemble increasingly abstract representations, and the final layer's output is scored against the vocabulary to produce next-token probabilities.
Three consequences worth stating in an interview
- Attention compares every token with every token β O(nΒ²) in context length. This is why long context is expensive and why context windows were historically small.
- Parallelism over the sequence is what made training on internet-scale data feasible β the transformer won on trainability, not just capability.
- During generation, per-token attention results are cached so each new token only computes its own attention β see below.
04Context windows
The context window is the model's entire working memory: system prompt + conversation + retrieved docs + tool definitions + tool results + its own output so far. Nothing outside it exists for the model. There is no persistent memory between calls β "memory" in products is engineering: summarization, retrieval, state you re-inject.
Modern windows are large (128kβ1M+), but "fits" β "used well":
- Lost-in-the-middle: retrieval quality across a long context is not uniform β information buried mid-context is recalled worse than content near the start or end. Placement of critical instructions and facts matters.
- Effective vs advertised length: models degrade on complex reasoning over very long contexts well before the hard limit. Long-context benchmarks ("needle in a haystack") measure retrieval, not reasoning-over-everything.
- Cost and latency scale with context β every request re-processes the whole prompt (unless prefix-cached). Stuffing 100 log files into context when 5 matter is paying real money to reduce accuracy β the practical argument for retrieval and context curation even when everything technically fits.
- Agent-specific pressure: agent loops accumulate context β every tool result appends. Long-running agents need context management: truncating stale tool output, summarizing history, or resetting with distilled state.
05Sampling: temperature, top-p, and friends
The model outputs a probability distribution; sampling strategy decides how you pick from it.
- Temperature rescales the distribution before sampling. Tβ0: always take the argmax (greedy) β maximally deterministic-ish, best for extraction/classification/structured output. Tβ0.7β1: sample proportionally β diversity for writing and brainstorming. T>1: flatten toward uniform β incoherence risk. Intuition: temperature is how much probability mass you're willing to give to non-top choices.
- Top-p (nucleus): sample only from the smallest set of tokens whose cumulative probability β₯ p (e.g., 0.9). Adaptive cutoff: when the model is confident the nucleus is tiny; when uncertain, it's broad. Generally set temperature or top-p, not both aggressively.
- Top-k: fixed cutoff β only the k most likely tokens. Cruder than top-p.
06Why hallucination happens β mechanism, not apology
Four causes, each with the engineering response an interviewer actually wants to hear:
1 Β· Objective is plausibility, not truth
Training rewards text that looks like text that follows β a fluent, well-formatted, wrong citation scores well on next-token prediction. Hallucination lives where truth and plausibility diverge.
Engineering response Ground the model: put the true facts in context (RAG, tool results) so the task becomes reading comprehension instead of recall.
2 Β· Lossy compression
Billions of facts squeezed into weights as patterns. Well-represented facts reconstruct reliably; for rare/tail facts the model interpolates β generating what's typical of the shape of such facts (plausible paper titles, API methods that "should" exist).
Engineering response Give it tools to look things up rather than remember β search, docs, databases.
3 Β· No native "I don't know"
The decoding loop must emit some token; the distribution after "The author of X is" concentrates on name-shaped tokens, not abstention. RLHF layers some calibrated refusal on top, and benchmark incentives historically rewarded guessing.
Engineering response Give an explicit out in the prompt ("if the logs lack evidence, say so") and constrain output to verifiable forms.
4 Β· Error compounding
Autoregression means an early confabulated detail becomes context that conditions everything after β the model doubles down coherently.
Engineering response Verify downstream: schema validation, code execution, cross-checking β catch drift before it snowballs.
07Prompt engineering that actually matters
Skip the folk magic β these are the techniques with reliable effect, and why they work in terms of Β§1:
System prompts
A privileged instruction channel, weighted by training to dominate user turns. Use for: role/scope, hard constraints, output contract, tool-use policy. Treat it as versioned code β it is your app's behavior spec: review changes, eval before shipping. The instruction hierarchy (system > developer > user) is also the first line of prompt-injection defense β while noting honestly that it's probabilistic, not a security boundary.
Few-shot examples
2β5 inputβoutput demonstrations. Works via in-context learning: you're conditioning the distribution on a pattern to continue. The high-leverage detail: examples beat descriptions for format and edge-case behavior β show the tricky case (an ambiguous log line and its correct classification), because the model imitates examples more faithfully than it follows prose. Failure mode: examples that are all one class bias outputs toward that class.
Chain-of-thought
"Think step by step" / structured reasoning before the answer. Why it works: each generated token is extra serial computation, and intermediate results written into context become available to condition on β a scratchpad. Matters for math, multi-hop logic, tricky classification. Modern wrinkle: reasoning models (o-series, extended thinking) internalize this β you buy reasoning with a token budget instead of prompting for it, and pay in latency/cost, so route only hard tasks to them.
Structured output
For machine-consumed responses (everything in a pipeline like Sentinel): define the schema explicitly; prefer native structured-output / JSON modes or tool-calling with a schema over "please return JSON" β constrained decoding masks invalid tokens, guaranteeing syntax though not semantic correctness. Still validate with Pydantic and design a repair/retry path. And order the schema deliberately: ask for reasoning fields before conclusion fields β generation is left-to-right, so a "verdict" field generated first is decided before the "evidence" field is written.
Also load-bearing
- Put long documents before instructions β recency helps instruction-following.
- Use delimiters / XML tags to separate untrusted data from instructions.
- Tell the model what to do, not only what not to do.
- Give it an explicit out ("if the logs don't contain enough evidence, say so") β measurably reduces forced confabulation.
08Model landscape awareness & routing
What's expected: not leaderboard trivia, but a decision framework plus a rough map.
Frontier APIs vs open-weights
| Frontier API models | Open-weights | |
|---|---|---|
| Who | Anthropic's Claude family, OpenAI's GPT/o-series, Google's Gemini | Llama, Mistral, Qwen, DeepSeek, Gemma |
| Strengths | Best raw capability, tool-use reliability, long-context quality; zero infra burden | Control & customization: fine-tuning, self-hosting, data never leaves your VPC; no per-token vendor cost |
| Costs | Per-token pricing; data governance via contract (API-term promises, not physical control) | You own serving: GPUs, vLLM-style inference stacks, scaling |
| Honest framing | Open models have closed much of the gap on mid-tier tasks; frontier still leads on the hardest agentic/reasoning work β and the frontier moves, so evaluate on your task, don't inherit last year's conclusions. | |
The tiering pattern β the actually-useful knowledge
| Tier | Profile | Route these tasks to it |
|---|---|---|
| Reasoning modes/models | Above frontier in latency & cost | Genuinely hard problems only β gnarly root-cause analysis |
| Frontier | Highest quality, slowest, priciest | Hard agentic work, complex synthesis |
| Workhorse mid-tier | ~10Γ cheaper; best quality-per-dollar | Most production work β drafting, general tasks |
| Fast/cheap small | Another ~10Γ cheaper | Classification, routing, extraction, high-volume simple calls β "is this log line an incident?" |
The engineering move is routing: match each task to the cheapest tier that passes your evals β with evals as the referee and fallback across tiers/providers for resilience. Second-order factors that decide real selections: tool-calling reliability, structured-output support, context length, rate limits, latency SLOs, data-privacy terms β often more decisive than benchmark deltas.
09Rapid-fire interview Q&A
Q: Explain how an LLM works to a smart non-ML engineer.
Q: Why do LLMs hallucinate, and what do you do about it?
Q: When do you change temperature?
Q: Prompting vs fine-tuning vs RAG β how do you choose?
Q: What determines LLM latency?
10Self-test
Why does an early wrong token derail a whole answer?
Autoregression: every later token is conditioned on everything before it, so a confabulated detail becomes context the model coherently doubles down on. This is hallucination cause #4 (error compounding) β and why downstream verification matters more than hoping for perfect generation.
What are Q, K, and V in attention β one sentence each?
Query: "what am I looking for?" (emitted by the token being updated). Key: "what I'm about" (offered by every token, matched against queries). Value: "what I carry" (the information blended in, weighted by the queryΒ·key match). Attention = a soft, learned, content-based lookup over the whole context, in parallel.
What is the KV cache and why does it matter for serving?
Cached keys/values of already-processed tokens, so each new token only computes its own attention instead of reprocessing the whole context. It's what prefix caching reuses (same system prompt β skip re-prefill) and what limits concurrent batch sizes on a GPU β cache memory is often the serving bottleneck.
Does temperature 0 eliminate hallucination? Does it guarantee determinism?
No and no. Low temperature makes the model consistently confident β a wrong answer resamples the same way; it doesn't make the answer true. And in production APIs, batching non-determinism, floating point, and infra mean T=0 is not bit-exact reproducible.
Why put reasoning fields before the verdict field in a JSON schema?
Generation is left-to-right: a "verdict" generated first is decided before any "evidence" is written. Ordering reasoning first forces the intermediate computation into context, so the conclusion can condition on it β the schema-level version of chain-of-thought.
Name the "lost-in-the-middle" effect and its practical consequence.
Recall across a long context is not uniform β content buried mid-context is retrieved worse than content near the start or end. Consequence: placement of critical instructions/facts matters, and stuffing everything into a huge window can pay real money to reduce accuracy β curate context instead.