AI

LLM Interview Questions and Answers for Freshers (30 Questions)

LLM Interview Questions and Answers for Freshers (30 Questions)

Short answer: An LLM interview checks whether you understand how a large language model works inside, and not only how to call one. Expect questions on tokens, the transformer and attention, how models are trained and aligned, how text is generated, and where models fail. Good answers are short, use a small example and name a trade-off.

Below are 30 questions in five groups, each with a model answer and a line on what interviewers look for. Six are marked For experienced. Seven answers come with small Python programs that run with no installs.

How to use this list

A large language model (LLM) is a neural network trained on a huge amount of text to predict the next piece of text. ChatGPT, Claude, Gemini and Llama are all LLMs.

This list is about the model itself. It does not repeat questions on retrieval or agents. Those have their own lists: RAG interview questions and answers and agentic AI interview questions and answers. Questions 27 and 28 give a short answer and point you there.

Every program uses only the Python 3 standard library. Save each block under the file name in its first line and run it with python3 <file>. Every output shown was produced with Python 3.12.8 on 24 November 2026. Nothing calls a real model, and nothing is random, so your output will match exactly.

The numbers in the programs are small and invented, so you can check them by hand. The one exception is question 23, which uses the real configuration of Qwen2.5-7B.

Basics: tokens, vocabularies and context

1. What is an LLM, and what does it actually do?

Answer: An LLM is a neural network that, given some text, produces a probability for every possible next token. A token is a small chunk of text, explained in the next question. To write a reply, the system picks one token, adds it to the text, and asks the model again. It repeats until the model emits a stop token. Models like this are called autoregressive: each output feeds back in as input. GPT-3, for example, is described in its paper as "an autoregressive language model with 175 billion parameters". Parameters are the learned numbers inside the network.

Interviewers look for: "predicts the next token" said plainly, and no claim that the model looks things up in a database or "understands" like a person.

2. What is a token, and why not use whole words or single characters?

Answer: A token is the unit of text the model reads and writes. It can be a whole word, part of a word, or a single character. Whole words need a huge vocabulary and fail on new words, names and typos. Single characters never fail, but a sentence becomes very long, and long inputs cost more. Subword tokens sit in the middle. Common words get one token, and rare words are split into pieces. Token count, not word count, decides how much text fits in the context window and what an API call costs.

Interviewers look for: the trade-off between vocabulary size and sequence length, and the habit of thinking in tokens.

3. How does byte pair encoding (BPE) build a vocabulary?

Answer: Start with every character as its own symbol. Count how often each adjacent pair appears in the training text. Merge the most frequent pair into a new symbol. Repeat for a fixed number of merges. Frequent words end up as single tokens, and rare words stay as pieces. Sennrich et al. (2015) adapted this old compression idea to words so a translation model could handle rare and unknown words. The final vocabulary size is the starting characters plus the number of merges. Many LLMs run the same idea on raw bytes, so any text can be encoded.

The program learns eight merges on a tiny corpus. The end-of-word mark _ lets the tokenizer tell "est" at the end of a word from "est" inside one.

# toy_bpe.py: learn byte pair encoding merges on a tiny corpus
from collections import Counter

# word -> how often it appears; "_" marks the end of a word
corpus = {"low_": 5, "lower_": 2, "newest_": 6, "widest_": 3}
words = {tuple(w): c for w, c in corpus.items()}

def pair_counts(words):
    counts = Counter()
    for symbols, freq in words.items():
        for pair in zip(symbols, symbols[1:]):
            counts[pair] += freq
    return counts

def merge(words, pair):
    out = {}
    for symbols, freq in words.items():
        new, i = [], 0
        while i < len(symbols):
            if i + 1 < len(symbols) and (symbols[i], symbols[i + 1]) == pair:
                new.append(symbols[i] + symbols[i + 1]); i += 2
            else:
                new.append(symbols[i]); i += 1
        out[tuple(new)] = freq
    return out

for step in range(1, 9):
    counts = pair_counts(words)
    best = max(counts, key=lambda p: (counts[p], p))   # ties go to the larger pair, so the output is fixed
    words = merge(words, best)
    print(f"merge {step}: {best[0]} + {best[1]} -> {best[0] + best[1]}  (seen {counts[best]} times)")

print()
for symbols, freq in words.items():
    print(" ".join(symbols), f"  x{freq}")

Output:

