Home / Question bank

Question bank

84 AI interview questions. Each has a 30-second answer and a full walkthrough paced for a 40-minute interview round. Answer out loud first, then compare.

What is a token, and why do LLMs use subword tokenization instead of words or characters? Transformer ArchitectureJunior

30-second answer

A token is an integer ID from a fixed vocabulary, learned before pre-training. Word vocabularies explode in size and can't represent unseen words; characters make sequences 4–5× longer, which is expensive for attention and decoding. Subword schemes like byte-level BPE give frequent strings single tokens and compose rare ones from pieces, with byte fallback so any input is representable. Vocabulary size trades sequence length against embedding and softmax cost, and tokenization explains several model quirks: spelling, arithmetic and uneven cost across languages.

Full 40-minute answer →
Explain scaled dot-product attention, implement it, and justify dividing by √d_k. Transformer ArchitectureMid

30-second answer

Project inputs to queries, keys and values; scores are QKᵀ/√d_k; apply the causal mask with −∞; softmax each row; multiply by V. Each output is a convex combination of value vectors weighted by query–key similarity. With unit-variance components, q·k has variance d_k, so unscaled scores grow with dimension, softmax saturates to near one-hot, and its gradient vanishes; dividing by √d_k restores unit variance. Multi-head attention runs this in parallel subspaces and projects the concatenation with W_O.

Full 40-minute answer →
Compare MHA, MQA, GQA and MLA. What problem do they solve? Transformer ArchitectureSenior

30-second answer

They differ in how keys and values are shared. MHA gives every head its own K and V; MQA shares one K/V across all heads; GQA shares K/V within groups; MLA caches a compressed latent and expands per-head K/V on the fly. The goal is a smaller KV cache: decode is memory-bandwidth-bound and the cache limits batch size and context length. GQA with 4–8 groups keeps nearly MHA quality with several-fold less cache; MQA saves the most but loses quality; MLA trades extra compute for even less memory.

Full 40-minute answer →
Why is attention O(n²), how does FlashAttention help, and how do models handle long context? Transformer ArchitectureSenior

30-second answer

Scores between all pairs make compute and naive memory quadratic in sequence length; per token the attention FLOPs (4·T·d per layer) only exceed the parameter matmuls (~24d²) beyond T ≈ 6d. FlashAttention is exact: it tiles Q, K, V into on-chip memory and uses an online softmax with running max and normalizer, so the T×T matrix is never written to HBM; memory becomes linear and it runs much faster, though FLOPs stay quadratic. Long context also needs positional extrapolation (RoPE scaling such as NTK or YaRN plus long-sequence fine-tuning), cheaper attention patterns (sliding window, hybrids), and system choices such as retrieval or compression, because effective use of long context degrades with distractors.

Full 40-minute answer →
How do rotary position embeddings (RoPE) work, and how do you extend a model's context length with them? Transformer ArchitectureSenior

30-second answer

RoPE rotates each pair of query and key dimensions by an angle proportional to position, with geometrically spaced frequencies θ_i = base^(−2i/d). Because rotations compose, the dot product between a query at m and a key at n depends only on n − m, giving relative position information while still applying per position, which suits KV caching. Extending context changes angles beyond those seen in training; fixes include position interpolation (rescale positions), NTK-aware scaling (raise the base), YaRN (per-frequency interpolation plus temperature), usually with a short long-context fine-tune.

Full 40-minute answer →
Why do modern LLMs use pre-norm and RMSNorm? What are the trade-offs? Transformer ArchitectureMid

30-second answer

Pre-norm (x + f(Norm(x))) keeps an identity residual path from input to output, so gradients flow directly and deep stacks train stably with little warmup; post-norm normalizes after each residual add and is prone to divergence at depth. The cost is that the residual stream grows with depth, so later layers contribute relatively less; scaled initialization and a final norm help. RMSNorm drops LayerNorm's mean-centering and bias (x / RMS(x) · γ), which is cheaper and empirically as good. QK-norm is often added to stop attention logits from growing and causing loss spikes.

Full 40-minute answer →
Estimate the parameters, training FLOPs and training time for a 7B-parameter transformer. Transformer ArchitectureMid

30-second answer

Each dense layer has about 12d² parameters (4d² attention, 8d² MLP), so N ≈ 12·L·d² plus V·d per embedding matrix; with d = 4,096, L = 32, V = 32k that's ≈ 6.7B. Training costs ≈ 6N FLOPs per token (2N forward, 4N backward), so 2T tokens need ≈ 8.4e22 FLOPs. On 1,024 GPUs at ~1e15 peak FLOP/s and 40% MFU that's ≈ 2.4 days. Inference weights are 2 bytes per parameter in bf16, and the KV cache is 2·L·n_kv·d_head·bytes per token.

Full 40-minute answer →
How does a Mixture-of-Experts transformer work, and what are its training and serving challenges? Transformer ArchitectureSenior

30-second answer

MoE replaces the dense MLP with many expert MLPs and a learned router that sends each token to its top-k experts, so total parameters grow while per-token compute tracks only the active experts. Training needs load balancing (auxiliary losses or bias adjustment) to avoid router collapse, capacity limits that may drop tokens, and router stabilization such as z-loss. Serving must keep all experts in memory, uses expert parallelism with all-to-all communication, and needs large batches to keep experts busy; it pays off at high throughput, less so for small latency-sensitive deployments.

Full 40-minute answer →
Why did transformers replace RNNs and LSTMs for language modelling? Transformer ArchitectureJunior

30-second answer

RNNs process tokens sequentially, so training can't parallelize across the sequence, and information between distant tokens must pass through many recurrent steps, which makes long-range dependencies hard to learn despite gating. Transformers compute all positions in parallel during training, give every pair of positions a direct one-step path through attention, and scale predictably with data and compute on GPUs. The cost is quadratic attention in sequence length and a KV cache that grows during generation, which is why state-space and linear-attention models are being revisited, often in hybrids.

Full 40-minute answer →
Derive the language-modelling loss. How do cross-entropy, perplexity and bits per byte relate? Pre-training & OptimizationMid

