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.
The golden rule: input tokens are cheap-ish, output tokens are slow and expensive. Constraining output length is often your best latency lever β€” cap it, streamline it, and stream tokens to the user to cut perceived latency.

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

  1. 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.
  2. Parallelism over the sequence is what made training on internet-scale data feasible β€” the transformer won on trainability, not just capability.
  3. During generation, per-token attention results are cached so each new token only computes its own attention β€” see below.
The KV cache β€” during generation, each token's keys and values are cached so every new token computes only its own query against the stored past, instead of recomputing attention for the whole context. The KV cache is the central object of inference serving: it's what prefix caching reuses (same system prompt β†’ skip re-prefill) and what limits concurrent batch sizes on a GPU β€” cache memory, not compute, is often the bottleneck. (Connects to LLM ops β†’ file 04.)

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.
The line to say: context is a budget you engineer, not a bucket you fill.

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.

πŸŽ› Sampling Playground

Toy next-token distribution after "The capital of France is". Temperature reshapes the bars (softmax over logits Γ· T); top-p draws a cutoff and greys out excluded tokens. Hit Sample repeatedly β€” feel the determinism at T=0.1 vs the chaos at T=2.

Output strip: The capital of France is…

Practitioner notes that mark you as one: temperature 0 β‰  bit-exact determinism in production APIs (batching non-determinism, floating point, infra) β€” never build correctness on exact-reproducibility assumptions. Low temperature does not reduce hallucination β€” it just makes the model consistently confident; a confident wrong answer resamples the same. For judgment/eval calls, use low temperature for stability.

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.

The system-level answer: design workflows where hallucination is caught, not prevented. That is exactly what Sentinel's adversarial-reviewer + human-gate architecture is: an admission that generation can't be trusted raw, so trust is produced by checking.

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.
The meta-skill: prompt changes are behavior changes β€” they need regression evals, not vibes. "I treat prompts like code: versioned, reviewed, and eval-gated" is a top-tier interview line because most teams don't.

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 modelsOpen-weights
WhoAnthropic's Claude family, OpenAI's GPT/o-series, Google's GeminiLlama, Mistral, Qwen, DeepSeek, Gemma
StrengthsBest raw capability, tool-use reliability, long-context quality; zero infra burdenControl & customization: fine-tuning, self-hosting, data never leaves your VPC; no per-token vendor cost
CostsPer-token pricing; data governance via contract (API-term promises, not physical control)You own serving: GPUs, vLLM-style inference stacks, scaling
Honest framingOpen 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

TierProfileRoute these tasks to it
Reasoning modes/modelsAbove frontier in latency & costGenuinely hard problems only β€” gnarly root-cause analysis
FrontierHighest quality, slowest, priciestHard agentic work, complex synthesis
Workhorse mid-tier~10Γ— cheaper; best quality-per-dollarMost production work β€” drafting, general tasks
Fast/cheap smallAnother ~10Γ— cheaperClassification, 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.

It's a next-token predictor: trained on huge text corpora to output a probability distribution over what comes next, then run in a loop β€” sample a token, append, repeat. The transformer architecture lets every token attend to every other token in the context, which is how it uses long-range structure. All "knowledge" is compressed into the weights; all working memory is the context window.

Q: Why do LLMs hallucinate, and what do you do about it?

The training objective rewards plausible text, not true text; tail knowledge is lossily compressed; and decoding must always emit something β€” there's no built-in abstention. I engineer around it: ground facts in context via retrieval/tools so the task becomes comprehension not recall, constrain and validate outputs, allow the model an explicit "insufficient evidence" path, and put verification downstream β€” in Sentinel that's an adversarial review pass plus a human approval gate.

Q: When do you change temperature?

Near 0 for anything a machine consumes or that must be consistent β€” classification, extraction, structured output, judge calls. Moderate for generative/creative output. And I know temperature 0 isn't perfectly deterministic in served APIs, so I never depend on exact reproducibility.

Q: Prompting vs fine-tuning vs RAG β€” how do you choose?

Prompting first β€” cheapest iteration loop, and few-shot + good instructions solve most behavior problems. RAG when the model needs knowledge it doesn't have (private, fresh, or vast). Fine-tuning when I need consistent behavior/style/format at scale or to make a small model punch above its class β€” not for injecting facts. They compose; the eval suite arbitrates.

Q: What determines LLM latency?

Prefill (prompt processing, parallel) + decode (output generation, serial per token) β€” output length usually dominates. Levers: cap/streamline output, stream tokens to cut perceived latency, prefix-cache the static prompt, pick a smaller/faster tier, and cut context bloat.

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.