merge 1: t + _ -> t_  (seen 9 times)
merge 2: s + t_ -> st_  (seen 9 times)
merge 3: e + st_ -> est_  (seen 9 times)
merge 4: o + w -> ow  (seen 7 times)
merge 5: l + ow -> low  (seen 7 times)
merge 6: w + est_ -> west_  (seen 6 times)
merge 7: n + e -> ne  (seen 6 times)
merge 8: ne + west_ -> newest_  (seen 6 times)

low _   x5
low e r _   x2
newest_   x6
w i d est_   x3

Look at the result. "newest" became one token because it is frequent. "lower" is still "low", "e", "r", because "lower" was rare. Real tokenizers learn tens of thousands of merges from far more text.

Interviewers look for: you can run the merge loop on paper, and you know that the number of merges is the main setting.

4. What is a context window, and what happens when you run past it?

Answer: The context window is the maximum number of tokens the model can take in at once. It covers your prompt, any documents you paste in, the chat history, and the reply being written. GPT-3 used a window of 2,048 tokens. Qwen2.5-7B's configuration file lists max_position_embeddings as 131,072. A request that is longer than the limit cannot be sent as it is, so your application must cut or summarise text. The model has no memory outside the window. Anything you want it to use must be inside.

Interviewers look for: the point that input and output share the window, and that a bigger window raises memory and cost (see question 23).

5. What is an embedding layer in an LLM?

Answer: The model works on numbers, not text. Each token ID is used as a row number in a big table, and that row is a vector of numbers (Qwen2.5-7B uses 3,584 per token). That vector is the token's embedding. The table is learned during training, so tokens used in similar ways end up with similar vectors. The embedding is where a token enters the transformer. The table is part of the model's parameters. Do not confuse it with a text-embedding model used for search. Sentence embeddings, cosine similarity and vector search are covered in the RAG interview questions.

Interviewers look for: a lookup table indexed by token ID, learned with the rest of the model.

6. What does "7B" mean, and is a bigger model always better?

Answer: "7B" means about seven billion parameters, the learned numbers inside the network. More parameters give more capacity, but size is not the whole story. Kaplan et al. (2020) found that loss "scales as a power-law with model size, dataset size, and the amount of compute used for training". So you need more data and compute along with more parameters, and each doubling gives a smaller gain. A bigger model also needs more memory, runs slower and costs more per token. Size is not everything: in the InstructGPT paper, a tuned 1.3B model was preferred over the 175B GPT-3 (question 17).

Interviewers look for: you name the cost side (memory, latency, price) and not only the quality side.

The transformer: attention and position

7. Why did transformers replace recurrent networks for language?

Answer: A recurrent network (RNN) reads one token at a time and passes a summary forward, so it cannot process a whole sentence in parallel. The transformer, introduced in "Attention Is All You Need" (Vaswani et al., 2017), is "based solely on attention mechanisms, dispensing with recurrence and convolutions entirely". Every token can look at every other token in one step, and all positions are computed together on a GPU. The paper reports models that were "more parallelizable and requiring significantly less time to train". That made it practical to train on far more text.

Interviewers look for: parallel training and direct token-to-token links, not just "it is more accurate".

8. Explain self-attention step by step.

Answer: Each token's vector is turned into three vectors: a query (what am I looking for), a key (what do I offer) and a value (what I pass on). For one token, take the dot product of its query with every key. Divide by the square root of the key size, apply softmax to get weights that add up to 1, and take the weighted sum of the values. The result is a new vector for that token that blends information from the tokens it attends to. The paper's formula is softmax(QKᵀ/√d_k)V.

The program does this for three tokens with 2-number vectors. It prints the weights each token gives to the others, first with full attention and then with a causal mask (question 13).

# attention.py: scaled dot-product attention for 3 tokens, d_k = 2
import math

Q = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]   # one query per token
K = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]   # one key per token
V = [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]   # one value per token
d_k = 2

def softmax(xs):
    m = max(xs)
    es = [math.exp(x - m) for x in xs]
    return [e / sum(es) for e in es]

def attend(causal):
    for i, q in enumerate(Q):
        scores = [sum(a * b for a, b in zip(q, k)) / math.sqrt(d_k) for k in K]
        if causal:
            scores = [s if j <= i else float("-inf") for j, s in enumerate(scores)]
        w = softmax(scores)
        out = [sum(w[j] * V[j][c] for j in range(3)) for c in range(2)]
        print(f"token {i}: weights {[round(x, 3) for x in w]} -> output {[round(x, 3) for x in out]}")

print("full attention (encoder style)")
attend(causal=False)
print("causal attention (decoder style)")
attend(causal=True)

Output:

