PrepStack › AI › LLM Fundamentals
LLM Fundamentals interview cheat sheet
Tokens, context, training, sampling, inference, APIs and cost
AI engineering interviews start with how LLMs actually work: next-token prediction, tokens, the context window, how models are trained and aligned, how sampling and inference work, and why models hallucinate. Then they move to practical questions: choosing a model, using the API (roles, streaming, tool calls, structured output, caching) and estimating cost and latency. Read the 15-minute revision first, run the small Python demos in your head, then switch to Quiz mode.
15-minute revision
- An LLM is a decoder-only transformer trained to predict the next token. Generation is a loop: predict a distribution, pick a token, append it, repeat.
- Models see tokens, not characters or words. English averages about 4 characters or 0.75 words per token. Billing, limits and latency are all counted in tokens.
- The context window holds input + output tokens together. Attention cost grows with length, and facts in the middle of long prompts are recalled worst.
- Training stages: pre-training (next-token on trillions of tokens) → SFT (instruction following) → preference tuning (RLHF, RLAIF, DPO) → often RL on verifiable tasks for reasoning.
- Chinchilla: for a fixed compute budget, scale parameters and tokens together, roughly 20 tokens per parameter. Training compute is about 6 × params × tokens FLOPs.
- Inference has two phases: prefill (process the prompt in parallel, compute-bound, sets time-to-first-token) and decode (one token at a time, memory-bandwidth-bound).
- The KV cache stores past keys and values so each new token does not recompute the prompt. It grows linearly with sequence length × batch and often limits concurrency.
- Sampling: greedy picks the argmax; temperature sharpens (<1) or flattens (>1) the distribution; top-k keeps k tokens; top-p keeps the smallest set whose mass ≥ p.
- Speed-ups: continuous batching, speculative decoding (draft model proposes, big model verifies), quantization (int8/int4 weights), FlashAttention, GQA, prompt caching.
- Embedding models turn text into a vector for search and similarity. Generation models produce text. They are different models with different APIs.
- Reasoning models spend extra test-time compute (hidden thinking tokens) before answering. Better on math, code and planning; slower and more expensive.
- Hallucination = fluent but unsupported output. Causes: the training objective rewards plausible text, knowledge gaps and cut-offs. Mitigate with grounding (RAG), tools, citations, constrained output and evals.
- API roles: system/developer (rules), user (input), assistant (model output), plus tool results. The model is stateless; you resend history each call (or use a stored-state feature).
- Structured outputs constrain the reply to a JSON Schema. Function calling lets the model ask your code to run a tool. Your code executes it, not the model.
- Cost ≈ input tokens × input price + output tokens × output price. Output tokens are usually several times pricier. Prompt caching and the batch API cut cost a lot.
- Open-weight ≠ open source. Check the licence (Apache 2.0, MIT or a custom community licence), hosting cost and data control versus a closed API's quality and convenience.
Foundations
What an LLM is: next-token prediction
A large neural network (a decoder-only transformer) that predicts a probability for every possible next token, used in a loop to generate text.
- Training objective: given tokens 1..n, predict token n+1. This is self-supervised: the labels come from the text itself, so no human labelling is needed for pre-training.
- Autoregressive generation: predict a distribution, pick a token, append it to the input, repeat until a stop token or
max_tokens. - Architecture: a stack of transformer decoder blocks. Each block has causal (masked) self-attention, so a token can only look at earlier tokens, followed by a feed-forward network (MLP).
- Parameters (weights) store what the model learned. Tokens are the units of text it reads and writes. A “70B model” has 70 billion parameters; it might have been trained on 15 trillion tokens.
- The model outputs logits (one score per vocabulary entry). Softmax turns them into probabilities; a sampling strategy picks the token.
- Capabilities like translation, coding and summarising emerge from next-token prediction at scale plus post-training. There is no separate module for each skill.
Interview questions
- What is a large language model?
- Why decoder-only instead of encoder-decoder?
- What is self-attention, in one minute?
- What is a Mixture-of-Experts model?
Tokens & tokenisers
Text is split into sub-word tokens by a tokeniser such as BPE. Token counts drive cost, limits, latency and some odd failures.
- A tokeniser maps text to integer ids from a fixed vocabulary (often 32k–200k entries). Each model family has its own tokeniser, so counts differ between models.
- Byte-Pair Encoding (BPE) starts from bytes or characters and repeatedly merges the most frequent adjacent pair. Common words become one token; rare words split into pieces. SentencePiece and WordPiece are related schemes.
- Rule of thumb for English: ~4 characters ≈ 1 token ≈ 0.75 words. Code, numbers, non-English languages and emojis usually need more tokens per character.
- Why counts matter: the context limit, the price (per million tokens), the latency (each output token is one decode step) and rate limits are all measured in tokens.
- Tokenisation explains classic failures: counting letters in a word, reversing strings and some arithmetic are hard because the model never sees individual characters.
- Special tokens mark structure: begin/end of sequence and role markers in the chat template. Never let user input inject them.
Interview questions
- What is a token and why not just use words or characters?
- How does BPE work?
- Why can an LLM fail to count the r's in “strawberry”?
- Why do token counts matter in production?
Context window & long context
The context window is the maximum tokens (prompt + output) per call. Bigger windows help, but cost, latency and recall in the middle get worse.
- The window counts input and output together. If the prompt is 120k of a 128k window, you have at most ~8k for the answer (and
max_tokensmay be capped lower). - The model has no memory between calls. Chat “memory” is the app resending earlier messages, summarising them or retrieving them.
- Long context is expensive: attention compute grows roughly quadratically with length in prefill, and the KV cache grows linearly, so time-to-first-token and memory rise.
- Lost in the middle: models recall facts at the start and end of a long prompt better than facts buried in the middle. Put key instructions and the question at the edges.
- Strategies when content does not fit: truncate oldest turns, summarise history, retrieve only relevant chunks (RAG), or map-reduce over chunks.
- Long-context vs RAG: long context is simpler and good for one big document; RAG is cheaper, scales to millions of documents and gives citations.
Interview questions
- What is the context window?
- What is the “lost in the middle” problem?
- Long-context model or RAG?
- How does a chatbot “remember” earlier messages?
Embeddings, generation & multimodal models
Embedding models map text to vectors for search; generation models write text; multimodal models take (and sometimes produce) images, audio or video too.
- An embedding is a fixed-length vector (for example 768–3072 numbers) where similar meanings are close. Compare with cosine similarity or dot product.
- Embedding models are usually encoder-style and output one vector per input. They power semantic search, RAG retrieval, clustering, deduplication and recommendations.
- Generation models output tokens. Their internal hidden states are vectors too, but you call a separate embeddings endpoint for retrieval.
- Embeddings from different models live in different spaces. Changing the embedding model means re-embedding the whole corpus.
- Multimodal models accept images, audio, PDFs or video as input (and some output images or speech). Images are converted to patch tokens by a vision encoder, so they also consume context and cost.
- Other specialised models: rerankers (cross-encoders that score query+document pairs), speech-to-text, text-to-speech, image generation (diffusion).
Interview questions
- Difference between an embedding model and a generative LLM?
- How do multimodal LLMs handle images?
- What is a reranker and when do you need one?
Training
Training stages: pre-training → SFT → preference tuning
Pre-training builds knowledge from raw text, SFT teaches the assistant format, preference tuning shapes helpfulness and safety, and RL can add reasoning.
- Pre-training: next-token prediction on trillions of tokens (web, books, code, papers). Costs most of the compute. Produces a base model that continues text but does not reliably follow instructions.
- Supervised fine-tuning (SFT) / instruction tuning: train on curated prompt→ideal-response pairs and chat transcripts. Teaches format, roles and following instructions.
- Preference tuning: learn from comparisons (“A is better than B”). Methods: RLHF (reward model + PPO), RLAIF (AI feedback guided by a written constitution), DPO (direct optimisation on preference pairs, no separate reward model).
- Reasoning RL: reinforcement learning on tasks with verifiable answers (math, code with tests) teaches models to produce long chains of thought that end in correct answers.
- Extra stages: mid-training/continued pre-training on domain or long-context data, distillation (a small model learns from a big one), safety training and red-teaming.
- Your own options as a user: prompt engineering → RAG → fine-tuning (SFT or LoRA on your data) → preference tuning. Go right only when the left fails.
Interview questions
- What is the difference between a base model and an instruct/chat model?
- What is instruction tuning?
- When would you fine-tune instead of prompting or using RAG?
- What is knowledge distillation?
Alignment: RLHF, RLAIF, DPO & reasoning RL
Preference tuning pushes the model toward answers people prefer; RLHF uses a reward model and RL, DPO skips both and trains directly on preference pairs.
- RLHF (InstructGPT recipe): 1) SFT model, 2) humans rank several answers, 3) train a reward model on those rankings, 4) optimise the policy with PPO to maximise reward with a KL penalty that keeps it close to the SFT model.
- The KL penalty prevents reward hacking: without it the policy finds weird outputs that fool the reward model (overly long, flattering or repetitive answers).
- RLAIF / Constitutional AI: an AI model, guided by a written set of principles, produces the preference labels. Cheaper and more consistent than all-human labelling.
- DPO (Direct Preference Optimization) rewrites the RLHF objective as a simple classification-style loss on (prompt, chosen, rejected). No reward model, no sampling loop, more stable. Variants include IPO, KTO and ORPO.
- Reasoning RL uses verifiable rewards (is the math answer right, do the tests pass) with methods like GRPO. Models learn to think longer, check work and backtrack.
- Side effects of alignment: sycophancy (agreeing with the user), over-refusal, and verbosity. Good evals measure these too.
Interview questions
- Explain RLHF step by step.
- What is DPO and why did it become popular?
- What is reward hacking?
- How are reasoning models trained differently?
Scaling laws, parameters vs tokens
Loss falls predictably as compute, parameters and data grow; Chinchilla showed many models were under-trained and suggested ~20 tokens per parameter.
- Scaling laws (Kaplan et al., 2020): test loss follows a smooth power law in parameters, data and compute. You can predict a big model's loss from small runs.
- Chinchilla (Hoffmann et al., 2022): for a fixed compute budget, scale parameters and tokens equally. Compute-optimal is about 20 training tokens per parameter. A 70B model trained on 1.4T tokens beat much larger under-trained models.
- Training compute ≈ 6 × N × D FLOPs (N = parameters, D = training tokens). Inference ≈ 2 × N FLOPs per generated token.
- Chinchilla optimises training cost only. Because inference cost scales with N, labs now over-train small models far beyond 20 tokens/param (trillions of tokens for 8B models) to get cheaper serving.
- Newer axes: data quality (filtering, synthetic data), test-time compute (reasoning) and post-training scale. Pure pre-training scaling shows diminishing returns relative to these.
- Parameters drive memory: fp16/bf16 uses 2 bytes per parameter, int8 1 byte, int4 0.5 bytes (plus KV cache and activations).
Interview questions
- What did the Chinchilla paper show?
- Why train an 8B model on 15T tokens if Chinchilla says ~160B is optimal?
- Parameters vs tokens: what is the difference?
- How much GPU memory does a 70B model need?
Inference & sampling
Decoding & sampling: greedy, temperature, top-k, top-p, beam
Sampling settings decide how a token is picked from the predicted distribution: deterministic and safe, or varied and creative.
- Greedy: always pick the highest-probability token. Deterministic but can be repetitive and miss better overall sequences.
- Temperature divides logits before softmax. T < 1 sharpens (more focused), T > 1 flattens (more random), T → 0 is greedy.
- Top-k: keep only the k most likely tokens, renormalise, sample. Top-p (nucleus): keep the smallest set whose cumulative probability ≥ p; adapts to how confident the model is.
- Beam search: keep the best
bpartial sequences by total log-probability. Good for translation and short exact outputs; rarely used for chat because it is bland and slow. - Repetition / frequency / presence penalties lower the scores of tokens already used, to reduce loops. Stop sequences and
max_tokensend generation. - Seed plus temperature 0 improves repeatability, but provider APIs do not fully guarantee determinism (batching and floating-point order can change results).
Interview questions
- What does temperature do?
- Difference between top-k and top-p?
- Why isn't beam search used for chatbots?
- How do you reduce repetitive loops in output?
Inference: prefill vs decode, TTFT & throughput
Prefill processes the whole prompt in parallel and sets time-to-first-token; decode produces one token per step and sets tokens-per-second.
- Prefill: all prompt tokens go through the model in one parallel pass, filling the KV cache. It is compute-bound (big matrix multiplies) and sets time to first token (TTFT).
- Decode: each step generates one token per sequence and reads all weights plus the KV cache from memory. It is memory-bandwidth-bound and sets inter-token latency.
- Total latency ≈ TTFT + output_tokens × time_per_output_token. Output length usually dominates, so asking for shorter answers is the easiest speed-up.
- Throughput (tokens/s across all users) and latency (per user) trade off: bigger batches raise throughput but each user waits longer per token.
- Serving engines like vLLM, TensorRT-LLM, SGLang and llama.cpp implement continuous batching, paged KV cache and quantization.
- Streaming does not make generation faster, but it makes perceived latency much lower because users read while tokens arrive.
Interview questions
- Why is decoding slower per token than prefill?
- What are TTFT and TPOT?
- A chat feature feels slow. How do you diagnose it?
KV cache & attention memory
The KV cache stores each layer's keys and values for past tokens so decode only computes the new token; its size often limits context length and batch size.
- Without a cache, generating token n would recompute attention inputs for all n−1 previous tokens: O(n²) work for a full answer. With it, each step only computes K/V for one new token.
- Size = 2 (K and V) × layers × KV heads × head_dim × sequence length × batch × bytes per value.
- GQA (grouped-query attention) shares each K/V head across several query heads, cutting the cache by 4–8×. MQA shares one K/V head across all. Most modern open models use GQA.
- PagedAttention (vLLM) stores the cache in fixed-size blocks like OS virtual memory, so little memory is wasted and sequences with a shared prefix can share blocks.
- Prompt caching at the provider level keeps the KV cache of a common prefix (system prompt, tools, documents) so the next request skips that prefill. That is why it cuts both latency and price.
- Other tricks: KV cache quantization (fp8/int8), sliding-window attention, and evicting less important tokens.
Interview questions
- What is the KV cache and why does it matter?
- How does grouped-query attention help?
- How does provider prompt caching relate to the KV cache?
Serving speed-ups: batching, speculative decoding, quantization
Most inference optimisations either keep the GPU busier (batching), do fewer slow steps (speculative decoding) or move fewer bytes (quantization, GQA, FlashAttention).
- Continuous (in-flight) batching: requests join and leave the batch at every decode step instead of waiting for the whole batch to finish. Large throughput gains over static batching.
- Speculative decoding: a small draft model (or extra heads like Medusa/EAGLE) proposes several tokens; the big model verifies them in one parallel pass and accepts the longest matching prefix. Output distribution is unchanged; speed-up depends on the acceptance rate.
- Quantization: store weights in int8/fp8 or int4 (GPTQ, AWQ, GGUF formats) instead of bf16. Less memory and bandwidth, so faster decode; small quality loss, larger at 4-bit and below.
- FlashAttention: computes attention in tiles inside fast on-chip memory, never writing the full attention matrix. Same result, much less memory traffic.
- Parallelism for big models: tensor parallel (split each layer across GPUs), pipeline parallel (split layers), expert parallel for MoE.
- Product-level speed-ups: smaller model, shorter prompts and outputs, prompt caching, streaming, and routing easy requests to cheap models.
Interview questions
- How does speculative decoding work and why is it lossless?
- What is quantization and what are the trade-offs?
- What is continuous batching?
- You must serve a 70B model at low cost. What do you try?
Capabilities, limits & safety
Reasoning models & test-time compute
Reasoning models think in hidden tokens before answering, trading latency and cost for accuracy on hard multi-step problems.
- Test-time compute: spend more computation at inference instead of (or in addition to) a bigger model. Forms: long chain of thought, self-consistency (sample many, vote), search over candidates, verifiers.
- Reasoning models are trained with RL on verifiable tasks to produce long internal reasoning, check work and backtrack, then give a final answer.
- APIs expose a reasoning effort or thinking budget setting. Reasoning tokens are billed as output tokens and use the context window even when they are hidden or summarised.
- They shine on math, competitive coding, complex debugging, planning and agentic tool use. For simple lookups, chat or extraction they mostly add latency and cost.
- Prompting changes: give the goal, constraints and success criteria; skip step-by-step micro-instructions and “think step by step”, which the model already does.
- Open reasoning models (for example DeepSeek-R1) showed that RL with simple verifiable rewards can produce strong reasoning behaviour.
Interview questions
- What is test-time compute scaling?
- When would you not use a reasoning model?
- Are reasoning tokens free if I cannot see them?
- Chain-of-thought prompting vs reasoning models?
Hallucinations & grounding
LLMs produce plausible text, not verified facts; grounding answers in retrieved sources and tools is the main mitigation.
- Hallucination: output that is fluent and confident but false or not supported by the given sources (made-up citations, APIs, numbers, quotes).
- Causes: the objective rewards plausible continuations, not truth; gaps and errors in training data; knowledge cut-off; ambiguous prompts; long or noisy context; and evaluation that rewards guessing over saying “I don't know”.
- Grounding means tying the answer to trusted context: RAG over your documents, web search, database or API tools, and asking the model to answer only from the provided sources and cite them.
- Other mitigations: lower temperature for factual tasks, structured outputs, allowing an explicit “not found” answer, self-checks or a second verifier model, and human review for high-stakes use.
- Measure it: groundedness/faithfulness evals (is each claim supported by the context?), citation accuracy, and golden Q&A sets.
- Two types: intrinsic (contradicts the given context) and extrinsic (adds claims not in the context that may or may not be true).
Interview questions
- Why do LLMs hallucinate?
- How would you reduce hallucinations in a customer-support bot?
- What does “grounding” mean?
- Does temperature 0 stop hallucinations?
Safety, alignment basics & limitations
Models are aligned to be helpful and harmless, but they can still be manipulated, biased, wrong or out of date, so apps need their own guardrails.
- Prompt injection: instructions hidden in user input or retrieved content (web pages, emails, PDFs) try to override your system prompt. Jailbreaks try to bypass safety training.
- Defences: treat all model input and output as untrusted, least-privilege tools, human confirmation for risky actions, input/output filters or classifier guardrails, and separating data from instructions.
- Other risks: data leakage (secrets or PII in prompts, logs or outputs), bias, toxic output, over-reliance, and copyright concerns.
- Core limitations: knowledge cut-off, no real-time data without tools, weak exact arithmetic and character-level tasks, non-determinism, context limits, sycophancy and sensitivity to prompt wording.
- Governance: evaluate before shipping, red-team, log and monitor, keep a human in the loop for high-impact decisions, and follow regulations such as the EU AI Act where they apply.
- OWASP publishes a Top 10 for LLM applications (prompt injection, sensitive information disclosure, excessive agency, and so on), a good checklist to mention.
Interview questions
- What is prompt injection and how do you defend against it?
- Difference between prompt injection and jailbreaking?
- What are the main limitations of LLMs?
- What does alignment mean in practice?
Using models in production
Model families, open vs closed & licensing
Closed frontier models come through APIs; open-weight models can be self-hosted, but their licences and hosting costs vary a lot.
- Closed (API-only): OpenAI GPT models, Anthropic Claude, Google Gemini. Usually top quality, managed scaling and features, but data leaves your network and you depend on the vendor's pricing and deprecations.
- Open-weight: Meta Llama, Mistral, DeepSeek, Alibaba Qwen, Google Gemma, OpenAI gpt-oss and others. You can run them on your own hardware, fine-tune them and keep data in-house.
- Open weights ≠ open source: usually the training data and full recipe are not released. The OSI's Open Source AI Definition is stricter than most model releases.
- Licences differ: some use permissive Apache 2.0 or MIT (many Mistral, Qwen and DeepSeek releases, gpt-oss); Llama uses a custom community licence with usage and attribution conditions. Always read the licence of the exact version.
- Vendors ship tiers: a large flagship, a mid model and a small fast/cheap one (for example Claude Opus/Sonnet/Haiku, or Gemini Pro/Flash). Model ids and versions change often; pin a version in production.
- Self-hosting is not automatically cheaper: count GPUs, utilisation, ops staff and evals. APIs are usually cheaper at low or spiky volume.
Interview questions
- Open-weight vs closed models: how do you choose?
- Is Llama open source?
- Why pin model versions?
Choosing a model: quality, latency, cost
Start with the strongest model to prove the task works, build evals, then move to the cheapest model that still passes them.
- Decide by evals on your data, not public benchmarks. Build a small golden set (50–200 cases) with clear pass criteria early.
- Key dimensions: quality, latency (TTFT, tokens/s), cost per task, context window, modalities, tool-calling and structured-output reliability, rate limits, data residency and compliance.
- Common path: prototype on a frontier model → measure → try smaller/cheaper models, prompt changes or fine-tuning → keep the cheapest that passes.
- Routing / cascades: send easy requests to a small model and escalate hard or low-confidence ones to a large or reasoning model.
- Cost per task matters more than price per token: a cheaper model that needs retries or longer prompts can cost more overall.
- Plan for fallbacks: a second provider or model if the first is down or rate-limited.
Interview questions
- How would you choose an LLM for a new feature?
- What is model routing?
- Your LLM bill doubled. What do you check?
API basics: roles, messages & streaming
You send a list of role-tagged messages plus settings; the model returns content and token usage; streaming sends tokens as they are generated.
- Roles:
system/developer(or Anthropic's top-levelsystemparameter) for rules and persona;userfor requests;assistantfor model replies; tool calls and tool results as their own items. - The API is stateless by default: send the relevant history each time. Some APIs can store conversation state server-side (for example OpenAI's
previous_response_id). - Common parameters:
model,max_tokens/max_output_tokens,temperature,top_p, stop sequences, tools, response format. - Responses include usage (input, output, cached and reasoning tokens) and a stop reason (finished, hit max tokens, tool call, refusal). Always check it.
- Streaming uses server-sent events (SSE): you receive text deltas as they are produced. It lowers perceived latency but you must handle partial output and errors mid-stream.
- OpenAI's current primary API is Responses (
client.responses.create); Chat Completions is still supported. Anthropic uses the Messages API (client.messages.create), which requiresmax_tokens.
Interview questions
- What are the system, user and assistant roles?
- Why stream responses?
- The LLM API is stateless. What does that imply?
Function calling & structured outputs
Function calling lets the model request a tool with JSON arguments that your code runs; structured outputs force the reply to match a JSON Schema.
- You describe tools with a name, description and JSON Schema for parameters. The model replies with a tool call (name + arguments) instead of text when it decides a tool is needed.
- Your code executes the tool, then sends the result back (OpenAI: a
function_call_outputitem with thecall_id; Anthropic: atool_resultblock with thetool_use_id). The model then answers or calls more tools. That loop is the basis of agents. - Structured outputs (strict JSON Schema mode) guarantee schema-valid JSON for completed, non-refused responses. Plain “JSON mode” only guarantees valid JSON, not your schema.
- Good tool design: few, clearly named tools, precise descriptions, enums for fixed choices, required fields, and helpful error messages returned as tool results.
- Validate arguments before executing; models can choose the wrong tool or pass bad values. Require confirmation for actions with side effects.
- MCP (Model Context Protocol) is an open standard for exposing tools and data to LLM apps in a reusable way.
Interview questions
- How does function calling work end to end?
- JSON mode vs structured outputs?
- How do you make tool calling reliable?
- How does constrained decoding guarantee a schema?
Cost & latency: estimation, prompt caching, batch API
Estimate cost from input and output tokens times their prices; cut it with shorter prompts and outputs, prompt caching, batching and smaller models.
- Cost per request = input tokens × input price + output tokens × output price (+ reasoning tokens as output). Prices are quoted per million tokens; output is typically several times pricier than input.
- Latency ≈ TTFT + output tokens ÷ tokens per second. Output length is usually the biggest lever.
- Prompt caching: a repeated exact prefix (system prompt, tool definitions, long documents) is served from cache at a large discount and lower TTFT. OpenAI caches long prefixes automatically; Anthropic uses
cache_control(automatic at the top level or explicit breakpoints) with a short default TTL (5 minutes, 1 hour optional). - Batch APIs (OpenAI Batch, Anthropic Message Batches) process many requests asynchronously, typically within 24 hours, at about 50% off. Ideal for evals, backfills, classification and embeddings jobs.
- Other levers: smaller or distilled models, routing, fewer RAG chunks, summarised history, concise output instructions,
max_tokenscaps, and caching whole responses for repeated questions. - Watch rate limits (requests and tokens per minute) as part of capacity planning.
Interview questions
- How do you estimate the cost of an LLM feature?
- What is prompt caching and how do you maximise hits?
- When would you use the batch API?
- Why are output tokens more expensive than input tokens?