Large language model (LLM) interview questions and answers

Large language model interview questions test whether you understand what happens inside the model, not only how to call an API. Expect self-attention and why it scales quadratically, the KV cache, tokenization, pretraining versus instruction tuning and preference tuning, temperature and top-p, quantization and serving costs, and why models hallucinate. Senior rounds add trade-offs: fine-tune or prompt, a bigger model or a smaller one, and how you would know a change helped.

By Published 7 min read

Who gets asked about LLM internals

LLM questions now appear in loops for ML engineers, research and applied scientists, AI engineers and some backend roles on AI teams. The depth varies. Product-facing AI engineers mostly get questions on context, decoding, cost and evaluation, with retrieval covered in RAG interview questions. Model-facing roles go further into attention math, training stages and inference optimization. This page covers both, from fundamentals to scenarios, and stays with ideas that hold across model families rather than any vendor's current lineup.

  1. Concept screenExplain attention, tokens, the context window and temperature in plain words. Interviewers probe one level deeper on each answer.
  2. CodingImplement scaled dot-product attention or a sampling function in NumPy or PyTorch, or write a small evaluation harness.
  3. Deep diveWalk through a project: which model, why, how you measured quality, what failed and what it cost to run.
  4. Design or scenarioServe a model under a latency budget, reduce hallucinations in a product, or decide whether to fine-tune.

LLM fundamentals questions

Fundamentals for freshers and every first screen
QuestionWhat it testsWhat a strong answer shows
What is a large language model?BasicsA neural network, almost always a transformer, trained to predict the next token on very large amounts of text. Generation is that prediction repeated, one token at a time, each new token appended to the input.
What is a token?TokenizationA unit from the model's fixed vocabulary, usually a word piece produced by a subword method such as byte-pair encoding. Common words are one token; rare words, code and many non-English scripts split into several, which affects cost and context use.
Explain self-attention in one minute.AttentionEach token builds a query, key and value vector. Its output is a weighted average of all values it may see, with weights from the softmax of query-key dot products scaled by the square root of the key dimension.
Why scale by the square root of d?NumericsDot products grow with dimension, which pushes softmax toward one-hot outputs with tiny gradients. Scaling keeps the scores in a range where training stays stable.
What does the causal mask do?AutoregressionIt stops each position from attending to later positions, so the model learns to predict the next token without seeing it. The same mask lets training score every position of a sequence in one pass.
What is multi-head attention for?ArchitectureSeveral smaller attention heads run in parallel, each free to focus on a different relation such as syntax, position or coreference. Their outputs are concatenated and projected back.
Why do transformers need positional information?PositionAttention by itself ignores order. Models add positions through learned or sinusoidal embeddings, or rotate queries and keys by position (rotary embeddings), which many recent models use.
Encoder-only, decoder-only or encoder-decoder?Model familiesEncoders (BERT style) read the whole input both ways and suit classification and embeddings. Decoder-only models generate left to right and dominate chat models. Encoder-decoder models suit translation and summarization with a clear input and output.
What is the context window?LimitsThe maximum number of tokens the model can attend to at once, prompt and output together. Anything beyond it is cut or must be summarized or retrieved.
What is the difference between pretraining and fine-tuning?Training stagesPretraining learns general language and knowledge from next-token prediction on huge corpora. Fine-tuning adapts that model to tasks, formats or behavior with far smaller, curated data.
Fundamentals for freshers and every first screen. Scroll sideways on a small screen.
import numpy as np

def causal_attention(Q, K, V):
    """Single-head scaled dot-product attention with a causal mask. Shapes: (seq, d)."""
    d = Q.shape[-1]
    scores = Q @ K.T / np.sqrt(d)
    future = np.triu(np.ones_like(scores, dtype=bool), k=1)
    scores = np.where(future, -np.inf, scores)     # token i cannot see tokens after i
    scores -= scores.max(axis=-1, keepdims=True)   # numerical stability
    weights = np.exp(scores)
    weights /= weights.sum(axis=-1, keepdims=True)
    return weights @ V, weights

rng = np.random.default_rng(0)
x = rng.normal(size=(4, 8))                     # 4 tokens, model width 8
Wq, Wk, Wv = (rng.normal(size=(8, 8)) for _ in range(3))
out, w = causal_attention(x @ Wq, x @ Wk, x @ Wv)
print(out.shape)                         # (4, 8)
print(w.round(2)[0])                     # [1. 0. 0. 0.]: the first token sees only itself
print(np.allclose(w.sum(axis=1), 1.0))   # True: each row is a distribution
Causal scaled dot-product attention for one head in NumPy.