full attention (encoder style)
token 0: weights [0.401, 0.198, 0.401] -> output [3.0, 4.0]
token 1: weights [0.198, 0.401, 0.401] -> output [3.407, 4.407]
token 2: weights [0.248, 0.248, 0.503] -> output [3.51, 4.51]
causal attention (decoder style)
token 0: weights [1.0, 0.0, 0.0] -> output [1.0, 2.0]
token 1: weights [0.33, 0.67, 0.0] -> output [2.34, 3.34]
token 2: weights [0.248, 0.248, 0.503] -> output [3.51, 4.51]

Read the first line of each block. In full attention, token 0 spreads its weight over all three tokens. With the causal mask, token 0 can only see itself, so its output is its own value, [1.0, 2.0].

Interviewers look for: query, key and value roles, softmax over keys, and the weighted sum of values. Being able to write it in a few lines of code is a plus.

9. Why divide by the square root of d_k?

Answer: When the vectors are long, dot products grow large. Large inputs push softmax into a state where one weight is almost 1 and the rest are almost 0. In that state the gradients, the signals used to train, become tiny. The paper says the authors suspected this and "counteract this effect" by scaling the dot products by 1/√d_k. The paper's footnote assumes the query and key numbers are independent with mean 0 and variance 1. a dot product of d_k pairs has variance d_k. Dividing by √d_k brings it back to about 1.

Interviewers look for: the link between scale, softmax saturation and training stability.

10. Why use multiple attention heads?

Answer: One attention head produces one set of weights per token, which is a single way of mixing information. Multi-head attention runs several heads in parallel, each with its own learned query, key and value projections, then joins their outputs. The paper says this "allows the model to jointly attend to information from different representation subspaces at different positions", and "with a single attention head, averaging inhibits this". The original model used h = 8 heads. Each head works on a smaller slice (the paper uses 64 numbers per head), so the total cost stays similar to one big head.

Interviewers look for: "different relationships at the same time", plus the fact that heads split the width, not multiply it.

11. Why does a transformer need positional encoding?

Answer: Attention alone has no sense of order. Shuffle the input tokens and it just shuffles the outputs, so "dog bites man" and "man bites dog" would look alike. The model needs order to be injected. The original paper adds "positional encodings" to the input embeddings, using sine and cosine waves of different wavelengths. It also tried learned position embeddings and found "nearly identical" results. Many newer LLMs use rotary embeddings instead, which we cover next. Other choices exist, but the point of all of them is the same: tell attention where each token sits.

Interviewers look for: the permutation problem stated clearly, and a name for at least two schemes.

12. What is RoPE, and why is it so widely used? (For experienced)

Answer: Rotary Position Embedding (RoPE), from the RoFormer paper (Su et al., 2021), does not add position to the embedding. It rotates each query and key vector by an angle that grows with the token's position. After rotation, the dot product between a query at position m and a key at position n depends only on the offset m − n. The paper says RoPE "encodes the absolute position with a rotation matrix and meanwhile incorporates the explicit relative position dependency in self-attention formulation". It also notes a "decaying inter-token dependency with increasing relative distances". Qwen2.5-7B's configuration lists a rope_theta of 1,000,000, the base that sets the rotation speeds.

The program rotates a 2-number query and key. Same offset, different positions: same score.

# rope.py: rotary position embedding in 2 dimensions
import math

def rotate(vec, pos, theta=0.5):
    a = pos * theta                      # the angle grows with the position
    x, y = vec
    return (x * math.cos(a) - y * math.sin(a), x * math.sin(a) + y * math.cos(a))

q, k = (1.0, 2.0), (3.0, 1.0)
print(f"no rotation: q.k = {q[0] * k[0] + q[1] * k[1]:.4f}")
for m, n in [(3, 1), (10, 8), (100, 98), (10, 5)]:
    rq, rk = rotate(q, m), rotate(k, n)
    dot = rq[0] * rk[0] + rq[1] * rk[1]
    print(f"query at {m:>3}, key at {n:>3}, offset {m - n}: q.k = {dot:.4f}")

Output:

no rotation: q.k = 5.0000
query at   3, key at   1, offset 2: q.k = -1.5058
query at  10, key at   8, offset 2: q.k = -1.5058
query at 100, key at  98, offset 2: q.k = -1.5058
query at  10, key at   5, offset 5: q.k = -6.9981

The score is -1.5058 whenever the offset is 2, at positions 3 and 1 or 100 and 98. It changes to -6.9981 for offset 5. Real models rotate many pairs of numbers, each at a different speed.

Interviewers look for: relative position from an absolute rotation, and awareness that a setting like rope_theta controls the rotation speeds.

13. Decoder-only, encoder-only, encoder-decoder: what is the difference?

Answer: An encoder reads the whole input with every token seeing every other token. BERT is encoder-only, built for understanding tasks like classification, and it learns by filling in masked words. A decoder generates text left to right, and a causal mask stops each position from attending to later ones. The original transformer had both: an encoder for the source sentence and a decoder for the translation. GPT-style models, including most chat models, are decoder-only. They use one stack, with the prompt and the reply in the same sequence. The mask is what makes next-token training and generation consistent.

Interviewers look for: the causal mask, and a reason decoder-only suits a general chat model (one simple objective, one stack).

Training: from raw text to a helpful assistant

14. How is an LLM pretrained?

Answer: Pretraining shows the model a very large amount of text. GPT-3's training data, for example, was built mainly from filtered Common Crawl web pages plus other text sources. At each position it predicts the next token. A wrong guess adds to a loss, and the optimiser adjusts the parameters to reduce it. No human labels are needed, because the next token in the text is the label. This is self-supervised learning. After pretraining you have a base model. It continues text well but does not reliably follow instructions or refuse harmful requests. Chat behaviour comes from the later stages described below.

Interviewers look for: self-supervision, and the difference between a base model and a chat model.

15. What are cross-entropy loss and perplexity?

Answer: For each position, cross-entropy loss is the negative log of the probability the model gave to the correct next token. Average it over positions. A confident correct guess gives a loss near 0, and a confident wrong guess gives a large loss. Perplexity is the exponential of that average. Hugging Face's docs define it as "the exponentiated average negative log-likelihood of a sequence". Read it as "the model is as unsure as if it were choosing between this many equally likely tokens". Lower is better. Perplexity values from models with different tokenizers are not comparable.

# loss.py: cross-entropy and perplexity from the probability given to each correct token
import math

# the model's probability for the true next token, at each of 5 positions
good_model = [0.50, 0.40, 0.25, 0.60, 0.30]
bad_model = [0.05, 0.02, 0.10, 0.01, 0.04]
V = 50_000   # vocabulary size for the "knows nothing" baseline

def cross_entropy(ps):
    return -sum(math.log(p) for p in ps) / len(ps)

for name, ps in [("good model", good_model), ("bad model", bad_model)]:
    ce = cross_entropy(ps)
    print(f"{name}: cross-entropy {ce:.4f} nats, perplexity {math.exp(ce):.2f}")

ce = cross_entropy([1 / V] * 5)
print(f"uniform over {V:,} tokens: cross-entropy {ce:.4f} nats, perplexity {math.exp(ce):,.0f}")

Output:

good model: cross-entropy 0.9421 nats, perplexity 2.57
bad model: cross-entropy 3.4069 nats, perplexity 30.17
uniform over 50,000 tokens: cross-entropy 10.8198 nats, perplexity 50,000

The good model behaves like a choice between about 2.6 tokens at each step. The bad model is like choosing between 30. A model that knows nothing and spreads probability evenly over 50,000 tokens has a perplexity of exactly 50,000.

Interviewers look for: the formula, the intuition for perplexity, and the tokenizer caveat.

16. What is supervised fine-tuning (SFT)?

Answer: SFT continues training a base model on examples of the behaviour you want: a prompt and an ideal reply. The loss is still next-token prediction, now computed on the replies. In the InstructGPT paper (Ouyang et al., 2022), labelers wrote demonstrations of desired behaviour, "which we use to fine-tune GPT-3 using supervised learning". This teaches the model the format of an assistant: answer the question, follow the instruction. In InstructGPT the SFT set had about 13,000 training prompts, which is tiny next to pretraining, so the quality of each example matters a lot. SFT alone does not tell the model which of two decent answers people prefer.

Interviewers look for: SFT as the step that turns a text continuer into an assistant, and the data-quality point.

17. What are the steps of RLHF?

Answer: Reinforcement learning from human feedback (RLHF) has three steps in the InstructGPT paper. First, SFT on human-written demonstrations. Second, collect "a dataset of rankings of model outputs" where people rank several answers to one prompt, and train a reward model to predict those rankings. Third, fine-tune the model with reinforcement learning (PPO) to score high on the reward model, while a per-token KL penalty from the SFT model keeps it from drifting far. The paper's headline result: outputs from the 1.3B InstructGPT model "are preferred to outputs from the 175B GPT-3", with 100 times fewer parameters.

Interviewers look for: the three stages in order, and what the reward model is.

18. RLHF vs DPO: what changes? (For experienced)