30-second answer

By the chain rule the model's sequence probability is the product of next-token probabilities; maximum likelihood minimizes the mean negative log-probability of each true next token, which is the cross-entropy between data and model. Per position the loss is −z_y + log Σ e^{z_j}, with gradient softmax(z) − onehot(y). Cross-entropy equals the data entropy plus KL(data‖model), so only the KL can be reduced. Perplexity is exp of the mean per-token loss but depends on the tokenizer; bits per byte divides total loss in bits by the number of bytes, allowing comparison across tokenizers.

Full 40-minute answer →
Explain Adam and AdamW. Why does decoupled weight decay matter, and what does Adam cost in memory? Pre-training & OptimizationMid

30-second answer

Adam tracks moving averages of the gradient (m) and squared gradient (v), bias-corrects them, and updates θ by η·m̂/(√v̂ + ε), giving momentum plus per-parameter step sizes. Adding L2 regularization to the gradient means the decay gets divided by √v̂, so parameters with large gradient history are decayed less; AdamW applies decay directly to the weights (θ −= ηλθ), making it uniform. LLM settings are typically β2 = 0.95, weight decay ≈ 0.1, clipping at 1.0. Adam's two fp32 moments add 8 bytes per parameter, a major part of the ~16 bytes/param training footprint.

Full 40-minute answer →
Why do LLMs use learning-rate warmup, and how do cosine and warmup–stable–decay schedules compare? Pre-training & OptimizationMid

30-second answer

Early in training, Adam's second-moment estimates rest on few samples and activations haven't settled, so full-size steps can be destructive; a linear warmup over the first ~1–2k steps keeps updates small until statistics are reliable (post-norm models need much more). Cosine decay to ~10% of peak must be sized to the run length. Warmup–stable–decay holds the peak rate for most of training then decays quickly at the end; it matches cosine quality while letting you branch decays from any checkpoint, extend training and run scaling studies cheaply.

Full 40-minute answer →
What do scaling laws say about how to allocate a compute budget between model size and data? Pre-training & OptimizationSenior

30-second answer

Loss follows L(N, D) = E + A/N^α + B/D^β, and training compute is C ≈ 6ND. Minimizing L subject to the budget gives N_opt ∝ C^{β/(α+β)} and D_opt ∝ C^{α/(α+β)}; with α ≈ β both grow as about √C, roughly 20 tokens per parameter (Chinchilla: 70B on 1.4T tokens beat a 280B model at similar compute). At 1e24 FLOPs that's ~90B parameters on ~1.8T tokens. Earlier work favoured bigger models largely because schedules weren't matched to run length. Compute-optimal isn't inference-optimal: widely served models are deliberately trained far longer than 20 tokens per parameter.

Full 40-minute answer →
Your large pre-training run has loss spikes. How do you diagnose and fix them? Pre-training & OptimizationSenior

30-second answer

First check what moved before the spike: gradient norm and clip rate, update-to-weight ratios, max attention logits, output logit magnitudes, activation norms and per-domain losses. Rewind to a checkpoint a few hundred steps earlier and skip the surrounding batches; if it doesn't recur, the data was the trigger. Otherwise lower the peak learning rate or lengthen warmup, add QK-norm for attention logit growth and z-loss for output logits, use β2 = 0.95 and sane ε, keep softmax and reductions in fp32, and remove pathological documents.

Full 40-minute answer →
How does mixed-precision training work? Compare fp16, bf16 and fp8. Pre-training & OptimizationMid

30-second answer

Matmuls run in low precision on tensor cores while an fp32 master copy of weights and the Adam moments are kept, and reductions accumulate in fp32; otherwise small updates round away. fp16 has 5 exponent bits (max 65,504), so gradients underflow without dynamic loss scaling; bf16 keeps fp32's 8-bit exponent with only 7 mantissa bits, so it rarely needs scaling and is the standard. fp8 (E4M3 for weights/activations, E5M2 for gradients) needs per-tensor or per-block scaling factors and higher precision for sensitive ops, but can raise throughput substantially.

Full 40-minute answer →
Design the data pipeline for pre-training an LLM on web data. Pre-training & OptimizationSenior

30-second answer

Extract clean text from HTML, identify language, then apply cheap heuristic filters (length, symbol ratios, repetition, stopwords) and a model-based quality classifier. Deduplicate exactly with hashes and near-duplicates with MinHash LSH on n-gram shingles, since duplicates waste compute, increase memorization and leak benchmarks. Filter PII and toxic content, and decontaminate against evaluation sets with long n-gram matching. Choose mixture weights across web, code, math, books and multilingual data with small-model ablations, repeat scarce high-quality data only a few epochs, and anneal on the best data at the end.

Full 40-minute answer →
Estimate the GPU memory needed to train a 7B-parameter model. Where does it go, and how do you reduce it? Distributed TrainingMid

30-second answer

Mixed-precision AdamW needs ~16 bytes per parameter: bf16 weights and gradients (4 B) plus fp32 master weights and two Adam moments (12 B), so ~112 GB of state for 7B, more than one 80 GB GPU. Activations add roughly 34·s·b·h bytes per layer: at 4k tokens, h = 4096 and 32 layers that's ~18 GB per sequence. Reduce it by sharding state with ZeRO/FSDP (16/N bytes per parameter with full sharding), activation recomputation (~33% more compute for most of the activation memory), smaller micro-batches with gradient accumulation, and 8-bit optimizer states.

Full 40-minute answer →
How does data-parallel training synchronize gradients? What does a ring all-reduce cost? Distributed TrainingMid

30-second answer

Each replica computes gradients on its slice of the batch, then gradients are summed with an all-reduce so every replica applies the same update. A ring all-reduce is a reduce-scatter followed by an all-gather, each N−1 steps of S/N bytes, so each GPU sends 2(N−1)/N·S bytes, nearly independent of N. For 14 GB of bf16 gradients on 8 GPUs that's ~24.5 GB per GPU, ~55 ms on NVLink. Gradients are bucketed and reduced during the backward pass so communication overlaps compute; at large scale hierarchical and tree algorithms reduce latency.

Full 40-minute answer →
Explain ZeRO stages 1–3 and FSDP. What do they save, and what do they cost? Distributed TrainingSenior

30-second answer

Data parallelism replicates 16 bytes per parameter on every GPU. ZeRO-1 shards the 12 bytes of fp32 optimizer state, ZeRO-2 also shards gradients (reduce-scatter instead of all-reduce), both at the same communication volume as DDP. ZeRO-3/FSDP also shards parameters, all-gathering each layer group just before use in forward and backward and freeing it afterwards, for ~1.5× DDP's communication and 16/N bytes per parameter. A 7B model on 64 GPUs drops from 112 GB to ~29 GB (ZeRO-1) or ~1.75 GB (ZeRO-3) of state per GPU. Prefetching hides communication; hybrid sharding keeps all-gathers within nodes.

Full 40-minute answer →
Compare tensor parallelism and pipeline parallelism. When would you use each? Distributed TrainingSenior

30-second answer

Tensor parallelism splits each layer's matrices across GPUs (column-parallel then row-parallel in the MLP, by heads in attention), needing two all-reduces of b·s·h activations per layer per direction, so it's kept within a node on NVLink. Pipeline parallelism splits layers into stages and sends only boundary activations point-to-point, so it works across nodes, but idles for (p−1)/(m+p−1) of the time unless there are many micro-batches; 1F1B bounds activation memory and interleaving shrinks the bubble. Typical layouts use TP = 8 within a node, a small PP degree across nodes, and data parallelism for the rest.

Full 40-minute answer →
Plan the pre-training of a 70B dense model on 1.4T tokens with 2,048 H100s. Choose a parallel layout and estimate the time. Distributed TrainingStaff

30-second answer

Compute is 6 × 70e9 × 1.4e12 ≈ 5.9e23 FLOPs; at 40% MFU on 2,048 × 989 TFLOP/s that's ~7.3e5 s, about 8.4 days, so budget ~10–11 days with failures. State is ~1.1 TB, so model parallelism is required: TP = 8 within each node, PP = 4 across nodes (20 layers per stage), DP = 64 with ZeRO-1, giving ~9 GB of weights, gradients and optimizer shards per GPU plus activations. With a 4M-token batch (1,024 × 4k sequences), each replica runs 16 micro-batches, a 1F1B bubble of ~16% that interleaving halves. Add sequence parallelism, selective recompute, async checkpoints about every 20 minutes and hot spares.

Full 40-minute answer →
Your training run reaches 20% MFU. How do you find and fix the lost throughput? Distributed TrainingSenior

30-second answer

MFU is useful model FLOPs (≈6N per token plus attention) per second divided by peak; 20% for a dense model on H100s leaves a lot on the table. Profile a step and account for time: exposed communication (TP across nodes, non-overlapped gradient reduce, small FSDP units), pipeline bubble (too few micro-batches), full recomputation where selective suffices, unfused or misaligned kernels, data-loader or Python host overhead and synchronization points, and stragglers visible in per-rank step times. Fix the biggest bucket first, re-measure, and repeat.

Full 40-minute answer →
How do you keep a multi-week training run on thousands of GPUs productive despite failures? Distributed TrainingSenior

30-second answer

Expect failures every few hours at this scale. Checkpoint the full state (weights, optimizer, data position, RNG) sharded and asynchronously, at an interval of about √(2 × checkpoint cost × MTBF), e.g. ~20 minutes. Automate detection, health checks, node replacement from hot spares, and restart from the last checkpoint. Track per-rank timing to find stragglers, watch for silent data corruption via cross-replica checks and replays, and keep runs deterministic so problems can be reproduced. Measure goodput: the fraction of wall-clock time producing useful training progress.

Full 40-minute answer →
What is the KV cache? How large does it get, and how do you reduce it? Inference & ServingMid

30-second answer

In autoregressive decoding the keys and values of earlier tokens never change, so they're cached and each step only computes projections for the new token and attends over the cache, turning quadratic recomputation into linear work per step. It costs 2 × layers × KV heads × head dim × bytes per token: ~320 KB for a 70B GQA model in bf16 (1.3 GB per 4k-token sequence), 8× more with full multi-head attention. It caps batch size and context length, so it's reduced with GQA/MQA or latent attention, fp8/int8 KV, paged allocation, prefix sharing and sliding-window layers.

Full 40-minute answer →
Explain prefill and decode in roofline terms. Which dominates latency and cost? Inference & ServingMid

30-second answer

Prefill processes all prompt tokens in parallel, reusing each weight across hundreds or thousands of tokens, so its arithmetic intensity is far above the GPU's ridge point (~295 FLOPs/byte on H100) and it's compute-bound; it sets time to first token. Decode produces one token per sequence per step and reads all weights plus each sequence's KV cache, giving intensity roughly equal to the batch size, so it's memory-bandwidth-bound; it sets time per output token. For typical outputs decode dominates end-to-end latency, and batching decode is the main throughput lever.

Full 40-minute answer →
Estimate latency and throughput for serving a 70B model on 8 H100s. Inference & ServingSenior

30-second answer

Weights are 140 GB in bf16, 17.5 GB per GPU with TP = 8. At batch 1, each decode step reads them at 3.35 TB/s: a floor of ~5.2 ms/token, ~8–12 ms in practice with all-reduces and kernel efficiency. At batch 64 with 2k-token contexts, KV reads add ~42 GB (5.2 GB per GPU), giving a ~6.8 ms floor per step for 64 tokens: ~9,000 tokens/s ideal, several thousand in practice, still memory-bound (compute is ~1.1 ms). Prefilling a 2k prompt takes ~2.9e14 FLOPs, ~75 ms at 50% utilization. KV capacity (~450 GB free) bounds the batch.

Full 40-minute answer →
How do continuous batching and paged attention improve LLM serving throughput? Inference & ServingSenior

30-second answer