Training and alignment questions

  • What objective is used to pretrain a decoder-only model? Cross-entropy on the next token at every position, averaged over the batch. Perplexity is the exponential of that loss and is a common pretraining metric.
  • What do scaling laws say, in plain terms? Loss falls predictably as parameters, data and compute grow together, and for a fixed compute budget there is a balance between model size and training tokens. Exact ratios differ between studies, so present it as a trend, not a constant.
  • What is supervised fine-tuning (SFT)? Training on example prompts and ideal responses so the model follows instructions and a chat format. It teaches behavior and style far more than new facts.
  • Explain RLHF at a high level. Humans compare pairs of responses, a reward model learns those preferences, and the language model is optimized against the reward with a penalty for drifting too far from the SFT model, often with PPO.
  • How does DPO differ from RLHF? Direct preference optimization skips the separate reward model and reinforcement learning loop. It trains directly on preferred and rejected pairs with a classification-style loss, which is simpler and often more stable.
  • What is LoRA and why is it popular? Low-rank adaptation freezes the base weights and learns small low-rank matrices added to selected layers. It cuts trainable parameters and memory sharply, and one base model can serve many adapters.
  • What is catastrophic forgetting? Fine-tuning on a narrow task degrades abilities the model had before. Mixing in general data, lower learning rates and parameter-efficient methods reduce it.
  • Should you fine-tune to add knowledge? Usually not as the first step. Facts that change belong in retrieval; fine-tuning is better for format, tone, a narrow skill or making a smaller model do what a larger one did.

Inference, decoding and serving questions

import numpy as np

def sample_next(logits, temperature=1.0, top_p=1.0, rng=np.random.default_rng(0)):
    """Temperature then nucleus (top-p) sampling over a vector of logits."""
    if temperature == 0:
        return int(np.argmax(logits))                # greedy decoding
    z = np.asarray(logits, dtype=float) / temperature
    probs = np.exp(z - z.max())
    probs /= probs.sum()
    order = np.argsort(probs)[::-1]
    cum = np.cumsum(probs[order])
    keep = order[: int(np.searchsorted(cum, top_p) + 1)]  # smallest set reaching top_p
    p = probs[keep] / probs[keep].sum()
    return int(rng.choice(keep, p=p))

logits = [2.0, 1.0, 0.5, -1.0]
print(sample_next(logits, temperature=0))               # 0, always the top token
print(sample_next(logits, temperature=0.7, top_p=0.5))  # 0: only token 0 is in the nucleus
for t in (0.5, 1.0, 2.0):
    z = np.array(logits) / t
    p = np.exp(z - z.max()); p /= p.sum()
    print(t, p.round(2))
# 0.5 [0.84 0.11 0.04 0.  ]
# 1.0 [0.61 0.22 0.14 0.03]
# 2.0 [0.43 0.26 0.21 0.1 ]
Temperature and nucleus (top-p) sampling over a vector of logits.
Intermediate questions on running models
QuestionWhat it testsWhat a strong answer shows
What do temperature and top-p change?DecodingTemperature divides the logits: low values sharpen the distribution, high values flatten it. Top-p samples only from the smallest set of tokens whose probabilities add up to p. Low settings suit extraction and code; higher ones suit brainstorming.
What is the KV cache?InferenceDuring generation, keys and values for earlier tokens do not change, so they are stored and reused rather than recomputed. It turns each new step into work on one token, at the cost of memory that grows with sequence length and batch size.
Why does attention cost grow quadratically?ComplexityEvery token scores every other token in the window, so compute and memory for the score matrix grow with the square of sequence length. Fused kernels such as FlashAttention cut memory traffic, and sparse or sliding-window schemes cut the work itself.
Prefill versus decode: why do they behave differently?PerformancePrefill processes the whole prompt in parallel and is compute-bound. Decode emits one token at a time and is usually limited by memory bandwidth, which is why batching many requests together raises throughput.
What does quantization trade?EfficiencyStoring weights in fewer bits (8-bit or 4-bit) cuts memory and often speeds inference, with some quality loss that depends on the method and the task. Always re-run your evaluation after quantizing.
What is speculative decoding?LatencyA small draft model proposes several tokens and the large model verifies them in one pass, accepting the ones it agrees with. Output matches the large model's distribution while using fewer slow steps.
What is continuous batching?ServingThe server adds new requests to a running batch as others finish, instead of waiting for a whole batch to complete, which keeps the accelerator busy with uneven output lengths.
How do you estimate the memory needed to serve a model?CapacityWeights take parameters times bytes per parameter. Add the KV cache, which scales with layers, hidden size, sequence length and concurrent requests, plus activation overhead. Show the arithmetic rather than quoting a number.
Intermediate questions on running models. Scroll sideways on a small screen.