Answer: DPO (Direct Preference Optimization, Rafailov et al., 2023) skips the separate reward model and the reinforcement learning loop. It trains on pairs of a preferred and a rejected answer. Its authors call RLHF "a complex and often unstable procedure" and show the same objective can be solved "with only a simple classification loss". Training uses no sampling from the model and little hyperparameter tuning. The trade-off: DPO learns from a fixed set of preference pairs, while RLHF can keep generating new outputs and scoring them. Which works better depends on the data and the task, so test both when you can.

Interviewers look for: "no reward model, no RL loop, a classification loss on pairs", and an honest note that it is not strictly better.

19. What do scaling laws say, and why do they matter? (For experienced)

Answer: Scaling laws are measured relationships between loss and the size of the model, the data and the compute. Kaplan et al. (2020) found loss follows "a power-law" in each, "with some trends spanning more than seven orders of magnitude". They also found that "other architectural details such as network width or depth have minimal effects within a wide range". A power law means steady but shrinking returns: you must multiply compute to keep lowering the loss. Labs use the curves to plan training runs before spending the money. The limit is that loss is not the same as usefulness on your task.

Interviewers look for: the three factors, the diminishing-returns shape, and caution about reading loss as quality.

Inference: how text is generated

20. What does temperature do?

Answer: The model outputs a raw score, a logit, for each token. Softmax turns the scores into probabilities. Temperature divides the logits before softmax. A temperature below 1 sharpens the distribution, so the top token dominates. Above 1 it flattens, so unlikely tokens get a real chance. Temperature near 0 approaches always picking the top token. It does not add knowledge. A high temperature gives more varied text and more mistakes. Holtzman et al. (2019) describe temperature as a way "to control the shape of the distribution".

# sampling.py: temperature, top-k and top-p on fixed logits
import math

tokens = ["Paris", "Lyon", "France", "city", "the", "banana"]
logits = [4.0, 2.5, 2.0, 1.5, 1.0, -1.0]

def softmax(xs, temperature=1.0):
    scaled = [x / temperature for x in xs]
    m = max(scaled)
    es = [math.exp(x - m) for x in scaled]
    return [e / sum(es) for e in es]

def show(label, probs):
    print(f"{label:<16}" + "  ".join(f"{t} {p:.3f}" for t, p in zip(tokens, probs)))

for t in (0.5, 1.0, 2.0):
    show(f"T = {t}", softmax(logits, t))

def top_k(probs, k):
    keep = sorted(range(len(probs)), key=lambda i: -probs[i])[:k]
    kept = [probs[i] if i in keep else 0.0 for i in range(len(probs))]
    return [p / sum(kept) for p in kept]

def top_p(probs, p):
    order = sorted(range(len(probs)), key=lambda i: -probs[i])
    keep, total = set(), 0.0
    for i in order:
        keep.add(i); total += probs[i]
        if total >= p:
            break
    kept = [probs[i] if i in keep else 0.0 for i in range(len(probs))]
    return [x / sum(kept) for x in kept]

base = softmax(logits)
show("top-k, k = 3", top_k(base, 3))
show("top-p, p = 0.8", top_p(base, 0.8))
print("greedy picks:", tokens[max(range(len(base)), key=lambda i: base[i])])

Output:

T = 0.5         Paris 0.928  Lyon 0.046  France 0.017  city 0.006  the 0.002  banana 0.000
T = 1.0         Paris 0.668  Lyon 0.149  France 0.090  city 0.055  the 0.033  banana 0.005
T = 2.0         Paris 0.411  Lyon 0.194  France 0.151  city 0.118  the 0.092  banana 0.034
top-k, k = 3    Paris 0.736  Lyon 0.164  France 0.100  city 0.000  the 0.000  banana 0.000
top-p, p = 0.8  Paris 0.818  Lyon 0.182  France 0.000  city 0.000  the 0.000  banana 0.000
greedy picks: Paris

Read the first three rows. At T = 0.5, "Paris" gets 92.8%. At T = 2.0 it gets 41.1%, and even "banana" gets 3.4%.

Interviewers look for: the divide-before-softmax detail and the effect at both ends.

21. What are top-k and top-p (nucleus) sampling?

Answer: Both cut off the unlikely tail before sampling. Top-k keeps the k most likely tokens. Top-p keeps the smallest set of tokens whose probabilities add up to at least p, so the set grows when the model is unsure and shrinks when it is sure. Holtzman et al. (2019) proposed it, "sampling from the dynamic nucleus of tokens containing the vast majority of the probability mass". After cutting, the remaining probabilities are rescaled to add up to 1. In the last two rows above, top-k with k = 3 keeps three tokens. Top-p with p = 0.8 keeps only "Paris" and "Lyon", because together they hold 81.7%.

Interviewers look for: why a fixed k is awkward (the right number changes per step) and how p adapts.

22. Greedy decoding, sampling and beam search: when do you use each?

Answer: Greedy decoding always takes the most likely token. It is repeatable and good for extraction or classification, but it can get stuck in loops. Sampling draws from the distribution, so output varies, which suits writing and brainstorming. Beam search keeps several candidate sequences and picks the best overall. The original transformer paper used beam search with a beam size of 4 for translation. For open-ended text, Holtzman et al. found that "maximization-based decoding methods such as beam search lead to degeneration", meaning text that is "bland, incoherent, or gets stuck in repetitive loops".

Interviewers look for: a choice tied to the task, and the awareness that beam search suits translation better than open chat.

23. What is a KV cache, and how big can it get?

Answer: When the model writes token n, attention needs the keys and values of all earlier tokens. Recomputing them for every new token would repeat work. A KV cache stores them. The vLLM paper (Kwon et al., 2023) describes two phases. The prompt is processed in parallel, which also generates its key and value vectors. Then tokens come one by one, which "makes the workload memory-bound". The cache size is 2 (key and value) × layers × KV heads × head dimension × tokens × bytes per number. The cache grows with every token and every user in the batch.

The program uses real numbers from Qwen2.5-7B's config.json: 28 layers, 28 attention heads, 4 key-value heads and a hidden size of 3,584. That gives a head size of 3,584 ÷ 28 = 128. Values are stored in bfloat16, 2 bytes each.

# kv_cache.py: KV cache size for Qwen2.5-7B, using values from its config.json
layers = 28                 # num_hidden_layers
q_heads = 28                # num_attention_heads
kv_heads = 4                # num_key_value_heads
head_dim = 3584 // q_heads  # hidden_size / num_attention_heads = 128

def kv_bytes(tokens, heads, bytes_per_value):
    # 2 = one key vector and one value vector per token, per layer, per KV head
    return 2 * layers * heads * head_dim * tokens * bytes_per_value

per_token = kv_bytes(1, kv_heads, 2)
print(f"head_dim = {head_dim}, bf16 KV cache per token = {per_token:,} bytes ({per_token / 1024:.0f} KiB)")
print(f"{'tokens':>8} {'GQA, 4 KV heads':>16} {'MHA, 28 heads':>14} {'GQA, 8-bit':>11}")
for n in (4_096, 32_768, 131_072):
    gqa = kv_bytes(n, kv_heads, 2) / 2**30
    mha = kv_bytes(n, q_heads, 2) / 2**30
    q8 = kv_bytes(n, kv_heads, 1) / 2**30
    print(f"{n:>8,} {gqa:>12.2f} GiB {mha:>10.2f} GiB {q8:>7.2f} GiB")

Output:

head_dim = 128, bf16 KV cache per token = 57,344 bytes (56 KiB)
  tokens  GQA, 4 KV heads  MHA, 28 heads  GQA, 8-bit
   4,096         0.22 GiB       1.53 GiB    0.11 GiB
  32,768         1.75 GiB      12.25 GiB    0.88 GiB
 131,072         7.00 GiB      49.00 GiB    3.50 GiB

At the full 131,072 tokens, one request needs 7 GiB just for its cache. A GiB is 1,073,741,824 bytes. The "MHA" column shows what it would be if the model kept all 28 key-value heads: 49 GiB. That gap is the subject of the next question.

Interviewers look for: the formula, and the fact that the cache, not the weights, becomes the limit at long context or high traffic.

24. What are multi-query and grouped-query attention? (For experienced)

Answer: In standard multi-head attention, each query head has its own key and value head. Multi-query attention (MQA) shares one key-value head across all query heads. The GQA paper (Ainslie et al., 2023) says MQA "drastically speeds up decoder inference" but "can lead to quality degradation". Grouped-query attention (GQA) sits in between: "an intermediate (more than one, less than number of query heads) number of key-value heads". Qwen2.5-7B has 28 query heads sharing 4 key-value heads, so seven query heads per group. The KV cache shrinks seven times, which the table above shows. The paper reports quality "close to multi-head attention" with "comparable speed to MQA".

Interviewers look for: the three variants on one spectrum, and the KV cache saving as the reason.

25. What is quantization, and what does it cost?

Answer: Quantization stores weights with fewer bits, for example 8-bit integers in place of 16-bit floats. The simplest version, absmax, picks one scale so the largest weight maps to 127, then rounds every weight to an integer. To use a weight again, multiply the integer by the scale. You lose a little precision and save a lot of memory. The LLM.int8() paper (Dettmers et al., 2022) shows 8-bit inference is possible "without any performance degradation" for models up to 175B parameters. It had to handle rare large "outlier" features in 16-bit. Lower bit widths, like 4-bit, save more but risk more quality loss.

# quantize.py: absmax int8 quantization of a few weights, and what it does to memory
weights = [0.123, -0.8047, 0.331, 1.27, -0.052, 0.6411]

scale = max(abs(w) for w in weights) / 127          # one scale for the whole group
q = [round(w / scale) for w in weights]             # integers in -127..127
back = [v * scale for v in q]
print(f"scale = {scale:.5f}")
print("int8 values:", q)
for w, b in zip(weights, back):
    print(f"  {w:>7.4f} -> {b:>8.4f}  error {abs(w - b):.4f}")

n = 7_000_000_000   # a 7-billion-weight model, to keep the sums round
for name, bits in [("fp32", 32), ("bf16/fp16", 16), ("int8", 8), ("int4", 4)]:
    print(f"{name:<10} {n * bits / 8 / 1e9:>5.1f} GB for the weights")

Output:

scale = 0.01000
int8 values: [12, -80, 33, 127, -5, 64]
   0.1230 ->   0.1200  error 0.0030
  -0.8047 ->  -0.8000  error 0.0047
   0.3310 ->   0.3300  error 0.0010
   1.2700 ->   1.2700  error 0.0000
  -0.0520 ->  -0.0500  error 0.0020
   0.6411 ->   0.6400  error 0.0011
fp32        28.0 GB for the weights
bf16/fp16   14.0 GB for the weights
int8         7.0 GB for the weights
int4         3.5 GB for the weights

Each weight comes back within 0.005 of the original. Memory is simple arithmetic: parameters × bits ÷ 8. A 7-billion-weight model needs 14 GB in 16-bit and 3.5 GB in 4-bit, before counting the KV cache and activations.

Interviewers look for: the scale-and-round idea, the memory sum, and awareness that outliers and low bit widths hurt accuracy.

Practical: failures, safety, evaluation and cost

26. Why do LLMs hallucinate, and what reduces it?

Answer: A hallucination is a fluent statement that is false. The model is trained to produce likely text, and a likely sentence is not always a true one. Kalai et al. (2025) argue that "the training and evaluation procedures reward guessing over acknowledging uncertainty", like students facing hard exam questions who guess when unsure. Mitigations reduce the problem and do not remove it. Give the model the facts in the prompt and ask it to cite them. Allow "I don't know". Check outputs against a source or a tool, and keep the temperature low for factual tasks.

Interviewers look for: "plausible, not verified" as the root cause, and layered mitigations rather than one fix.

27. When would you add RAG instead of changing the model?

Answer: Add retrieval-augmented generation (RAG) when the model lacks facts, such as your private documents or anything newer than its training data. RAG fetches relevant passages at query time and puts them in the prompt, so you can update the knowledge without retraining and show sources. Fine-tuning is better for behaviour, such as a fixed output format or tone. Start with a clear prompt, add RAG for missing facts, and fine-tune only when the model has the facts but behaves inconsistently. The full comparison is in RAG vs fine-tuning vs prompt engineering, and the follow-up questions are in the RAG interview questions.

Interviewers look for: facts versus behaviour as the deciding question.

28. How is an agent different from a plain LLM call?

Answer: A plain call sends a prompt and gets text back. An agent runs the model in a loop where it can call tools, such as a search or a database query, read the results and decide the next step. Your code runs the tools, not the model. Agents handle multi-step tasks but cost more tokens, are slower and fail in more ways. If a fixed sequence of steps solves the task, use that rather than an agent. The loop, tool calling and safety limits are covered in the agentic AI interview questions.

Interviewers look for: the one-line difference, and the instinct not to build an agent when a simple workflow will do.

29. How would you evaluate an LLM for your use case? (For experienced)

Answer: Do not rely on a public leaderboard alone. Kalai et al. argue that the benchmarks that dominate leaderboards are graded in a way that rewards guessing, so a high score does not show an honest model. Build a test set from your own tasks: real inputs and the answers you accept. Where answers are checkable, score with code, such as exact match, a regex or running the generated code against tests. Where they are not, use human review on a sample, and add an LLM judge only after checking it against humans. Re-run the set whenever you change the model, the prompt or the settings.

Interviewers look for: your own data, a mix of automatic and human checks, and a regression habit.

30. What drives LLM cost and latency, and how do you reduce them? (For experienced)

Answer: Cost grows with the tokens you send and the tokens you generate. Latency has two parts. The prompt is processed in parallel, which is fast per token. Generation is sequential, one token at a time, and as the vLLM paper puts it, this makes the workload memory-bound. So long outputs are slow, and a long prompt adds work in the parallel prompt phase before the first token appears. Ways to cut both: shorter prompts, a smaller model for easy requests and capped output length. A quantized model helps, and so does a smaller KV cache through GQA. Servers also batch many requests together.

Interviewers look for: the two phases (prompt versus generation) and a lever for each, not "use a faster GPU".

Where this knowledge breaks: limits to admit in an interview

  • The explanations are simplified. Real models add layer normalisation, feed-forward blocks and residual connections around attention. The programs show the core idea, not a production model.
  • Training details differ between labs. Many are not published. Papers describe how GPT-3 and InstructGPT were trained, and newer models may differ. Say "in the InstructGPT paper" and not "ChatGPT does".
  • No program here calls a real model. The probabilities and logits are made up so you can verify them by hand. Real distributions are much larger and messier.
  • The KV cache figures are for one request, one config, one precision. Real servers add overhead, and the weights need memory as well.
  • Sampling settings are not a safety tool. Lower temperature reduces variety, not wrong answers or prompt injection. OWASP's LLM01:2025 says a prompt injection occurs when user prompts "alter the LLM's behavior or output in unintended ways". Treat model output as untrusted input, and never put secrets in a prompt. The same OWASP list names sensitive information disclosure as a separate risk.

How to prepare in two weeks

  1. Days 1-3: tokens and attention. Re-type the BPE and attention programs from memory. Then run a real tokenizer such as tiktoken on your own sentences and look at the splits.
  2. Days 4-6: training. Read the abstracts of the transformer, InstructGPT and DPO papers. Write each in three sentences of your own.
  3. Days 7-9: inference. Change the logits in the sampling program and predict the output before you run it. Do the same for the KV cache with another model's configuration file.
  4. Days 10-12: build something. Call a hosted or local model from Python. Log tokens in and out, and write a ten-question test set for it.
  5. Days 13-14: mock interview. Answer ten questions from this list aloud, in 60 seconds each, with one example per answer.

Freshers should be solid on questions 1 to 11, 14, 15, 20 and 21. Experienced candidates should also expect 12, 18, 19, 24, 29 and 30, plus a project story with numbers.

FAQ

What are the most asked LLM interview questions?

Expect "what is a token", how self-attention works, why divide by the square root of d_k, the difference between pretraining and fine-tuning, and what temperature does. Many interviewers also ask about hallucination, context windows and how you would evaluate a model. Practise each answer with one small example.

What LLM interview questions are asked to freshers?

Freshers get the basics: what an LLM is, tokens and tokenization, embeddings, the transformer, self-attention, pretraining, temperature and hallucination. Interviewers want a clear explanation in plain words and a simple example. Few will ask for maths beyond softmax and dot products. A small project you built helps more than memorised definitions.

What LLM interview questions are asked to experienced candidates?

Experienced candidates face design and trade-off questions: RoPE and long context, grouped-query attention and KV cache memory, RLHF versus DPO, quantization, evaluation on your own data, and cost and latency. Expect "how would you choose a model for this task" and a detailed walk-through of one project you shipped.

Is there a PDF or GitHub repo of LLM interview questions?

Many repos and PDFs exist, but quality varies and few run the code. Check any answer against the original paper before you repeat it. This page works as a copy-paste study set: every program here runs as written. Save the page to PDF from your browser if you need an offline copy.

Do I need to know the maths of transformers for an interview?

You need the core pieces: dot products, softmax, the attention formula and what the loss measures. You rarely need to derive gradients. Be able to compute a small attention example by hand, and explain scaling by √d_k. For research roles, expect more depth. For application roles, tokens, cost and evaluation matter more.

What is the difference between an LLM and a chatbot?

An LLM is the model that predicts the next token. A chatbot is a product built around one: it adds a system prompt, chat history, safety rules and often tools or retrieval. The same LLM can power many chatbots. The chat behaviour of the model itself comes mainly from supervised fine-tuning and preference training.

Keep going

Read how to create your own Jarvis by learning LLMs to build a first assistant, and the future of AI for software developers for the career picture. For the retrieval side, see Crio's RAG explained walkthrough and the RAG interview questions. For agents, continue with the agentic AI interview questions.

If you want to build LLM apps, RAG systems and agents on real projects with mentor reviews, look at Crio's AI Engineering program.

You've successfully subscribed to Crio Blog
Great! Next, complete checkout to get full access to all premium content.
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Billing info update failed.