Static batching holds a batch until its longest request finishes, wasting slots and delaying new requests. Continuous batching schedules every decode iteration: finished sequences leave and waiting ones join, keeping the batch full. Paged attention stores the KV cache in fixed-size blocks with per-sequence block tables, so memory isn't reserved for maximum length, waste is under one block per sequence, and blocks can be shared for common prefixes or parallel samples. Together they raise the effective batch size several-fold. Chunked prefill bounds latency spikes from long prompts; disaggregation separates prefill and decode pools.

Full 40-minute answer →
How would you quantize an LLM for serving? What are the options and pitfalls? Inference & ServingSenior

30-second answer

Choose by bottleneck. Weight-only int8/int4 (GPTQ, AWQ) cuts bytes per decode step, helping memory-bound small-batch serving and fitting a 70B model (~35 GB in int4) on one GPU. Weight-and-activation fp8 or int8 (with SmoothQuant-style outlier handling) speeds up matmuls for prefill and large batches. Quantize the KV cache to fit more or longer sequences. The difficulty is activation outliers, handled with per-channel or per-group scales and calibration data. Validate on your own tasks, especially math, code, long context and multilingual, since averages hide regressions.

Full 40-minute answer →
How does speculative decoding work, why is it lossless, and how much does it speed things up? Inference & ServingSenior

30-second answer

A cheap draft (small model, extra heads like Medusa/EAGLE, or n-gram lookup) proposes k tokens; the target scores all of them in one forward pass, which costs about one decode step because decode is memory-bound. Each draft token is accepted with probability min(1, p/q); at the first rejection a replacement is sampled from normalize(max(0, p − q)), which provably preserves the target's distribution. With acceptance α, expected tokens per target pass are (1 − α^{k+1})/(1 − α): ~3.4 for α = 0.8, k = 4, typically a 2–3× latency gain. Gains shrink at large batch sizes and high temperatures.

Full 40-minute answer →
Explain temperature, top-k, top-p and min-p sampling, and when to use beam search or constrained decoding. Inference & ServingMid

30-second answer

Temperature divides logits before softmax: below 1 sharpens, above 1 flattens, near 0 approaches greedy. Truncation removes the unreliable tail: top-k keeps a fixed number of tokens, top-p keeps the smallest set reaching cumulative probability p, and min-p keeps tokens above a fraction of the top probability, adapting to confidence. Beam search maximizes sequence likelihood and suits short constrained outputs like translation, but yields bland, repetitive open-ended text. Constrained decoding masks invalid tokens to guarantee JSON or grammar validity. Use low temperature for extraction and code, moderate for chat, higher for diverse sampling.

Full 40-minute answer →
How does supervised fine-tuning turn a base model into an assistant? Discuss chat templates, loss masking and data. Post-training & AlignmentMid

30-second answer

SFT trains on conversations formatted with a chat template whose special tokens mark system, user, assistant and tool turns, using the same next-token loss as pre-training but masked so only assistant tokens contribute. The template must match inference exactly. A modest amount of high-quality, diverse data teaches format and behaviour, since knowledge comes from pre-training; coverage of skills such as code, math, tools, refusals and multilingual text matters more than raw volume. Use low learning rates for 1–3 epochs, evaluate on tasks, mix in general data to limit forgetting, and avoid training the model to assert facts it doesn't know.

Full 40-minute answer →
How does LoRA work? Work through its parameter and memory savings, and explain QLoRA. Post-training & AlignmentMid

30-second answer

LoRA freezes W and learns ΔW = (α/r)·BA with A (r × d_in) random and B (d_out × r) zero-initialized, so training starts from the base model and the update can be merged afterwards with no inference cost. Each adapted matrix adds r(d_in + d_out) parameters: for a 7B model with r = 16 on all linear layers, about 40M (~0.6%), so optimizer state drops from ~112 GB to under 1 GB. Adapters are megabytes and can be served per tenant. QLoRA keeps the frozen base in 4-bit NF4 and adapters in bf16, fitting 65B fine-tuning on one 48 GB GPU.

Full 40-minute answer →
When would you fine-tune instead of using RAG or prompting, and vice versa? Post-training & AlignmentMid

30-second answer

Start with prompting and evaluation. Use RAG when answers need fresh, private, large or citable knowledge, or knowledge that changes, since retrieval is updatable and auditable. Fine-tune to change behaviour: consistent format and tone, a narrow skill, domain style, tool-use patterns, or to replace long prompts at high volume or distil a large model into a cheaper one. Fine-tuning is unreliable for injecting facts and can increase hallucination on unseen ones. They combine well: fine-tune for behaviour and retrieval use, retrieve for knowledge, and justify each step with evals.

Full 40-minute answer →
How is a reward model trained, and how do you detect and prevent reward hacking? Post-training & AlignmentSenior

30-second answer

Collect preference comparisons and train the SFT model with a scalar head under the Bradley–Terry loss −log σ(r(x, y_w) − r(x, y_l)). Its accuracy on held-out pairs is typically only 65–75%, and optimizing hard against it exploits its errors: longer answers, sycophancy, confident tone, formatting tricks. Gold-reward quality rises then falls as the policy moves away (in KL) from the reference. Prevent it with a KL penalty, early stopping on a held-out gold judge, reward-model ensembles, length control, refreshing the reward model on new policy samples, rule-based or verifiable rewards where possible, and reading samples.

Full 40-minute answer →
Compare RLHF with PPO and DPO. Derive the DPO objective. Post-training & AlignmentSenior

30-second answer

RLHF maximizes reward-model score minus β·KL to a reference policy, usually with PPO, which needs online sampling and policy, reference, reward and value models. That objective's optimum is π* = π_ref·exp(r/β)/Z, so r = β log(π*/π_ref) + β log Z; substituting into the Bradley–Terry likelihood cancels Z and gives DPO's loss −log σ(β[log π(y_w)/π_ref(y_w) − log π(y_l)/π_ref(y_l)]), a supervised loss on pairs with only policy and reference models. DPO is simpler and stable but offline; online or iterative DPO and RL with fresh samples generally do better, and RL handles non-preference rewards.

Full 40-minute answer →
How are reasoning models trained with reinforcement learning? Explain RL with verifiable rewards and GRPO. Post-training & AlignmentSenior