Senior and scenario questions

Scenario rounds connect the internals to product decisions. Many end with a framework question, which is where LangChain interview questions pick up, or with grounding answers in documents.

Scenario questions for experienced candidates
QuestionWhat it testsWhat a strong answer shows
Why do LLMs hallucinate, and how do you reduce it?ReliabilityThe model predicts plausible text, not verified facts, and training can reward confident answers. Reduce it with retrieved sources and instructions to cite them, constrained output formats, lower temperature for factual tasks, and an evaluation that measures unsupported claims.
Your model ignores information in the middle of a long prompt. What do you do?Long contextModels often use the start and end of a long context more reliably than the middle. Put key instructions and evidence near the end, trim irrelevant text, or retrieve fewer, better passages instead of filling the window.
Fine-tune a small model or prompt a large one?Trade-offsPrompt the large model first to set a quality bar and collect data. Fine-tune a smaller one when volume makes cost or latency matter, the task is narrow and stable, and an evaluation shows it reaches the bar.
How would you evaluate a model change before shipping?EvaluationA fixed set of real inputs with reference answers or rubrics, automatic checks where possible, a model or human grader for open-ended outputs with its agreement measured, and slices for known hard cases. Compare against the current model, not in isolation.
Users report the assistant got worse after a provider update. How do you investigate?DebuggingPin model versions where you can, rerun the evaluation set on old and new versions, diff the failures by category, and check whether prompts relied on quirks of the old model.
Latency must drop by half without hurting quality. What are your options?OptimizationStream tokens, shorten prompts and outputs, cache repeated prefixes, route easy requests to a smaller model, quantize, and use speculative decoding. Measure time to first token and tokens per second separately.
Scenario questions for experienced candidates. Scroll sideways on a small screen.

Fictional example

"Explain the KV cache to a product manager"
Interviewer
A product manager asks why long conversations make our assistant slower and more expensive. How do you explain it?
Candidate
I would say the model rereads the whole conversation to write each new word, but it keeps notes on what it has already read, which we call the KV cache, so it does not start from scratch. Those notes grow with every message. Longer chats mean more memory per user, which means fewer users per machine, and the first reply after a long paste takes longer because the model reads all of it before answering. Then I would offer options: summarize older turns, drop pasted documents once used, or cap history, and I would measure answer quality on long chats before and after each one.

A two-week LLM practice plan

  • Days 1 to 3: implement attention, a causal mask and a tiny transformer block in NumPy or PyTorch, and explain each line aloud.
  • Days 4 and 5: tokenize sample text in several languages and code with a public tokenizer, and note how token counts change cost and context use.
  • Days 6 and 7: write one-minute answers on pretraining, SFT, RLHF, DPO and LoRA, each with when you would use it.
  • Days 8 and 9: work out serving arithmetic for an imaginary model: weight memory, KV cache per request and how batching changes throughput.
  • Days 10 to 12: build a 30-question evaluation set for one task and compare two decoding settings on it.
  • Days 13 and 14: three scenario questions out loud: hallucination, a latency cut and fine-tune versus prompt.

LLM interviews reward clear explanations of hard ideas, and you only find out how clear you were by reading it back. Natively, an AI interview assistant for Mac and Windows, records a text transcript of each mock round on your computer, so you can check whether your attention explanation made sense in one pass. During practice it can suggest answers, read an architecture diagram or a coding prompt from a screenshot, and help you debug a NumPy implementation. Pro or the free trial adds your résumé and the job description to its context, and the notes remain for later review.

Questions people ask

What LLM questions are asked in interviews?

How self-attention works and why it scales quadratically, tokens and context windows, the KV cache, pretraining versus fine-tuning, RLHF and DPO, LoRA, temperature and top-p, quantization and serving, hallucination and how to evaluate a model change.

How do I explain the transformer in an LLM interview?

Describe tokens turned into vectors, attention layers where each token weighs the earlier tokens by query-key similarity, feed-forward layers, and a final layer that predicts the next token, repeated during generation.

What is the difference between RLHF and DPO?

RLHF trains a reward model from human preference pairs and then optimizes the language model against it with reinforcement learning. DPO trains directly on the preference pairs with a simpler loss and no separate reward model.

Do LLM interviews include coding?

Often. Common tasks are implementing scaled dot-product attention or a sampling function in NumPy or PyTorch, or writing a small evaluation harness for model outputs.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP