Employer interviews
Interviews are private. Sign in to see your group interviews.
Sign in…
This interview was not found. Maybe the data in this browser was cleared.
Interviews dashboardEasy questions are at the top, and harder ones sit under their basic question. If a basic question gets a weak score, the questions under it fade.
1. A hundred chats on one GPU
How LLM inference works· in roadmapGPU memory and parallelism· in roadmap
Question: Our shop runs its own support assistant on an open-weight 8B model. A teammate writes this capacity plan for the launch:
model: shop-assistant-8b # 8B parameters, stored in BF16
layers: 32
kv_heads: 8 # grouped-query attention
head_dim: 128
max_context: 32768 # tokens
gpu: 1 x 80 GB
plan: 100 chats at the same time, each may use the full context
The plan says: “The model is only 16 GB, so 80 GB is plenty.” What do you think? Is this plan OK?
Short answer: The plan counts only the weights and forgets the KV cache. Every token of every running chat keeps keys and values for every layer. Here that is about 128 KB per token, so one full 32k chat needs about 4 GB. One hundred full chats need about 400 GB, five times the whole GPU. After weights and runtime memory, only about 55 GB is left for the cache, so about 400,000 tokens in flight, or about 13 full-length chats. If real chats are short, it may still work, but the plan must use real chat lengths, and when the cache is full the engine will queue or pause requests.
Hint (if the candidate says there is no problem): When the model writes the next word, what does it need to remember about all the words before it? Where is that kept, and how big is it?
Why is this a problem? (step by step)
- Weights. 8 billion parameters × 2 bytes (BF16) = about 16 GB. This part the plan got right.
- KV cache per token. For each token, each layer stores one key and one value vector per KV head. That is 2 (key and value) × 32 layers × 8 heads × 128 numbers × 2 bytes = 131,072 bytes, about 128 KB.
- Per chat. A full chat of 32,768 tokens × 128 KB = about 4 GB.
- For the plan. 100 full chats × 4 GB = about 400 GB. One GPU has 80 GB.
- What is really free. 80 GB minus 16 GB weights, minus a few GB for the runtime and temporary work, leaves roughly 55 GB. Divided by 128 KB, that is about 400,000 tokens for all chats together.
- What happens when it is full. The serving engine cannot start new requests, or must pause and later redo some. Users see long waits, not an error message.
The fix: what I would do
- Use real numbers. Look at the length of real chats (prompt plus history plus answer). If the average is 2,000 tokens, 400,000 tokens is about 200 chats, and the plan is fine for the average, but not for the long tail.
- Set a lower max context if the product does not need 32k, for example trim or summarize old history.
- Make the cache smaller. An FP8 KV cache halves its size, if the hardware and engine support it and the evals stay good.
- Add GPUs or replicas when real peak traffic needs more tokens in flight than one GPU can hold.
- Watch it. Track KV cache usage and waiting requests on the dashboard, and alert before it is full.
Follow-up question: Why does this model have 8 KV heads and not one KV head per query head? What would change with 32 KV heads?
Follow-up answer:
- The model uses grouped-query attention (GQA): several query heads share one key and value head. That keeps quality close to full attention but makes the KV cache much smaller.
- With 32 KV heads, every number above would be 4 times larger: about 512 KB per token and about 16 GB for one full chat. Only about three full chats would fit.
- So the model’s architecture is a big part of serving cost, not only its parameter count.
Red flag: Counts only the model size, or says “the GPU will handle it”. Another red flag: knows the words “KV cache” but cannot estimate its size from the model’s config.
Show answer
2. One request at a time
How LLM inference works· in roadmapBatching and caching for LLM serving· in roadmap
Question: A teammate built the first server for our shop assistant with Hugging Face Transformers and FastAPI:
lock = asyncio.Lock()
@app.post("/chat")
async def chat(req: ChatRequest):
async with lock: # the GPU can run one thing at a time
ids = tokenizer(req.prompt, return_tensors="pt").to("cuda")
out = model.generate(**ids, max_new_tokens=512)
return {"text": tokenizer.decode(out[0])}
It works well in the demo. At peak we expect about 50 people chatting at the same time. What do you think?
Short answer: The lock makes the GPU serve one request at a time, so with 50 users most of them wait in a queue while the GPU is mostly idle. Writing one token for 1 request or for 30 requests costs almost the same time, because each step is limited by reading the weights from memory, not by math. The “generate” call is also blocking inside an async function, so the whole server freezes while it runs. There is no streaming, and the answer includes the prompt text. I would use a serving engine with continuous batching, such as vLLM or SGLang, and stream the answer.
Hint (if the candidate says there is no problem): Each answer takes about 8 seconds. What does the 50th person see? And what does the GPU usage graph look like?
Why is this a problem? (step by step)
- A queue of people. One answer takes about 8 seconds. The 50th user waits about 400 seconds before their answer even starts.
- The GPU is underused. In each decode step the GPU reads all 16 GB of weights to write one token. Writing one token for 30 requests in the same step reads the weights only once. So one-at-a-time wastes most of the GPU.
- The event loop is blocked. “model.generate” is normal blocking code inside “async def”. While it runs, FastAPI cannot even answer a health check.
- No streaming. The user sees nothing for 8 seconds, then the whole answer.
- Small bugs. For this kind of model, “generate” returns the prompt tokens plus the new tokens, so the reply repeats the prompt. Special tokens are not removed.
- No limits. No timeout, no limit on prompt size, no cancel when the user leaves.
The fix: what I would do
- Use a serving engine made for this: vLLM, SGLang or TensorRT-LLM. They batch many requests in each step (continuous batching), manage the KV cache in pages, and offer an OpenAI-compatible API.
- Stream tokens to the user so the first words appear fast.
- Keep the app server thin. It checks the user, builds the prompt, calls the engine, and streams back.
- Set limits: max prompt length, max output tokens, request timeout.
- Load test with 50 parallel users and measure time to first token and tokens per second per user.
Follow-up question: Why not just remove the lock and let FastAPI call “generate” from many threads?
Follow-up answer:
- The calls would fight over the same GPU. Each would still run its own small batch of one, so we do not get the batching win.
- Each call keeps its own memory, so we can run out of GPU memory in an uncontrolled way.
- Real batching needs a scheduler that adds and removes requests at each step and manages the KV cache. That is exactly what serving engines do, so we should not build it again.
Red flag: Suggests “buy a bigger GPU” or “add more replicas” without seeing that one GPU is serving one user at a time. Another red flag: does not notice the blocking call inside async code.
Show answer
3. A bigger batch, a big win?
How LLM inference works· in roadmapRunning LLM serving in production· in roadmap
Question: Last week a teammate changed one setting of our serving engine and posted this in the team chat:
| Setting: max running requests | Throughput (output tokens per second, whole GPU) |
|---|---|
| 16 (before) | 1,800 |
| 128 (after) | 5,200 |
“Almost 3 times more throughput on the same GPU. Big win!” The same week, support says customers complain that the chat “feels slow”. What do you think?
Short answer: Throughput for the whole GPU went up, but the table says nothing about each user. A bigger batch makes every decode step slower, so each user gets fewer tokens per second, and new requests may wait longer for their first token. We need user-facing numbers: time to first token (TTFT) and time per output token (TPOT) at p95 and p99, under real traffic. Then we pick the batch size that gives the most throughput while still meeting a latency target, not the largest throughput.
Hint (if the candidate says there is no problem): 5,200 tokens per second shared by 128 requests is how many tokens per second for one user? And how many for 16 requests sharing 1,800?
Why is this a problem? (step by step)
- Per user speed went down. 1,800 / 16 is about 112 tokens per second for each user. 5,200 / 128 is about 40 tokens per second. That is almost 3 times slower for each person.
- Wait for the first token. With more requests in each step, a new prompt competes with many running answers. TTFT can grow, especially at busy times.
- Averages hide the pain. Even if the average is fine, the slowest 5 percent of users (p95) feel it the most, and they are the ones who complain.
- Throughput alone is the wrong goal. It is a cost number. Users feel latency. We need both.
The fix: what I would do
- Agree on targets (SLOs) with product, for example: TTFT p95 under 1 second, TPOT p95 under 50 ms (about 20 tokens per second, faster than people read).
- Measure goodput: throughput counting only requests that met the targets.
- Run a sweep: load test with real prompts at batch limits 16, 32, 64, 128, and draw a chart of throughput and p95 latency.
- Pick the setting with the best throughput that still meets the targets. Add replicas if the traffic needs more.
- Put TTFT and TPOT p95 on the dashboard, next to throughput, so this cannot happen again unseen.
Follow-up question: Product wants both: fast chat for customers and cheap nightly jobs that summarize 200,000 reviews. How do you handle that?
Follow-up answer:
- These are two workloads with different goals. Chat needs low latency. The batch job needs high throughput and does not care about one request’s speed.
- I would run the nightly job with large batches, at night when chat traffic is low, or on separate replicas, or through a low-priority queue.
- Then each workload gets settings tuned for its own target.
Red flag: Accepts “more tokens per second” as the only success number. Another red flag: talks about average latency only, never about p95 or p99.
Show answer
4. A big model on two GPUs
GPU memory and parallelism· in roadmapQuantization· in roadmap
Question: The evals show that a bigger open-weight 70B model answers hard support questions much better. A teammate wants to move to it with the GPUs we already have:
model: shop-assistant-70b # 70B parameters, BF16
layers: 80
kv_heads: 8
head_dim: 128
gpus: 2 x 80 GB, connected over PCIe (no NVLink)
tensor_parallel: 2
max_context: 32768
plan: same traffic as today, about 50 chats at the same time
“The weights are 140 GB and we have 160 GB, so it fits.” What do you think?
Short answer: It fits only the weights. About 140 GB of 160 GB goes to weights, and after runtime memory only about 10 to 12 GB is left for the KV cache. This model needs about 320 KB per token, so that is about 35,000 tokens for all chats together, roughly one full 32k chat or 15 short ones, not 50. Also, tensor parallelism sends data between the GPUs in every layer for every token. Over PCIe without NVLink, that is slow and adds latency. Options: FP8 weights (about 70 GB, if the GPUs support FP8 and evals stay good), more GPUs with fast links, or use the big model only for the hard questions.
Hint (if the candidate says there is no problem): After the weights, how much memory is left for each chat? And how often do the two GPUs need to talk to each other?
Why is this a problem? (step by step)
- Weights. 70 billion × 2 bytes = about 140 GB, split over two GPUs: 70 GB each.
- What is left. Each GPU has 80 GB. After 70 GB of weights and some GB for the runtime, maybe 5 to 6 GB is left on each, about 10 to 12 GB in total.
- KV cache per token. 2 × 80 layers × 8 heads × 128 × 2 bytes = 327,680 bytes, about 320 KB.
- Tokens in flight. About 11 GB / 320 KB = about 35,000 tokens. One full 32k chat alone needs about 10.7 GB.
- Result. Most requests wait in the queue. The plan of 50 chats does not work.
- Communication. With tensor parallelism, each layer is split over both GPUs, and they must combine results (an all-reduce) inside every layer, for every decode step. PCIe is many times slower than NVLink, so each token takes longer.
The fix: what I would do
- Do the math first: weights + KV cache for real chat lengths + runtime memory, for the target traffic.
- FP8 weights. About 70 GB for the whole model. On two GPUs that leaves roughly 80 GB for the KV cache, about 250,000 tokens. This needs GPUs and kernels with FP8 support, and an eval run to check quality.
- Better hardware layout. GPUs connected with NVLink for tensor parallelism, or more GPUs. With only PCIe, test pipeline parallelism too: it sends less data between GPUs, but it has its own costs.
- Route by difficulty. Keep the 8B model for most questions, and send only hard ones to the 70B model. Measure how many are “hard”.
- Load test the final setup with real traffic before switching.
Follow-up question: What is the difference between tensor parallelism and pipeline parallelism, in simple words?
Follow-up answer:
- Tensor parallelism cuts each layer into parts. Every GPU does part of every layer, and they talk inside every layer. It lowers latency, but needs a very fast link.
- Pipeline parallelism gives whole layers to each GPU: layers 1 to 40 on GPU 1, layers 41 to 80 on GPU 2. They talk only at the border. It needs less bandwidth, but one request goes through the GPUs one after another, so without enough parallel work some GPUs wait.
- Common practice: tensor parallelism inside one machine with NVLink, pipeline parallelism across machines.
Red flag: Says “it fits” after counting only the weights. Another red flag: does not know that GPUs in tensor parallelism must talk in every layer.
Show answer
5. INT4 looks the same
Quantization· in roadmapLLM evaluation (evals)· in roadmap
Question: A Pull Request changes one line in our serving config for the 8B shop assistant:
model: shop-assistant-8b
quantization: int4-awq # was: none (BF16)
The description says: “INT4 weights are 4 times smaller. I tested 20 prompts by hand and the answers look the same. This should cut our GPU cost in half.” About 40 percent of our customers write in Persian, and the assistant often fills a JSON form for returns. What do you think?
Short answer: INT4 can be a good idea, but this PR does not prove quality or cost. Twenty hand-picked prompts are not an eval. Quality loss from quantization is often small on average but larger in some areas: math, code, long context, strict formats like our JSON, and some non-English languages. Speed is also not automatic: weight-only INT4 helps most when decoding is memory-bound at small batches. At large batches the win can be much smaller. And “half the cost” assumes we use the freed memory for more requests. I would run our eval set split by language and task, and a load test at our latency targets, before and after.
Hint (if the candidate says there is no problem): Which of our customers were in those 20 prompts? And what does our JSON return form look like after the change?
Why is this a problem? (step by step)
- Small, biased sample. Twenty prompts, chosen and judged by one person, probably in English, cannot show a 2 percent drop.
- Loss is uneven. Lower precision adds small errors to every layer. On easy chat they rarely matter. On exact tasks, like a valid JSON with the right order number, small errors can break the result.
- Languages. Research suggests quantization can hurt some non-English languages more than English. We must check Persian on its own.
- Speed depends on the batch. INT4 weights mean fewer bytes to read in each decode step. That helps a lot when reading weights is the limit. When the batch is large, math becomes the limit, and the speed-up can shrink. Kernel quality on our GPU also matters.
- Cost is a full-system number. Smaller weights free memory. That memory lowers cost only if it holds more KV cache, so more requests run per GPU, at our latency targets.
The fix: what I would do
- Run the eval set on both versions: real tickets, split by Persian and English, chat answers and JSON forms, short and long chats.
- Check format rules with code: valid JSON rate, right field values.
- Compare with clear limits, for example: no group may drop more than 1 point.
- Load test both at our latency targets, and compare throughput and cost per million tokens.
- Try options: FP8 (if the GPUs support it) usually loses less quality than INT4. Also consider INT8, or a quantized KV cache.
- Release to a small share of traffic behind a flag, and watch quality signals before moving everyone.
Follow-up question: What is the difference between weight-only quantization and quantizing weights and activations?
Follow-up answer:
- Weight-only (for example INT4 AWQ or GPTQ) stores the weights in fewer bits and turns them back into 16-bit numbers inside the kernel to do the math. It saves memory and memory bandwidth, so it helps decode at small batches.
- Weights and activations (for example FP8, or INT8 for both) also run the math itself in low precision on hardware that supports it. This can speed up the compute-heavy parts too, like prefill and large batches.
- Either way, we check quality with evals.
Red flag: “The answers look the same” is the only proof. Another red flag: assumes 4 times smaller weights means 4 times faster or 4 times cheaper.
Show answer
6. The prompt that starts with the time
Batching and caching for LLM serving· in roadmap
Question: This function builds the prompt for every turn of the shop assistant:
def build_prompt(user, history, question):
return (
f"Current time: {datetime.now().isoformat()}\n"
f"Customer: {user.name} (id {user.id})\n"
+ SHOP_RULES # about 3,000 tokens, same for everyone
+ format_history(history)
+ f"Customer: {question}\nAssistant:"
)
Our serving engine has prefix caching turned on. You see this in code review. What do you think? Is there a problem?
Short answer: Yes. Prefix caching can reuse the KV cache only for the exact same tokens from the start of the prompt. This prompt starts with the current time (to the microsecond) and the customer’s name, so no two prompts share a start. The 3,000 tokens of shop rules are computed again for every turn of every chat. I would put the parts the same for everyone first (the shop rules), then the parts the same for this chat (name, today’s date, the history), and the new question at the end.
Hint (if the candidate says there is no problem): The dashboard shows a prefix cache hit rate of almost 0 percent. Why could that be?
Why is this a problem? (step by step)
- How prefix caching works. The engine keeps the KV cache of earlier prompts. If a new prompt starts with the same tokens, it reuses that work and runs prefill only for the new part.
- It must be the exact start. One different token at position 5 means everything after it is different too, because each token’s keys and values depend on all tokens before it.
- Here the first line always changes. The time changes every call. The name changes for every customer.
- The cost. Every turn runs prefill on about 3,000 extra tokens. That makes the time to first token longer and uses GPU compute that could serve other users.
- Multi-turn chats lose too. Turn 2 of a chat could reuse turn 1’s whole prompt, but the time at the start breaks that as well.
The fix: what I would do
- Order by how often it changes: the same for everyone, then the same for this chat, then new in this turn.
def build_prompt(user, history, question):
return (
SHOP_RULES # same for everyone
+ f"Customer name: {user.name}\n" # same for this chat
+ f"Today: {date.today().isoformat()}\n"
+ format_history(history) # grows, old part is stable
+ f"Customer: {question}\nAssistant:" # new every turn
)
- Ask if we need the time at all. Often the date is enough. Never use microseconds.
- Check that the history is stable. If we summarize or reorder history in each turn, it breaks reuse too.
- Measure the prefix cache hit rate and time to first token before and after.
Follow-up question: Does the model’s answer change if we move the customer’s name after the rules?
Follow-up answer:
- It can change a little, because the model sees things in a different order. That is why we run the eval set after the change.
- In practice, models handle facts placed after the instructions well. If one fact matters a lot, the instructions can say where to find it.
- Also, the user id is not useful to the model here. If we do not need it, we remove it.
Red flag: Does not know that the cache works only on an exact prefix. Another red flag: suggests “just turn on more caching” without changing the prompt order.
Show answer
7. Round robin over eight replicas
Batching and caching for LLM serving· in roadmapRunning LLM serving in production· in roadmap
Question: Traffic grew, so we now run 8 replicas of the shop assistant, one GPU each, with prefix caching on. In front of them is our normal load balancer:
upstream llm_backend {
# round robin (the default)
server llm-1:8000;
server llm-2:8000;
# ... llm-3 to llm-8
}
Every turn of a chat sends the whole history again. With 1 replica, the prefix cache hit rate was about 70 percent. With 8 replicas it is about 15 percent, and time to first token got worse for long chats. What do you think is happening?
Short answer: Round robin sends each turn of the same chat to a different replica. The prefix cache lives in each GPU’s own memory, so turn 5 lands on a replica that has never seen turns 1 to 4, and must run prefill on the whole history again. More replicas means a smaller chance of landing on the right one. I would use cache-aware routing: send requests of the same chat (or the same prompt prefix) to the same replica, but still balance load so one replica does not get overloaded.
Hint (if the candidate says there is no problem): Where is the prefix cache stored? Which replica gets turn 2 of a chat that turn 1 sent to llm-3?
Why is this a problem? (step by step)
- The cache is local. Each engine keeps its KV cache in its own GPU memory. Replicas do not share it.
- Round robin ignores content. Turn 1 goes to llm-3, turn 2 to llm-4, and so on.
- The chance is 1 in 8. A turn finds its own history in the cache only if it lands on the same replica by luck.
- Long chats pay the most. A chat with 6,000 tokens of history must recompute all of it on most turns.
- The shop rules still hit. That is why the rate is 15 percent, not zero: the shared rules are cached on every replica.
The fix: what I would do
- Route by chat. Hash the conversation id and send all its turns to the same replica (sticky routing).
- Keep balance. Pure stickiness can overload one replica. A good router mixes “where is the cache” with “how busy is each replica”, for example queue length or KV cache usage.
- Use a ready router when you can. Some serving stacks have prefix-aware or session-aware routers, for example the SGLang router, the vLLM production stack or llm-d. Check what fits our setup.
- Measure cache hit rate per replica, time to first token for long chats, and load balance.
- Plan for replica changes. When a replica is added or removed, some chats move and lose their cache once. Consistent hashing keeps that number small.
Follow-up question: One very big customer sends 30 percent of all traffic, all with the same long prefix. What happens with routing by prefix?
Follow-up answer:
- All of it would go to one replica, which becomes a hot spot while the others are idle.
- So the router must allow a hot prefix to live on more than one replica, and spread its requests over them by load.
- Each of those replicas pays the prefill for that prefix once, then reuses it. That is a small cost compared to overloading one GPU.
Red flag: Suggests “add more replicas” as the fix, which makes the hit rate even worse. Another red flag: thinks the prefix cache is shared between all replicas automatically.
Show answer
8. Pauses when a catalog arrives
Batching and caching for LLM serving· in roadmapHow LLM inference works· in roadmap
Question: Our shop assistant now also serves business customers. Its config:
model: shop-assistant-8b
max_context: 131072 # 128k tokens, the model supports it
max_running_requests: 64
# no other limits
One business customer pastes their whole 100-page product catalog (about 90,000 tokens) into the chat and asks questions about it, many times a day. Each time they do, normal chat users on the same replica see their answers stop for a few seconds in the middle. What do you think is going on?
Short answer: A 90,000-token prompt needs a huge prefill. If the engine runs that prefill in one step, every running chat must wait for it, so their streams freeze. The long prompt also takes about 11 GB of KV cache, which can force the engine to pause other requests. I would turn on chunked prefill with a token budget per step, so long prompts are split and mixed with decode steps. I would also add per-customer token limits, consider a separate pool for long-context work, reuse the catalog with prefix caching, or better, use retrieval so only the useful pages are sent.
Hint (if the candidate says there is no problem): Decode for one token of 64 chats takes milliseconds. How long does the model need to read 90,000 new tokens? What do the 64 chats do meanwhile?
Why is this a problem? (step by step)
- Prefill is heavy. Prefill processes all prompt tokens. Its work grows with the prompt length, and attention work grows even faster for long prompts.
- Steps are shared. In continuous batching, all requests move forward in the same steps. One step with a giant prefill is a long step for everyone.
- Users feel it as a freeze. A chat that was streaming 30 tokens per second suddenly stops for a few seconds.
- Memory. 90,000 tokens × about 128 KB = about 11 GB of KV cache for one request. If the cache is full, the engine pauses or drops other requests and recomputes them later.
- It repeats. The same catalog is sent many times a day. Without prefix caching, every question pays the full prefill again.
- No fairness. One customer can use most of a replica, with no limit.
The fix: what I would do
- Chunked prefill. Split long prefills into chunks with a token budget per step, so decode steps keep running between chunks. Many engines support this; check that it is on and tune the budget.
- Separate long-context traffic. Route very long prompts to their own replicas, so normal chat keeps its latency target.
- Limits per customer. Tokens per minute and max prompt length per plan.
- Reuse the catalog. Put the catalog at the start of the prompt so prefix caching reuses it for follow-up questions.
- Send less. Retrieval (RAG): search the catalog and send only the few relevant pages. That is faster, cheaper, and often more accurate.
- Measure inter-token latency p99 for normal chats, before and after.
Follow-up question: What is “disaggregated prefill”, and when does it help?
Follow-up answer:
- It runs prefill and decode on different GPUs. Prefill GPUs build the KV cache, then send it to decode GPUs, which only write tokens.
- It helps when long prompts and steady streaming fight with each other, because each pool can be tuned for its own job.
- The cost: moving the KV cache between GPUs needs fast networking, and the system is more complex. It makes sense at large scale, not usually as a first step.
Red flag: Thinks the GPU “is just slow” and wants a bigger GPU, without seeing that one long prompt blocks everyone. Another red flag: no idea that prefill and decode behave differently.
Show answer
9. Speculative decoding at busy hours
Batching and caching for LLM serving· in roadmap
Question: A teammate added speculative decoding to the shop assistant. A small draft model guesses 5 tokens, and the main 8B model checks them in one step. Their benchmark:
| Test | Without | With speculative decoding |
|---|---|---|
| One request at a time, English chat | 95 tokens/s | 200 tokens/s |
They turned it on in production. A week later, at busy hours (about 100 running requests per replica), total throughput is 15 percent lower than before, and per user speed is about the same. At night, users get faster answers. What do you think?
Short answer: Speculative decoding helps when the GPU is memory-bound, at small batches: the main model checks several guessed tokens for almost the price of one. At busy hours the GPU is already full with 100 requests, so the step is closer to compute-bound. Now every wrong guess is wasted compute, and the draft model also uses compute and memory. So it hurts throughput when busy. The benchmark was also one request and English only, but much of our traffic is in Persian and JSON, where the draft model may guess worse. I would measure acceptance rate on real traffic, and use speculative decoding only at low load, or tune or turn it off when the batch is large.
Hint (if the candidate says there is no problem): The benchmark ran one request at a time. What is different about the GPU when 100 requests run together?
Why is this a problem? (step by step)
- Why it works at all. At small batches, one decode step reads all the weights but does very little math. Checking 5 tokens in the same step costs almost the same as writing 1.
- The guesses must be right. If the main model accepts on average 3 of 5 guessed tokens, we get about 3 tokens per step. If it accepts 1, we gain little and paid for the draft.
- Busy GPU, different limit. With 100 requests per step, the GPU already does a lot of math. Checking 5 tokens for each of them is real extra work, and the rejected ones are thrown away.
- The draft model is not free. It uses GPU time and memory that could hold more KV cache.
- Wrong test traffic. English chat at batch 1 is the best case. Persian text or JSON forms may have lower acceptance rates.
The fix: what I would do
- Measure on real traffic: acceptance rate by language and task, throughput and latency at different loads.
- Turn it on by load. Use it at low load, and reduce the number of guessed tokens or turn it off when the batch is large. Check what our engine supports.
- Try other drafters. For example, a draft trained on our own traffic, or methods built into the model like extra prediction heads, or n-gram lookup for answers that copy the prompt.
- Decide by our goals. If night users matter and day throughput matters more, run it only where it helps.
Follow-up question: Does speculative decoding change the answers?
Follow-up answer:
- When done correctly, no. The main model checks every token, and the acceptance rule is made so the output follows the same distribution as the main model alone.
- So it is a speed trick, not a quality trade, unlike quantization.
- In practice, tiny differences can come from number precision, so we still run the eval set once after turning it on.
Red flag: Believes “2 times faster in the benchmark” means 2 times faster in production. Another red flag: does not know that the batch size changes whether the GPU is limited by memory or by compute.
Show answer
10. A benchmark with one prompt
Running LLM serving in production· in roadmap
Question: Before launch, a teammate load tested the new shop assistant server:
prompt = "Hello, where is my order 12345?"
times = []
for _ in range(1000):
start = time.time()
send(prompt, max_tokens=20)
times.append(time.time() - start)
print("median latency:", statistics.median(times))
Result: “Median latency 180 ms. One replica can easily handle thousands of users.” Real chats have about 1,500 tokens of history and answers of about 300 tokens. What do you think?
Short answer: This test does not look like real traffic at all. It sends the same prompt every time, so prefix caching makes prefill almost free. It sends one request at a time, so there is no batching, no queue and no competition. Prompts are tiny and answers are 20 tokens, while real ones are about 1,500 and 300. And it reports only the median of total time, not time to first token, time per token, or p95/p99. I would replay real prompts with real length distributions, ramp up concurrency step by step, measure TTFT and TPOT at p50/p95/p99, and find the load where we break our latency targets.
Hint (if the candidate says there is no problem): How many requests were running at the same time in this test? And what did the cache do with the 999 repeats?
Why is this a problem? (step by step)
- Cache makes it fake. After the first call, the whole prompt is in the prefix cache.
- Concurrency is 1. “Thousands of users” means many requests at once. This test never had two at the same time.
- Wrong sizes. Real prompts are about 50 times longer and need real prefill. Real answers are 15 times longer, and decode time grows with each token.
- Wrong numbers. The median hides the slow tail. Total time mixes waiting for the first token with streaming speed, and users feel these differently.
- No warm-up, no variety. The first calls can be slower (loading, compiling), and real traffic mixes short and long chats.
The fix: what I would do
- Use real prompts. Sample anonymized real chats, or build a set with the same length distribution for prompts and answers.
- Ramp concurrency: 1, 8, 16, 32, 64, 128 parallel users, or a request rate that grows over time.
- Measure the right numbers: TTFT, TPOT (or inter-token latency), end-to-end time, and throughput, each at p50, p95 and p99. Also the error rate.
- Find the knee. The load where p95 TTFT or TPOT goes above the target is the real capacity of one replica.
- Use a tool made for this instead of a loop, for example the benchmark scripts that come with the engine, or tools like GuideLLM or GenAI-Perf. Check which fits.
- Measure from the client side too, through the real network and proxies.
Follow-up question: The real capacity turns out to be 40 chats per replica at our targets. Peak traffic is 600 chats. How many replicas do you plan?
Follow-up answer:
- 600 / 40 = 15 replicas just for the peak.
- Add room for a failed replica and for a deploy (rolling restart), for example 2 to 3 more.
- Add a margin for traffic growth, and plan autoscaling for the day and night curve, so we do not pay for 18 GPUs at night.
- Then test again at that size, because the router and the network also change the numbers.
Red flag: Accepts a single-prompt loop as a load test. Another red flag: reports only averages or medians.
Show answer
11. Self-hosting is cheaper, says the spreadsheet
Running LLM serving in production· in roadmapGPU memory and parallelism· in roadmap
Question: Today the shop assistant uses an outside model API. A teammate wants to move to our own GPUs and shares this math. (All prices are made-up examples.)
GPU rent: 4 dollars per hour
Benchmark: 5,000 output tokens per second
(max batch 256, p95 time per token 140 ms)
1M tokens takes: 1,000,000 / 5,000 = 200 seconds
Cost of 1M tokens: 4 x 200 / 3600 = about 0.22 dollars
API price today: about 1 dollar per 1M tokens
=> Self-hosting is 4.5 times cheaper!
What do you think about this math?
Short answer: The math assumes the GPU runs at benchmark peak, 24 hours a day, and that is never true. The 5,000 tokens/s was measured at a batch where time per token is 140 ms, too slow for our chat target. At our latency target, throughput may be half. Real traffic has a day and night curve, so average use may be 30 to 40 percent. We need spare replicas for failures and deploys. The API price may count input and output tokens differently from the benchmark. And it leaves out people and operations. Redo it with throughput at our SLO, real traffic, spare capacity and team cost; self-hosting may still win at large, steady scale, or may not.
Hint (if the candidate says there is no problem): Is 140 ms per token OK for our users? And how busy is the GPU at 4 a.m.?
Why is this a problem? (step by step)
- Peak, not real. The benchmark ran the largest batch. At our target of 50 ms per token, assume we measure 2,500 tokens/s. Cost becomes about 0.44 dollars per 1M tokens.
- Utilization. We pay for the GPU every hour, busy or not. If average use is 35 percent of the peak capacity, cost per token is about 0.44 / 0.35 = about 1.27 dollars per 1M tokens.
- Spare capacity. One GPU failing must not break the chat. Extra replicas for failures and rolling deploys add maybe 10 to 20 percent more.
- Token mix. Chats have long prompts and short answers. APIs usually price input and output tokens separately. Our cost per request depends on prefill work too, not only output tokens.
- People. Someone runs the GPUs, updates engines, handles incidents at night and runs evals for new models. That is real cost.
- Quality. The open-weight model must pass the same evals as the API model, or the savings are not a fair comparison.
The fix: what I would do
- Measure throughput at our SLO, with real prompts, not at the largest batch.
- Use the real traffic curve to compute how many GPUs we need per hour, and what autoscaling can save.
- Add redundancy and people cost to the total per month.
- Compare cost per request, for the same chats, both ways, at the same quality.
- Write down the break-even point: above what monthly traffic self-hosting wins. Also count non-cost reasons: data control, custom models, vendor limits.
- Start small: move one workload, for example the nightly review summaries, which can use big batches and run at full GPU use.
Follow-up question: Which workload is easiest to make cheap on our own GPUs, and why?
Follow-up answer:
- Offline batch jobs, like summarizing all reviews at night.
- They have no latency target, so we can use very large batches and keep the GPU near 100 percent busy.
- They can run when chat traffic is low, on the same GPUs, so we use capacity we already pay for.
- Many API providers also offer cheaper batch prices, so compare that too.
Red flag: Trusts peak benchmark throughput as the cost basis. Another red flag: forgets that idle GPU hours still cost money.
Show answer
12. Streaming behind the proxy
Running LLM serving in production· in roadmap
Question: The shop assistant engine streams tokens with server-sent events. On the engine’s dashboard, time to first token p95 is 400 ms. But users say: “I wait about 10 seconds, then the whole answer appears at once.” Sometimes long answers stop in the middle. The engine sits behind our Nginx:
location /chat/stream {
proxy_pass http://llm_backend;
}
What do you think?
Short answer: The engine streams, but Nginx does not. By default Nginx buffers the upstream response, so it collects tokens and sends them later, often all at once. It also talks to the upstream with HTTP/1.0 by default and has a 60 second read timeout, which can cut long or slow answers. I would set proxy_buffering off for this route (or send an X-Accel-Buffering: no header from the app), use HTTP/1.1 to the upstream, raise the read timeout, and measure time to first token at the client, not only on the engine.
Hint (if the candidate says there is no problem): The engine says the first token leaves in 400 ms. Where else can a token wait before it reaches the browser?
Why is this a problem? (step by step)
- Two different “first token” times. The engine measures when it sends the first token. The user feels when the browser shows it. Everything in between can add delay.
- Proxy buffering. With buffering on, Nginx reads the upstream response into buffers and sends it to the client in bigger pieces. For streaming, that turns “word by word” into “all at once”.
- HTTP version. By default Nginx uses HTTP/1.0 to the upstream. Streaming works better with HTTP/1.1 and keep-alive.
- Timeouts. The default read timeout is 60 seconds between two reads. A slow answer during a busy time, or a long pause, can be cut.
- Other layers too. A CDN, a cloud load balancer or compression can also buffer.
The fix: what I would do
- Fix the route:
location /chat/stream {
proxy_pass http://llm_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_buffering off;
proxy_read_timeout 300s;
}
- Check every layer between the engine and the browser: CDN, load balancer, gzip.
- Measure at the client. Log time to first token as the browser sees it, and compare with the engine’s number.
- Test it: use curl with no buffering on the public URL and watch the tokens come one by one.
Follow-up question: A user closes the tab in the middle of a long answer. What should happen, and how do you check it?
Follow-up answer:
- The engine should stop generating for that request and free its KV cache. Otherwise the GPU writes hundreds of tokens nobody reads.
- The proxy must close the upstream connection, and the app must pass the cancel to the engine (abort the request).
- To check: start a long answer, close the client, and watch the engine’s running requests and generated tokens metrics. The request should disappear in a moment.
Red flag: Trusts only the engine’s own latency numbers. Another red flag: blames the model for slowness without looking at the network path.
Show answer
13. Design the serving for the shop assistant
How LLM inference works· in roadmapGPU memory and parallelism· in roadmapQuantization· in roadmapBatching and caching for LLM serving· in roadmapRunning LLM serving in production· in roadmapLLM evaluation (evals)· in roadmap
Question: The shop wants to move its assistant from an outside API to an open-weight model on its own GPUs. The facts:
- Chat: peak of about 1,500 chats at the same time, in the evening. At night, about 100. Prompts are about 1,500 tokens (shop rules plus history), answers about 300 tokens. Persian and English.
- Targets: time to first token p95 under 1 second, at least 20 tokens per second for each user.
- Nightly job: summarize reviews for 6,000 products, no latency target, must be done by morning.
- Quality: the new model must pass the current eval set.
- Budget: must cost less per month than the API.
You own this. How do you design it? Take a few minutes, then explain your plan step by step.
Short answer: I start with evals to pick the smallest model that passes, in both languages. Then I do memory and capacity math: weights, KV cache for real chat lengths, and throughput per GPU at our targets, which I measure with a realistic load test. I serve with a ready engine (vLLM, SGLang or TensorRT-LLM) with continuous batching and prefix caching, put the shared shop rules first in the prompt, and use cache-aware routing. I try FP8 or INT4 only if evals stay good. I autoscale on queue and KV cache signals with pre-loaded weights, run the nightly job in big batches on the same GPUs at night, and keep the API as a fallback. I watch TTFT/TPOT p95, cost per million tokens and quality after launch.
Why is this hard? (step by step)
- Quality first. A cheaper model that fails evals is not cheaper; it moves the cost to support.
- Memory limits users per GPU. KV cache, not weights, usually decides how many chats fit.
- Two goals fight. Bigger batches lower cost but raise per-user latency.
- Traffic is not flat. 1,500 in the evening, 100 at night. Fixed capacity for the peak wastes money.
- GPU replicas start slowly. Loading many GB of weights takes minutes, so scaling must start early.
- Many layers can break latency: routing, proxies, long prompts.
The fix: my plan
- Choose the model.
- Run the eval set on a few open-weight candidates, for example an 8B and a larger one, split by language and task.
- Pick the smallest that passes. Maybe route only hard questions to a bigger model later.
- Do the math (for an 8B model like in the lessons).
- Weights about 16 GB in BF16. KV cache about 128 KB per token.
- One chat is about 1,800 tokens, about 230 MB. With about 55 GB free on an 80 GB GPU, the memory holds about 230 chats.
- The real limit may be speed: measure how many chats one GPU serves while still meeting TTFT under 1 s and 20 tokens per second.
- Measure capacity. Load test with real anonymized prompts and growing concurrency. Suppose we find 120 chats per GPU at our targets. Then the peak needs about 13 GPUs, plus 2 spare.
- Serving setup.
- A ready engine with continuous batching, prefix caching and chunked prefill.
- Prompt order: shop rules first, then chat facts, then history, then the new question.
- A router that keeps each chat on one replica but still balances load.
- Streaming end to end, with proxy buffering off.
- Limits: max prompt and answer length, tokens per minute per user.
- Make it cheaper, safely.
- Try FP8 weights and an FP8 KV cache on GPUs that support it, and INT4 if needed. Run evals and the load test again for each.
- Measure speculative decoding at low load only.
- Scaling.
- Autoscale on waiting requests and KV cache usage, not CPU.
- Keep weights on fast local disk or a cache near the GPUs, and keep a minimum of warm replicas.
- Scale up before the evening peak, using the known daily curve.
- Nightly job. Run review summaries at night on the same GPUs, with big batches and low priority. Done by morning, almost no extra cost.
- Release.
- Behind a flag: 5 percent of chats, then 25, then all. Keep the API as a fallback if our replicas are overloaded or down.
- Dashboards: TTFT and TPOT p95, errors, queue, cache hit rate, cost per million tokens, and quality signals like thumbs up and support reopen rate.
- Decide again monthly. Compare total monthly cost, including people, with the API at the same quality.
What I would not do: Pick the biggest model “to be safe”, plan capacity from a single-prompt benchmark, quantize without evals, or switch all traffic on one day with no fallback.
Follow-up question: Two months later, a new open-weight model is released that is better on our evals. How do you switch?
Follow-up answer:
- Run our eval set on it first, in both languages, and check its memory math: its KV cache size per token may be very different.
- Load test it at our targets, because the same parameter count can give different speed.
- Deploy it on a few replicas behind the router, send a small share of traffic, and compare quality and latency with the current model.
- Move traffic step by step, keep the old model ready for rollback, and remove it only after a stable period.
Red flag: Starts by choosing GPUs or an engine before quality and targets are clear. Another red flag: no plan for the day and night traffic curve, or no fallback when GPUs fail.
Show answer
14. 60,000 tokens per second for one user?
Math for ML· in roadmapHow a GPU works· in roadmap
Question: A teammate wants to promise very fast answers for our shop assistant. They write:
Model: 8B parameters, BF16 weights
One token needs about 2 x 8e9 = 16 GFLOPs
Our GPU: about 1,000 TFLOPS (BF16, dense)
So one user can get 1,000e12 / 16e9 = 62,500 tokens per second
Is this math right? What speed can one user really expect?
Short answer: The FLOP count is right, but math is not the limit for one user. In each decode step the GPU must read all 16 GB of weights from memory to make one token. At about 3.35 TB/s that takes about 5 ms, so the best case is about 200 tokens per second, and real engines get less. Decode for one user does only about 1 FLOP per byte read, far below the GPU’s balance point of about 300, so it is memory-bound.
Hint (if the candidate agrees with the plan): To make one token, which data must the GPU read, and how fast can it read it?
Why is the plan wrong? (step by step)
- FLOPs per token. About 2 × parameters = 16 GFLOPs. Correct.
- Bytes per token. Every weight is read once per step: 8 billion × 2 bytes = 16 GB.
- Memory speed. About 3.35 TB per second on this kind of GPU.
- Time per step. 16 GB ÷ 3.35 TB/s ≈ 4.8 ms, before any other overhead.
- Tokens per second. 1 ÷ 4.8 ms ≈ 200 tokens per second at most for one request.
- Intensity. 16 GFLOPs ÷ 16 GB = 1 FLOP per byte. The GPU could do about 300 FLOPs for each byte it reads, so the cores are idle most of the time.
The fix: what I would do
- Estimate both limits (compute and memory) and use the smaller one.
- Promise numbers from a load test, not from a spec sheet.
- Use the idle compute by batching many users: 64 users share one read of the weights.
- Read fewer bytes: FP8 or INT4 weights make decode faster, if evals stay good.
Follow-up question: Prefill of a 2,000-token prompt uses the same weights. Is it memory-bound too?
Follow-up answer:
- No. Prefill uses each weight for all 2,000 tokens, so it does about 2,000 FLOPs per byte of weights.
- That is above the balance point, so prefill is compute-bound, and the TFLOPS number does matter there.
- So time to first token depends on compute; time per token depends on memory bandwidth.
Red flag: Uses only TFLOPS to predict speed, or does not know that decode reads all the weights in every step.
Show answer
15. An attention score that crashes
Math for ML· in roadmapTransformers and attention· in roadmap
Question: A new teammate writes attention for one head, to learn how it works:
import numpy as np
t, d = 5, 128 # 5 tokens, head size 128
Q = np.random.randn(t, d)
K = np.random.randn(t, d)
V = np.random.randn(t, d)
scores = Q @ K # line A
w = np.exp(scores) # line B
w = w / w.sum(axis=-1, keepdims=True)
out = w @ V
Line A crashes. After a “fix”, line B sometimes gives nan. What is wrong, and how do you fix both?
Short answer: Line A multiplies (5, 128) @ (5, 128): the inner sizes (128 and 5) do not match. The scores need Q @ K.T, which is (5, 128) @ (128, 5) = (5, 5): one score for each pair of tokens. Line B can overflow: exp of a big number is infinity, and infinity divided by infinity is nan. Subtract the row max first and divide the scores by √d. For a language model, also add the causal mask, so a token cannot look at later tokens.
Hint (if the candidate is stuck): Write the shape next to every line. What shape should “one score per pair of tokens” have?
Why is this a problem? (step by step)
- Shapes. Q is (5, 128) and K is (5, 128). For
@, the left’s last size must equal the right’s first size: 128 ≠ 5. - What we want. Score[i, j] = dot product of query i and key j. That is Q @ K.T, shape (5, 5).
- Scale. Dot products of 128 random numbers get large. Dividing by √128 ≈ 11.3 keeps them in a good range.
- Overflow.
np.exp(800)isinf. Theninf / inf=nan, and thenanspreads through every later layer. - Missing mask. Without a causal mask, token 0 can see token 4: the model “cheats” and gives different results from training.
The fix: what I would do
scores = Q @ K.T / np.sqrt(d) # (5, 5)
mask = np.triu(np.ones((t, t), dtype=bool), k=1) # future
scores[mask] = -np.inf
scores -= scores.max(axis=-1, keepdims=True)
w = np.exp(scores)
w /= w.sum(axis=-1, keepdims=True)
out = w @ V # (5, 128)
Follow-up question: In decode, only one new token is processed. What are the shapes of q, K and the scores then?
Follow-up answer:
- q is (1, 128): only the new token’s query.
- K and V are (t, 128): all earlier tokens, read from the KV cache.
- Scores are (1, t). No mask is needed, because every cached token is in the past.
Red flag: Fixes the shape by trial and error (K.T, Q.T, reshape) without explaining what the result means. Or says overflow “never happens in practice”.
Show answer
16. We trained on 8 GPUs, so we serve on 8 GPUs
Neural network basics· in roadmapHow a GPU works· in roadmap
Question: Our team fine-tuned the 8B shop model on a machine with 8 GPUs of 80 GB each. Now the team lead writes the serving budget:
Fine-tuning used 8 x 80 GB GPUs and almost all memory.
So serving needs 8 x 80 GB GPUs per copy of the model.
We want 3 copies for traffic: 24 GPUs.
Do you agree? How would you size it?
Short answer: No. Training keeps much more in memory than inference. With mixed precision and Adam, training needs roughly 16 bytes per parameter (weights, gradients, optimizer state), plus saved activations for the backward pass: well over 128 GB for 8B. Inference needs only the weights (about 16 GB in BF16), the KV cache and some runtime memory. One 80 GB GPU per copy is a good first guess. The real number of copies should come from a load test with real chat lengths, not from training hardware.
Hint (if the candidate agrees): What does training keep in memory that inference does not need at all?
Why is this a problem? (step by step)
- Training memory. Weights + gradients + optimizer state (Adam keeps two extra numbers per weight, often in FP32) + activations saved for the backward pass.
- Rough count for 8B. About 16 bytes × 8 billion = 128 GB, before activations. That is why it was spread over 8 GPUs.
- Inference memory. Only the forward pass with fixed weights: about 2 bytes × 8 billion = 16 GB.
- The rest of an 80 GB GPU goes to the KV cache, which decides how many chats run at the same time.
- The budget of 24 GPUs may be 8 times too large.
The fix: what I would do
- Start with one GPU per copy and count: 16 GB weights + a few GB runtime + KV cache for real chat lengths.
- Load test with realistic traffic and measure time to first token and time per token at p95.
- Add copies only when the load test shows the targets are missed.
- Consider FP8 weights to free more memory for the KV cache, if evals stay good.
Follow-up question: When would you still use 2 or more GPUs for one copy of a model?
Follow-up answer:
- When the weights do not fit, for example a 70B model in BF16 needs about 140 GB.
- When you need more KV cache for very long contexts than one GPU can hold.
- When one GPU is too slow for the latency target and tensor parallelism makes each step faster.
Red flag: Thinks training and inference need the same hardware, or cannot name what training keeps in memory.
Show answer
17. Remove the activations to save time?
Neural network basics· in roadmap
Question: A teammate profiles a small model and sees time spent in the activation function (SiLU) of every layer. They suggest:
Idea: delete the activation in every layer.
Each layer becomes just x @ W, which is simpler and faster.
We keep all the trained weights.
What happens to the model? Is the idea worth trying?
Short answer: The model breaks. Without activations, every layer is a plain matrix multiply, and many matrix multiplies in a row are the same as one: (x @ A) @ B = x @ (A @ B). The deep network collapses into one linear layer and can only learn straight-line rules. Also, the weights were trained with the activations, so removing them changes every output. And the saving is small: activations are cheap next to the matrix multiplies, which are where the time goes. If an activation is slow, the fix is a fused kernel, not removing it.
Hint (if the candidate likes the idea): What is (x @ A) @ B the same as?
Why is this a problem? (step by step)
- Math. Matrix multiply is associative, so a stack of linear layers equals one linear layer with W = A @ B @ C ….
- Power. A single linear layer cannot learn curved patterns, like “yes if x is big OR small”.
- Trained weights. Each layer’s weights expect inputs that went through the activation. Remove it, and the numbers the next layer sees are wrong.
- Cost. An activation does a few operations per number. A matrix multiply does thousands per number. The time is in the matrix multiplies.
- Real slowness from activations usually comes from an extra memory round trip: the layer writes its output to HBM, and a separate kernel reads it back to apply the activation.
The fix: what I would do
- Keep the activations. Changing the model’s math needs retraining and evals.
- Fuse the activation into the matrix multiply kernel, so the data does not make an extra trip to memory. Serving engines and compilers (for example
torch.compile) do this. - Measure first: in a real profile, confirm where the time goes before changing anything.
Follow-up question: Then which changes can make the model faster without retraining?
Follow-up answer:
- Batching more requests, so each read of the weights serves more tokens.
- Smaller number formats (FP8, INT8, INT4) with evals to check quality.
- Fused and optimized kernels, and a serving engine instead of a plain script.
Red flag: Does not know why neural networks need activations, or optimizes a small part of the time without measuring.
Show answer
18. Temperature 0, but the answer still changes
Transformers and attention· in roadmap
Question: A support lead reports a bug about our shop assistant:
1. With temperature 0.8, the same question gets different answers.
2. So we set temperature 0. Now answers are mostly the same,
but under heavy load a few answers still differ a little.
Please fix the model so it is always the same.
Explain both points. Is the second one a bug?
Short answer: Point 1 is by design: with temperature above 0, the next token is sampled at random from the chances, so answers differ. Point 2 is expected too: temperature 0 means greedy (always the top token), but the scores themselves can change a tiny bit between runs. On a GPU, floating-point math is not exactly associative, and the order of additions can depend on the batch size and which kernels run, which change with load. When two tokens have almost the same score, a tiny change can flip the pick, and the rest of the answer follows a different path. It is usually not a model bug. Fix it with evals that accept small wording changes, or, if exact repeats really matter, an engine setting for deterministic or batch-invariant mode, at some speed cost.
Hint (if the candidate says “temperature 0 must be fully deterministic”): Is (a + b) + c always exactly equal to a + (b + c) with floating-point numbers?
Why does this happen? (step by step)
- Sampling. The model gives a chance for every token. With temperature 0.8, the sampler picks at random by these chances.
- Greedy. With temperature 0, it picks the highest score. If scores never changed, the answer would never change.
- Floating point. In BF16 or FP32, adding the same numbers in a different order can give a slightly different result.
- Load changes the order. With continuous batching, a request shares a batch with different requests each time. Different batch shapes can choose different kernels or split the sums differently.
- Close calls flip. If “Your” has 0.4100 and “The” has 0.4099, a tiny change picks the other one. After that, every later token can differ.
The fix: what I would do
- Explain that point 1 is expected; use low temperature for support if stable answers matter.
- Write evals on meaning, not exact text: does the answer give the right order status and policy?
- If exact repeats are required (for example for tests or audits), check the serving engine’s options for deterministic or batch-invariant kernels, and measure the speed cost.
- For tests, run with a fixed batch size and a fixed seed, so results are comparable.
Follow-up question: Is a fixed random seed enough to make sampling with temperature 0.8 repeatable in production?
Follow-up answer:
- Not by itself. The seed fixes the random numbers, but the chances they are compared with can still change a little with batching, as above.
- Many engines accept a per-request seed, which helps, but the same limits apply.
- Exact repeatability needs both a fixed seed and deterministic math.
Red flag: Says the model is “broken” or “has memory” without knowing how sampling works, or claims temperature 0 is always bit-for-bit repeatable on GPUs.
Show answer
19. Why not cache the queries too?
Transformers and attention· in roadmapHow LLM inference works· in roadmap
Question: A teammate reads about the KV cache and suggests an “improvement”:
The KV cache stores keys and values of past tokens.
Each token also has a query. Let's store the queries too (a QKV cache),
so the model never computes anything twice. Even faster!
What do you answer?
Short answer: It would only waste memory. In decode, the new token’s query is compared with the keys of all earlier tokens, and the result weights their values. Old queries are never used again: an earlier token’s query was needed only once, to compute that token’s own output, and because of the causal mask that output never changes when new tokens come. Keys and values are reused in every later step, so caching them saves work. Caching queries saves nothing and makes the cache about 1.5 times larger with standard attention, and much more with grouped-query attention, where there are 4 times more query heads than KV heads in our model.
Hint (if the candidate likes the idea): In one decode step, which vectors of the earlier tokens does attention read?
Why is this a problem? (step by step)
- One decode step. Compute q, k, v for the new token only. Add k and v to the cache.
- Attention. Scores = q · (all cached keys). Output = weighted sum of all cached values.
- Old queries. Not in this formula. They were used once, when their own token was new.
- The causal mask means an earlier token’s output depends only on tokens before it, so it never needs to be recomputed with a new token.
- Memory. Our model has 32 query heads and 8 KV heads per layer, each of size 128. Storing queries adds 32 × 128 numbers per layer per token, twice the size of today’s keys and values (2 × 8 × 128). The cache would be 3 times larger, and fewer chats would fit.
The fix: what I would do
- Keep the KV cache as it is.
- If the goal is speed, look at what really costs time: reading weights and the KV cache. Batching, prefix caching and a smaller KV format (for example FP8) help.
- Explain with the formula, so the team understands why K and V are special.
Follow-up question: Prefix caching reuses the KV cache of a shared beginning, like the shop’s long system prompt. Why is it safe to share it between users?
Follow-up answer:
- Because of the causal mask, the keys and values of a token depend only on the tokens before it.
- If two requests start with exactly the same tokens, those tokens have exactly the same K and V, no matter what comes after.
- So the engine can compute them once and reuse them, as long as the prefix is identical token by token.
Red flag: Cannot explain what Q, K and V do in decode, or thinks a bigger cache is free.
Show answer
20. GPU-Util is 100%, so we need more GPUs
Question: During a sale, the shop assistant gets slower. An engineer checks the server:
$ nvidia-smi
GPU Name ... Memory-Usage GPU-Util
0 ... 71000MiB / 81559MiB 100%
They write: “The GPU is at 100%. We must buy a second GPU today.” What would you check before you agree?
Short answer: GPU-Util only says that at least one kernel was running during the sample time. It does not say how many cores were busy or how much memory bandwidth was used. A decode-heavy LLM server often shows 100% while most of its compute is idle. Before buying, check what users feel (time to first token, time per token, queue time, at p95), what the engine does (running and waiting requests, batch size, KV cache usage, preemptions), and the traffic (request rate, prompt and answer lengths). The fix might be a larger batch limit, a shorter max context, prefix caching or FP8 KV cache, and a second GPU only if the load test says so.
Hint (if the candidate agrees at once): What exactly does the GPU-Util number measure?
Why is this a problem? (step by step)
- GPU-Util is the share of time in which a kernel was running. One small kernel running all the time gives 100%.
- Memory-Usage near full is normal: serving engines reserve most free memory for the KV cache at start-up, on purpose.
- The real limits are KV cache space, memory bandwidth and the scheduler’s batch limits, and none of them is shown by these two numbers.
- The real symptom is in user metrics: is it the queue (TTFT grows) or each step (TPOT grows)?
- Cause examples. A sale brings longer chats → KV cache full → requests wait. Or a batch limit set too low → GPU under-used.
The fix: what I would do
- Open the engine’s metrics (for example running and waiting requests, KV cache usage, tokens per second).
- Look at TTFT and TPOT at p95 for the sale period.
- Tune first: batch and token limits, max context, prefix caching for the long system prompt, FP8 KV cache with evals.
- Run a load test that copies the sale traffic, and buy capacity from its results.
- Add an alert on queue time and KV cache usage, not on GPU-Util.
Follow-up question: Which tools give a truer picture of how busy the GPU is?
Follow-up answer:
- NVIDIA DCGM metrics (for example SM activity, tensor core activity and memory bandwidth use), often exported to Prometheus.
- Profilers like Nsight Systems or the PyTorch profiler, for a short detailed look.
- The serving engine’s own metrics: tokens per second and batch size are the most useful daily numbers.
Red flag: Treats GPU-Util and memory usage as “how full” the GPU is, or buys hardware without looking at user-facing metrics.
Show answer
21. A benchmark that is too good to be true
PyTorch for inference· in roadmapHow a GPU works· in roadmap
Question: A teammate compares BF16 and FP8 weights for our 8B model with this script:
import time, torch
model = load_model() # weights on the GPU
x = make_inputs(batch=1, tokens=16) # a short prompt
start = time.perf_counter()
for _ in range(100):
out = model(x)
elapsed = time.perf_counter() - start
print("ms per forward:", elapsed / 100 * 1000)
The result: 0.3 ms per forward pass for both formats, so “FP8 gives no speed-up”. What is wrong with this benchmark?
Short answer: Several things. (1) No torch.cuda.synchronize(): GPU work is asynchronous, so the clock mostly measures how fast Python can queue work, not how long the GPU takes. (2) No warm-up: the first runs include one-time costs. (3) No torch.inference_mode(): gradient tracking adds memory and time. (4) Unrealistic input: one forward pass of a 16-token prompt is neither time to first token nor time per output token, and batch 1 with a tiny prompt hides real behavior. Fix the timing and measure TTFT and TPOT with realistic prompts and batch sizes, then compare formats.
Hint (if the candidate trusts the number): When model(x) returns in Python, has the GPU finished the work?
Why is this a problem? (step by step)
- Asynchronous GPU. PyTorch puts kernels in a queue on the GPU and returns at once.
- The clock stops early. Without synchronize,
perf_counteris read while most kernels are still waiting or running. Both formats look the same because both are only “queued”. - Physics check. Reading 16 GB of BF16 weights takes about 5 ms on a 3.35 TB/s GPU. 0.3 ms per forward is impossible.
- Warm-up. The first calls load kernels and allocate memory; they make the average noisy.
- Wrong unit. Users feel time to first token and time per token in a real chat, not one forward pass of 16 tokens.
The fix: what I would do
@torch.inference_mode()
def bench(model, x, warmup=5, runs=50):
for _ in range(warmup):
model(x)
torch.cuda.synchronize()
start = time.perf_counter()
for _ in range(runs):
model(x)
torch.cuda.synchronize()
return (time.perf_counter() - start) / runs
- Synchronize and warm up, as above.
- Measure decode with the KV cache (one new token per step) and prefill with real prompt lengths, separately.
- Try several batch sizes (1, 8, 32), because the gain from FP8 can change with batch size.
- Then use the real serving engine for the final numbers, and check quality with evals.
Follow-up question: You could also time with CUDA events. Why might that be useful?
Follow-up answer:
torch.cuda.Event(enable_timing=True)records time on the GPU itself, between two points in its queue.- It measures GPU time without stopping Python at every step, which is good for timing one part of a model.
- You still need to synchronize (for example
end.synchronize()) before reading the elapsed time.
Red flag: Accepts a GPU timing without synchronize, or does not sanity-check the number against memory bandwidth.
Show answer
22. More guessed tokens, slower answers
Speculative decoding in depth· in roadmap
Question: At night the shop assistant (8B model) runs speculative decoding with a 1B draft model. A teammate changed one number and measured again, at low load:
| Guessed tokens per round | English chats | Persian chats |
|---|---|---|
| 0 (off) | 95 tokens/s | 95 tokens/s |
| 4 | 185 tokens/s | 130 tokens/s |
| 10 | 155 tokens/s | 96 tokens/s |
They say: “More guesses should mean more speed. The engine must have a bug.” What do you think?
Short answer: It is not a bug. Each round gives on average (1 − α^(k+1)) / (1 − α) tokens, where α is the acceptance rate. This has a ceiling of 1 / (1 − α), so extra guesses add less and less. But the drafter runs k steps every round, kept or not, so the cost grows in a straight line. With α near 0.7 (English), the best k is about 4. With α near 0.5 (Persian), the ceiling is 2 tokens per round and the best k is about 2, so k = 10 pays for guesses that are almost never used. I would measure the acceptance rate per language, pick k per traffic type, and for Persian try a better drafter (trained on our Persian chats, or an EAGLE or Medusa style drafter).
Hint (if the candidate agrees it is a bug): The 10th guess is used only if the first 9 were all kept. How likely is that?
Why does this happen? (step by step)
- A round. The drafter writes k tokens, the main model checks them in one step, keeps the ones up to the first miss, and adds one token of its own.
- Expected tokens per round. With α = 0.7: k = 4 gives about 2.8 tokens, k = 10 gives about 3.3. Only a little more.
- Cost per round. If one draft step costs about a tenth of a main step, k = 4 costs 1.4 main steps and k = 10 costs 2 main steps.
- Speed-up. 2.8 / 1.4 ≈ 2.0, but 3.3 / 2 ≈ 1.6. So k = 10 is slower, as measured.
- Persian. With α = 0.5, a round can never give more than 2 tokens. k = 10 gives about 2.0 / 2 = 1.0: no gain at all.
The fix: what I would do
- Read the engine metrics: acceptance rate and mean accepted length, split by language and task.
- Sweep k (for example 1 to 8) on a replay of real traffic, and pick the best k for each pool.
- Improve α for Persian: a drafter trained on our own chats, or a drafter that reads the main model’s hidden state.
- Use n-gram lookup where answers copy the prompt (order summaries, JSON fixes).
- Check at busy-hour load too, because the best k is smaller when the GPU is busy.
Follow-up question: Can a better drafter ever make the answers worse?
Follow-up answer:
- No. The acceptance rule makes the output follow the main model’s distribution, whatever the drafter is.
- A bad drafter only makes it slower, because fewer guesses are kept.
- We still run the eval set once, because tiny number differences are possible.
Red flag: Thinks more guessed tokens always means more speed. Another red flag: does not know that the drafter’s cost is paid for every guess, kept or not.
Show answer
23. Tensor parallelism over two machines
Distributed inference· in roadmap
Question: The shop serves its 70B model (BF16, 80 layers, 64 query heads, 8 KV heads) on one machine with 8 GPUs connected by NVLink. A teammate wants faster answers and changes the setup:
# before
machines: 1
tensor_parallel: 8
# after
machines: 2 # connected with a 200 Gb/s network
tensor_parallel: 16
After the change, each user gets fewer tokens per second than before, the cost doubled, and the KV cache room per GPU did not grow as expected. What happened, and what would you do?
Short answer: Tensor parallelism does two all-reduces in every layer: with 80 layers that is 160 waits in every decode step. Inside one machine they go over NVLink and are fast. Across two machines they go over the network, and each wait is many times longer. Splitting the weights 16 ways makes the reading part of each step smaller, but the waits grow more than the reading shrinks, so tokens get slower. Also, the model has only 8 KV heads: with 16 GPUs, each KV head is copied on two GPUs, so the KV cache per GPU stops shrinking. I would go back to tensor parallel 8 inside one machine, and use the second machine as a second replica for more traffic. If a model ever needs two machines to fit, I would use tensor parallel 8 inside each machine and pipeline parallel 2 across them.
Hint (if the candidate says “more GPUs should be faster”): How many times per token must all 16 GPUs wait for each other, and over which link?
Why is this a problem? (step by step)
- What each step does. Each GPU reads its share of the weights, then waits in 160 all-reduces.
- Small messages. At decode, each all-reduce carries only the batch × hidden size (about 512 KB for 32 chats), so the fixed delay of each wait matters most.
- NVLink vs network. Inside a machine, a wait takes a few microseconds. Over a network it can take tens of microseconds. 160 of them add several milliseconds per token.
- KV heads. 8 KV heads cannot split 16 ways, so the engine copies them. Memory per GPU for the cache stays about the same as with 8 GPUs.
- Cost. Twice the GPUs for one copy of the model, so the cost per token doubles even before the slowdown.
The fix: what I would do
- Tensor parallel 8 on one machine, and a second replica on the other machine behind the router. Twice the throughput, same latency.
- For lower latency per user, look at other tools: speculative decoding at low load, FP8 weights, or a smaller model that passes the evals.
- If a model does not fit on one machine, use pipeline parallel across machines: only one hand-off per step at the border.
- Measure tokens per second per user and time spent in communication, not only GPU use.
Follow-up question: When would you split prefill and decode onto separate GPUs?
Follow-up answer:
- When long prompts (like big catalogs) make the chats stutter, and chunked prefill on the same GPUs is not enough.
- The cost is moving the KV cache: about 320 KB per token for this model, so about 1.3 GB for a 4,000-token prompt. It needs a fast network.
- It is worth it at large scale, when each pool can be tuned on its own. For a few replicas, it is usually too much work.
Red flag: Thinks twice the GPUs always gives twice the speed. Another red flag: puts tensor parallelism across machines without counting the waits per layer.
Show answer
Not saved in this browser.