30-second answer

Use tasks with programmatically checkable outcomes: math answers compared with references, code run against tests, format and constraint checks. For each prompt, GRPO samples a group of G responses, scores them, and gives every token in response i the advantage (r_i − mean)/std, then applies a PPO-style clipped update with a KL penalty; the group mean replaces a learned value model. Prompts all-correct or all-wrong give no signal, so difficulty is curated. Longer reasoning with self-checking emerges, accuracy scales with thinking tokens, and risks include reward hacking of weak verifiers, length growth and entropy collapse.

Full 40-minute answer →
Design the post-training pipeline that turns a new base model into a helpful, safe assistant with strong reasoning. Post-training & AlignmentStaff

30-second answer

Define target capabilities, safety policy and an evaluation suite first. Stage 1: SFT on curated, diverse conversations (human, distilled and rejection-sampled), with loss masking and a fixed chat template. Stage 2: preference optimization (reward model plus RL, or online/iterative DPO) on fresh policy samples for helpfulness, honesty and harmlessness, with a KL anchor. Stage 3: RL with verifiable rewards for math, code and tool use (GRPO-style), with curriculum and anti-hacking checks. Interleave safety data and red-teaming, gate each stage on regression evals, and iterate the data flywheel from evaluation failures.

Full 40-minute answer →
What is pass@k, and how do you estimate it without bias? EvaluationMid

30-second answer

pass@k is the probability that at least one of k sampled solutions passes the tests, used for code and math where a verifier can pick a correct sample. Plugging the empirical success rate into 1 − (1 − p)^k is biased. Instead draw n ≥ k samples per problem, count c correct, and use 1 − C(n − c, k)/C(n, k), computed stably as a running product, averaged over problems. For n = 20, c = 3, pass@5 ≈ 0.60. Report n, temperature and the k values, use a higher temperature for large k, and note that pass@k overstates single-attempt usefulness.

Full 40-minute answer →
How does benchmark contamination happen, and how would you detect and prevent it? EvaluationSenior

30-second answer

Test items leak into training through web copies, forum solutions, synthetic data from models that saw them, or tuning on test sets, inflating scores. With access to the corpus, search for long n-gram overlaps and canary strings. Without it, look for membership signals (abnormally low perplexity or high min-k% token probabilities, verbatim completion from a prefix) and, most convincingly, a performance gap on freshly written or perturbed versions of the items. Prevent it by decontaminating all training stages against reported evals, keeping private and time-split held-out sets, and refreshing benchmarks.

Full 40-minute answer →
How do you use an LLM as a judge reliably? What biases does it have? EvaluationSenior

30-second answer

Use a strong judge with an explicit rubric or checklist, a reference answer for factual tasks, and pairwise comparison when detecting small differences. Known biases are position (favouring one slot), verbosity, self-preference for its own model family, and rewarding style over correctness; counter them by judging both orders, controlling for length, using a different or multiple judge families, and asking for reasoning before the verdict. Validate on a few hundred human-labelled examples from your domain, comparing judge–human agreement with human–human agreement, and re-validate whenever the judge or prompt changes.

Full 40-minute answer →
Your new model scores 2 points higher on a 500-item benchmark. Is it better? EvaluationSenior

30-second answer

Probably not established. At 70% accuracy and n = 500 the standard error is about 2 points, so each model's 95% interval is roughly ±4 points. Compare paired: only items where the models disagree matter; if they disagree on 75 items, split 42 to 33, McNemar's z ≈ 9/√75 ≈ 1.0, not significant. To confirm, add items or benchmarks, average over sampling runs and seeds, check prompt robustness, account for clustered items, and avoid picking the best of many variants without a held-out confirmation set.

Full 40-minute answer →
Why do LLMs hallucinate, how do you measure it, and how do you reduce it? EvaluationMid

30-second answer

Pre-training rewards plausible continuations, and models have no built-in signal separating known from unknown facts; fine-tuning on facts the model didn't know and evaluations that grade abstentions as wrong both reward confident guessing. Measure factuality on closed-book QA scored for correct, wrong and abstained answers, faithfulness to provided context in RAG, and atomic-claim precision for long answers. Reduce it with retrieval grounding and verified citations, training and prompting that reward calibrated abstention, constrained outputs, self-consistency checks, and grading that penalizes confident errors more than abstentions.

Full 40-minute answer →
Design the evaluation suite for deciding whether to ship a new model version in an LLM product. EvaluationSenior

30-second answer

Start from product tasks and failure costs. Build layered evals: deterministic checks (formats, tool calls, unit tests), reference-based task sets sampled from real traffic with labels, rubric or pairwise LLM-judge evals validated against human labels, safety and over-refusal sets, and latency and cost measurements. Version datasets, keep a regression set of past incidents, and stratify by segment. Compare candidate and production on the same items with paired statistics and decision thresholds set in advance, then confirm with shadow traffic and a staged rollout watching online metrics.

Full 40-minute answer →
Design a customer-support chatbot that answers from a company knowledge base. AI System DesignSenior

30-second answer

Clarify scale, latency, languages and escalation requirements. Metrics: resolution/deflection rate, groundedness, CSAT, p95 latency, cost per conversation. Architecture: ingestion pipeline (parse, chunk by section, embed, index with metadata), orchestrator with input guardrails, hybrid retrieval + rerank, an LLM prompted to answer only from cited context and hand off when unsure, output checks, streaming. Deep dives: evals (golden set with unanswerable cases), human handoff, freshness of docs, caching common questions, and monitoring with feedback loops.

Full 40-minute answer →
How would you reduce the latency of an LLM feature that currently takes 8 seconds? AI System DesignMid

30-second answer

First measure the breakdown: retrieval, queueing, time-to-first-token, decode. Then: stream output; cut output length; use a smaller or faster model for some or all steps; parallelize retrieval and tool calls; trim the prompt and use prompt caching for static prefixes; cache frequent responses. If self-hosting, use continuous batching, quantization and speculative decoding.

Full 40-minute answer →
Your LLM bill doubled last month. How do you investigate and reduce it? AI System DesignMid

30-second answer

Break cost down by feature, model, tenant and input vs. output tokens using request logs. Look for prompt bloat (too many retrieved chunks, long histories), runaway agent loops, retries, or traffic growth. Reduce with routing to cheaper models, prompt caching, shorter outputs, conversation summarization, response caching, batch APIs for offline work, and budgets/limits per user or tenant.

Full 40-minute answer →
How do you get reliable JSON out of an LLM? AI System DesignJunior

30-second answer

Use the provider's structured output or tool-calling mode with a JSON schema where available. Give a clear schema and examples. Validate every response with a schema validator; on failure, retry with the validation error included. Keep schemas simple, and design downstream code to handle a final failure gracefully.

Full 40-minute answer →
What is prompt injection and how do you defend against it? AI System DesignMid

30-second answer

It's when input causes the model to follow attacker instructions instead of the developer's. Indirect injection arrives through content the model reads (web pages, emails, documents). Defences limit impact rather than eliminate it: treat external content as data, least-privilege tools scoped to the user, human confirmation for consequential actions, block data exfiltration channels like auto-loaded URLs, injection classifiers as one layer, and red-team testing.

Full 40-minute answer →
Design a content moderation service that inspects LLM outputs in real time. AI System DesignSenior

30-second answer

Functional: classify streamed LLM output against a policy taxonomy, apply per-tenant actions (allow, redact, halt and replace) and log every decision for audit and human review. Non-functional: under ~300 ms added to first text with no stutter, 99.95% availability, per-category precision and recall targets, fail-open or fail-closed per surface. Design: a shared service the LLM gateway streams to; text is held in sentence-sized windows, a small classifier scores every window, an LLM judge handles uncertain ones, and a policy engine decides. Key trade-off: holding text keeps users safe but adds delay, so use a small first window and pipeline the checks.

Full 40-minute answer →
How would you evaluate a new model before switching production traffic to it? AI System DesignMid

30-second answer

Run it on the offline golden set covering quality, safety and format adherence, and compare against the current model with the same prompts (adjusting prompts if needed). Check latency and cost. Then shadow traffic or a small canary with online metrics and guardrail rates, followed by a staged rollout with a quick rollback path.

Full 40-minute answer →
When should you NOT use an LLM? AI System DesignJunior

30-second answer

When a deterministic rule, regex, lookup or small classifier solves the problem reliably; when latency or cost budgets are tiny and volume huge; when outputs must be exactly reproducible or provably correct; or when you can't tolerate any unverified errors and can't add verification. LLMs are best where inputs are messy and some fuzziness is acceptable or checkable.

Full 40-minute answer →
Explain semantic caching and its risks. AI System DesignMid

30-second answer

Store past query embeddings with their answers; for a new query, return a cached answer if a previous query is similar enough. It saves cost and latency for repetitive traffic. Risks: near-identical questions can need different answers ("cancel my order" vs. "don't cancel my order"), personalization and permission differences, and stale answers. Use conservative thresholds, scope caches by user/tenant, add TTLs, and evaluate false-hit rates.

Full 40-minute answer →
How would you design a model router? AI System DesignSenior

30-second answer

Classify each request by difficulty or type with a cheap model or heuristics, then send easy ones to a small model and hard ones to a large model. Alternatively, cascade: try the small model and escalate if a verifier or confidence signal is low. Measure the quality/cost frontier on an eval set, include fallbacks for provider outages, and monitor routing distribution for drift.

Full 40-minute answer →
What would you log for an LLM request, and what would you avoid logging? AI System DesignMid

30-second answer

Log model and version, prompt template version, token counts, latency breakdown, retrieved document IDs, tool calls, guardrail decisions, cost, errors and feedback, with a trace ID. Avoid storing raw PII and secrets; redact or tokenize sensitive fields, restrict access, and apply retention limits consistent with privacy commitments.

Full 40-minute answer →
What is the 'lethal trifecta' for AI agents? AI System DesignSenior

30-second answer

An agent that combines access to private data, exposure to untrusted content, and a channel to communicate externally. Untrusted content can inject instructions that make the agent read private data and send it out. The mitigation is architectural: remove at least one leg, for example by blocking outbound channels or requiring human approval for them.

Full 40-minute answer →
Design an LLM inference service that serves open-weight models on your own GPUs to internal teams. AI System DesignStaff

30-second answer

Functional: OpenAI-compatible streaming API, several models behind stable names, interactive and batch priorities, per-team quotas and metering, safe rollouts. Non-functional: TTFT ≤ 800 ms and ≤ 40 ms per output token at p95, which caps decode batch size. Estimate decode and prefill separately: ~300 req/s at peak needs roughly fourteen 8-GPU nodes. Design: gateway with token buckets, a router using prefix-cache affinity with bounded load, engine pools with continuous batching, paged KV, prefix caching and chunked prefill, batch backfill that's preempted first, autoscaling on queue time with warm spares, and canary rollouts with quality checks.

Full 40-minute answer →
Design a multi-tenant platform where customers fine-tune and serve their own LoRA models. AI System DesignStaff

30-second answer

Functional: dataset upload and validation, LoRA jobs with good defaults, loss curves, automatic evaluation against the base model, deployment by model ID, deletion and audit. Non-functional: strict tenant isolation, low idle cost, fine-tuned latency within ~10% of base. A typical 8B job (30M tokens) needs ~4N FLOPs/token, about 40 minutes on one H100. Design: tenant-keyed encrypted storage, sandboxed training containers on a fairly scheduled GPU pool, an eval and safety gate, a registry with lineage, and multi-LoRA serving that batches different adapters over shared base weights with GPU/host/object-store adapter caches and adapter-affinity routing.

Full 40-minute answer →
Design a ChatGPT-style conversational assistant for 10 million daily users. AI System DesignSenior

30-second answer

Functional: streaming answers, multi-turn context, history across devices, regenerate and edit (a message tree), sharing, free and paid tiers. Non-functional: TTFT ≤ 1 s p95, resumable streams, no lost messages. ~3,500 messages/s at peak and ~35,000 open streams; model serving is ~99% of cost. Design: save the user message first; build context from the current branch within a token budget (recent turns verbatim, older ones summarized), keeping the prefix stable; route with conversation affinity so the prefix cache hits; write tokens to a stream buffer that clients read with Last-Event-ID; write the final message back. Overload: degrade the free tier first and route easy messages to smaller models.

Full 40-minute answer →
Design an inline code-completion assistant like GitHub Copilot. AI System DesignSenior

30-second answer

Latency first: suggestion within ~300 ms p50 and 500 ms p95 of a pause. The client debounces, cancels stale requests, reuses suggestions as the user types through them, and sends prefix, suffix and the most similar snippets from open files, ordered so consecutive prompts share a cacheable prefix. A small fill-in-the-middle code model (3–15B) in nearby regions with session affinity generates short completions, which are trimmed at block boundaries, parsed and filtered (secrets, public-code matches). ~50k requests/s at peak, prefill-dominated, so prefix caching cuts GPUs ~4×. Measure accepted and retained code, not just acceptance.

Full 40-minute answer →
Design a real-time answer engine like Perplexity that answers questions from the live web with citations. AI System DesignSenior

30-second answer

Pipeline with per-stage budgets: a small model rewrites the question into searches and a freshness class (~120 ms); our fresh index and a search API run in parallel (~250 ms); pages come from a snapshot cache or a live fetch with a 700 ms timeout; a cross-encoder reranks ~60 passages with a per-domain diversity limit; sources show at ~1.1 s. The answer model writes only from numbered passages, and an entailment model checks each cited sentence. ~3 cents per query, so cache answers by freshness class and route simple lookups to cheaper models. Buy coverage (search API), build freshness (own index for news and popular domains).

Full 40-minute answer →
Design long-term memory for a chat assistant, so it remembers users across conversations. AI System DesignSenior

30-second answer

Two paths. Write: explicit 'remember/forget' goes through a synchronous memory tool; other user turns pass a cheap gate (~5% pass) and an async LLM extractor that compares them with similar existing memories and emits ADD/UPDATE/DELETE operations. Extract only from user-authored text to prevent memory poisoning by injected content. Read: always include a short profile summary, plus memories above a similarity threshold, found by exact search over the user's small set (no vector database needed). Users can view, edit and delete everything; temporary chats bypass memory; deletion propagates to embeddings, summaries and caches.

Full 40-minute answer →
Design an autonomous coding agent that takes an issue and opens a pull request. AI System DesignStaff

30-second answer

Per-task microVM sandboxes from warm snapshots (repo and dependencies), with no credentials and egress limited to a package proxy. The harness runs the loop outside the sandbox with search, read, edit (exact replace), run and todo tools; trims tool output; keeps the prompt prefix stable so ~90% of input is cached (~$1 instead of ~$4.40 per task); compacts rarely. Limits on steps, cost and time, loop detection, and the harness re-runs tests before finishing. A separate git service pushes the diff with a branch-scoped token and opens a PR for human review. Checkpoints allow resuming from review comments; a benchmark of past issues measures every change.

Full 40-minute answer →
Design a real-time voice agent that handles customer-support phone calls. AI System DesignSenior

30-second answer

Target ~1 s from the caller stopping to hearing a reply. Cascaded streaming pipeline: telephony and a media server, a per-call session with VAD, streaming ASR and an end-of-turn model, a fast LLM with cached instructions and tools, and streaming TTS that starts on the first clause. Budget: ~250 ms end of turn, 50 ms ASR final, 250 ms LLM first token, 180 ms first clause, 120 ms TTS, 100 ms network. Barge-in stops playback within ~200 ms and truncates the transcript to words actually played. Identity checks gate tools in code; filler speech covers slow tools; any failure transfers to a human. Compare with speech-to-speech models on latency vs control.

Full 40-minute answer →
Walk me through how you'd build a RAG system over a company's internal docs. RAG & RetrievalMid

30-second answer

Offline: load and parse docs keeping structure, chunk by section with overlap, prepend title/section headers, embed, store with metadata (source, date, ACL). Online: rewrite the query with conversation context, run hybrid retrieval (BM25 + vectors) with permission filters, rerank top ~50 to ~5, build a prompt with delimited, ID-tagged chunks and instructions to cite and to say when the answer isn't present, then generate. Wrap it with an eval set measuring recall@k and faithfulness, plus logging and feedback.

Full 40-minute answer →
How do you choose chunk size? RAG & RetrievalMid

30-second answer

Empirically, against a retrieval eval. Start with structure-aware chunks of a few hundred tokens with modest overlap. Too small loses context; too large dilutes the embedding and wastes prompt space. Consider parent-child retrieval: match on small chunks, pass the larger parent section to the model. Measure recall@k and answer quality across a few settings rather than guessing.

Full 40-minute answer →
Why use hybrid search instead of only vector search? RAG & RetrievalMid

30-second answer

Dense embeddings capture meaning and paraphrase but are weak on exact tokens such as error codes, SKUs, names and rare jargon. BM25 excels at exact matches. Combining them (often with Reciprocal Rank Fusion) improves recall across both query types at little cost.

Full 40-minute answer →
What is a reranker and why is it more accurate than the first-stage retriever? RAG & RetrievalMid

30-second answer

A cross-encoder reranker processes the query and a candidate together, so attention can compare them token by token. A bi-encoder embeds them separately and compares one vector to another, which compresses information. Cross-encoders are too slow to run over the whole corpus, so you retrieve broadly with a bi-encoder or BM25 and rerank a small candidate set.

Full 40-minute answer →
Explain HNSW and its main parameters. RAG & RetrievalSenior

30-second answer

HNSW builds a layered proximity graph: sparse upper layers for long jumps, a dense bottom layer with every vector. Search greedily walks from an entry point toward the query, descending layers. M controls edges per node (recall and memory), efConstruction controls build quality, efSearch controls query-time candidate list size (recall vs. latency). It gives high recall at low latency but uses significant memory.

Full 40-minute answer →
HNSW vs. IVF-PQ: when would you choose each? RAG & RetrievalSenior

30-second answer

HNSW for high recall and low latency when the vectors fit in memory and you need incremental inserts. IVF-PQ when scale or memory cost dominates (hundreds of millions to billions of vectors): IVF limits the search to a few clusters and PQ compresses vectors heavily, at some accuracy cost, often with re-ranking on full vectors.

Full 40-minute answer →
How do you enforce document permissions in RAG? RAG & RetrievalSenior

30-second answer

Store ACL metadata (tenant, groups, document IDs) with each chunk and filter at retrieval time using the caller's identity, never relying on the LLM to withhold information. Use a vector store that supports efficient filtered search, keep ACLs in sync with the source system, and test for leakage in evals. Per-tenant indexes are an option for strong isolation.

Full 40-minute answer →
How do you evaluate a RAG system? RAG & RetrievalMid

30-second answer

Separate retrieval from generation. Retrieval: recall@k, MRR, nDCG on a labeled query set. Generation: faithfulness to context, answer relevance, correctness against references, citation accuracy, often with a calibrated LLM-as-judge. Include unanswerable and multi-hop cases, version the set, run it in CI, and complement with online feedback signals.

Full 40-minute answer →
What is 'lost in the middle' and how do you mitigate it? RAG & RetrievalMid

30-second answer

Models tend to use information at the beginning and end of a long context better than information in the middle. Mitigate by sending fewer, better-reranked chunks, placing the most relevant ones at the edges, and keeping prompts focused rather than stuffing the context window.

Full 40-minute answer →
Your embedding provider releases a better model. How do you migrate? RAG & RetrievalSenior

30-second answer

Embeddings from different models aren't comparable, so you must re-embed the corpus. Build a new versioned index in parallel, backfill in batches, evaluate it against the old one on the golden set, dual-write new documents to both during transition, then shift traffic gradually and keep the old index for rollback.

Full 40-minute answer →
When does long context make RAG unnecessary? RAG & RetrievalSenior

30-second answer

For small, stable corpora that fit comfortably in context, stuffing everything in can be simpler. RAG still wins when the corpus is large, changes often, needs per-user permissions, must cite sources, or when cost and latency matter, since long prompts are expensive and slower. Prompt caching narrows the gap for static content.

Full 40-minute answer →
What is HyDE? RAG & RetrievalMid

30-second answer

Hypothetical Document Embeddings: have the LLM write a plausible answer to the query, embed that, and search with it. A hypothetical answer often lies closer to real answer passages in embedding space than a short question does. It costs an extra LLM call and can drift if the hypothetical answer is wrong.

Full 40-minute answer →
How does function calling / tool use work under the hood? Agents & LLM ApplicationsJunior

30-second answer

You send tool definitions (name, description, JSON schema). The model is trained to emit a structured tool call when appropriate. Your application parses it, executes the function, and returns the result as a tool-result message. The model then continues, possibly calling more tools, until it produces a final answer. The model never runs code itself.

Full 40-minute answer →
Implement an agent loop. What safeguards do you add? Agents & LLM ApplicationsMid

30-second answer

Loop: call the model with tools and history; if it requests tools, validate arguments, authorize against the user's permissions, execute (in parallel when independent), append results, repeat; stop on a final answer. Safeguards: max iterations and token budget, timeouts, errors returned as tool results, idempotency for side effects, human confirmation for destructive actions, logging/tracing of every step.

Full 40-minute answer →
When would you use a workflow (chained prompts) instead of an autonomous agent? Agents & LLM ApplicationsMid

30-second answer

When the steps are known in advance. Workflows are predictable, cheaper, faster and easier to test and debug. Use an agent only when the path genuinely depends on intermediate results and can't be enumerated, and accept the extra cost, latency and risk.

Full 40-minute answer →
How do you handle a conversation that exceeds the context window? Agents & LLM ApplicationsMid

30-second answer

Count tokens before sending. Options: drop the oldest turns while keeping the system prompt and recent turns; summarize older history into a running summary; move long-term facts into retrieval or a memory store; truncate large tool outputs. Choose based on what information the task actually needs.

Full 40-minute answer →
How do you test code that calls an LLM? Agents & LLM ApplicationsMid

30-second answer

Unit-test the surrounding code with a mocked client (prompt rendering, parsing, retries, tools). Validate output against schemas. Maintain an eval set graded by exact match, programmatic checks or a calibrated LLM judge, run it in CI on prompt/model changes, and look at pass rates over repeated runs. Add online monitoring and user feedback.

Full 40-minute answer →
How would you stream an LLM response to a web client? Agents & LLM ApplicationsMid

30-second answer

Call the provider's streaming endpoint (server-sent events) from the backend, never exposing API keys to the browser. Forward text deltas to the client via SSE or WebSockets, flush promptly, handle client disconnects by cancelling the upstream request, buffer tool-call arguments until complete, and record usage and errors from the final events.

Full 40-minute answer →
What is MCP? Agents & LLM ApplicationsJunior

30-second answer

The Model Context Protocol is an open standard for connecting AI applications to tools and data through a client–server interface. A server exposes tools, resources or prompts; any MCP-capable client can use them. It reduces one-off integrations. Security considerations include trusting servers, scoping credentials, and treating server outputs as untrusted content.

Full 40-minute answer →
How do you handle rate limits from an LLM provider at scale? Agents & LLM ApplicationsSenior

30-second answer

Client-side: exponential backoff with jitter honoring Retry-After. System-side: a token-aware rate limiter or queue in front of the provider, prioritizing interactive over batch traffic, per-tenant quotas, request batching where supported, prompt caching to reduce token load, and fallbacks to other models or regions. Monitor utilization against provisioned limits and request increases ahead of launches.

Full 40-minute answer →
Your prompt change improved one test case but you're unsure it's better overall. What do you do? Agents & LLM ApplicationsMid

30-second answer

Run the full eval set, ideally multiple times to account for non-determinism, and compare per-category scores against the baseline. Check for regressions in safety and format adherence. If the offline result is positive, roll out behind a flag or A/B test and watch online metrics before making it the default.

Full 40-minute answer →