Outcome School (@outcome_school) header
Outcome School (@outcome_school) profile picture

Get a High-Paying Tech Job. Software engineers like you join Outcome School to achieve the outcome that is a high-paying tech job.

Internet
Joined June 2024
Photo by Outcome School (@outcome_school)Photo by Outcome School (@outcome_school)Photo by Outcome School (@outcome_school)Photo by Outcome School (@outcome_school)Photo by Outcome School (@outcome_school)Photo by Outcome School (@outcome_school)Photo by Outcome School (@outcome_school)Photo by Outcome School (@outcome_school)Photo by Outcome School (@outcome_school)Photo by Outcome School (@outcome_school)
Our recent 6 articles on X: - KV Cache in LLMs - Paged Attention in LLMs - Causal Masking in Attention - Byte Pair Encoding in LLMs - Harness Engineering in AI - Math behind Attention - Q, K, and V X is a knowledge sharing platform.
1
3
27
3,007
Outcome School retweeted
This question was asked in AI Engineering interviews at Google DeepMind, Apple, and Perplexity. Question: Compare greedy, beam search, top-k, top-p and temperature sampling. When does each fail? Let's answer it step by step. At every step, an LLM gives a probability for every token in its vocabulary. The decoding strategy decides how we pick the next token from that list. Greedy and beam search pick the most likely tokens. Temperature, top-k, and top-p control random sampling. Greedy: always pick the token with the highest probability. - Good for: short factual answers, classification, extraction. - Fails: it gets stuck in repetition loops in long text, and it can miss a better sentence because one locally best token leads to a worse path. Beam search: keep the B most likely partial sequences at every step and return the best full sequence. - Good for: tasks with one right answer, like translation and speech recognition. - Fails: in open-ended writing, the most likely text is bland, generic, and repetitive. It also favors short outputs unless we add a length penalty, and it costs B times more compute. Temperature: divide the logits by T before softmax. Let's say the logits are [2, 1, 0]: - T = 1: [0.665, 0.245, 0.090] - T = 0.5: [0.867, 0.117, 0.016], sharper - T = 2: [0.506, 0.307, 0.186], flatter T close to 0 behaves like greedy. - Fails: too low gives repetitive text, too high gives incoherent text. Temperature reshapes the curve but never removes the long tail of bad tokens. Top-k: keep only the k most likely tokens, renormalize, and sample. - Fails: k is fixed, but the shape of the distribution is not. When the model is confident, k = 50 still lets in many bad tokens. When many tokens are reasonable, like the start of a story, k = 50 can cut out good options. Top-p (nucleus sampling): keep the smallest set of tokens whose probabilities add up to p, like 0.9, then sample. - Adapts to the distribution: a few tokens when the model is sure, many when it is not. - Fails: with a very flat distribution, the set becomes huge and includes junk. A high temperature makes this worse, because it flattens the distribution before top-p is applied. In practice, these are combined: temperature first, then top-k and top-p filter the tokens, then we sample. When to use which: - Code, math, JSON, extraction: greedy or a low temperature. - Chat and creative writing: temperature around 0.7 to 1.0 with top-p around 0.9. - Translation: beam search. In the interview, the most important line is: the most likely sequence is not the best text for open-ended generation, so we use sampling, and top-p works better than top-k because it adapts to how confident the model is at each step.
3
2
19
828
Outcome School retweeted
This question was asked in AI Engineering interviews at Moonshot AI and Character . AI. Question: Explain prefix caching / prompt caching. When should you use it, and what invalidates a cached prefix? Let's answer it step by step. Prefix caching, also called prompt caching, saves the KV Cache of a prompt prefix that repeats across requests. When a new request starts with exactly the same tokens, the model loads the saved KV Cache and runs prefill only on the new part. First, why it helps. Prefill computes the Key and Value of every prompt token in every layer. For a long prompt, this is heavy work, and it decides the time to first token. Let's say every request has the same 5,000-token system prompt and document, plus a 50-token user question. - Without caching: prefill on 5,050 tokens, every time. - With caching: the first request computes all 5,050 tokens and saves the KV Cache of the 5,000-token prefix (a cache write). Every later request loads it and runs prefill on only the 50 new tokens (a cache read). The answer quality does not change, because the cached Keys and Values are the same ones the model would compute again. How it works inside the serving engine: - vLLM hashes each KV Cache block together with all the tokens before it, and a new request reuses every matching block from the start. - SGLang keeps the cached prefixes in a radix tree (RadixAttention). When should we use it? - Long system prompts that are the same for every user - Tool definitions and few-shot examples in agents - Large documents with many questions asked about them - Multi-turn chat: every new turn repeats the full history as the prefix The rule: put the stable part first, and the changing part last. What invalidates a cached prefix? - Any change in the prefix: the match is at the token level from the very first token. Change the token at position 10, and everything from position 10 onward is a miss, because the Keys and Values after it depend on it. - Dynamic content early: a timestamp or a user name at the top breaks the cache for every request. - Reordering: tools or documents in a different order give different tokens. - A different model or version: the KV Cache belongs to the exact weights. - Eviction: the cache lives in limited GPU or CPU memory. Unused prefixes get removed by LRU or after a time-to-live. - Routing: in a cluster, a request sent to a server that does not hold the prefix gets a miss. Cache-aware routing fixes this. The cache is also position-dependent. The same text at a different position has different Keys after RoPE. In the interview, the most important line is: prefix caching reuses the KV Cache of an exact token prefix, so we design prompts with the static part first and the dynamic part last, and any change before a token invalidates the cache for everything after it.
1
2
21
937
Outcome School retweeted
Preparing for AI Engineering interviews? Here are key LLM topics you should know: - Transformer Architecture - Tokenization & Embeddings - Attention Mechanisms - RoPE & Positional Encoding - Flash Attention & Paged Attention - KV Cache & Inference Optimization - MoE, Quantization & Distillation - RLHF, DPO, PPO & GRPO - LLM Training & Scaling Laws I've compiled questions and answers covering these topics and much more. Explore the complete repository: github.com/amitshekhariitbhu…
1
15
59
2,065
Outcome School retweeted
This question was asked in AI Engineering interviews at Microsoft, Apple, and Perplexity. Question: What are TTFT, TPOT, ITL and throughput, and how do they trade against each other? Let's answer it step by step. An LLM answers in two phases. Prefill reads the whole prompt and produces the first token. Decode then generates the rest, one token at a time. Each metric measures a different part of this. TTFT (Time To First Token): the time from sending the request until the first token arrives. It includes the time waiting in the queue plus the prefill. Long prompts and a busy queue make it worse. TPOT (Time Per Output Token): the average time for each token after the first one, for one request. TPOT = (end-to-end latency - TTFT) / (output tokens - 1) ITL (Inter-Token Latency): the actual gap between two consecutive tokens. TPOT is one average per request. ITL is the full list of gaps, so it shows the spikes. A request can have a good TPOT and still have one 2-second pause in the middle. So, we look at p99 ITL for a smooth stream. Throughput: the total output tokens per second across all users on the server. TTFT, TPOT, and ITL are per-user latencies, smaller is better. Throughput is a system metric, bigger is better. End-to-end latency = TTFT + (N - 1) x TPOT For example, TTFT 400 ms, 200 output tokens, TPOT 25 ms: 400 + 199 x 25 = 5,375 ms. Now, how do they trade against each other? - Batch size: decode is limited by memory, not math. A bigger batch shares the cost of reading the weights, so throughput goes up a lot. But each step does more work, so TPOT for every user goes up a little. And when the batch is full, new requests wait, so TTFT goes up. - Prefill vs decode on the same GPU: when a long prompt arrives, its prefill takes over the GPU. If we run it at once, the new user gets a fast TTFT, but every other user sees an ITL spike. If we delay it, the stream stays smooth, but TTFT gets worse. - Chunked prefill: splits a long prompt into pieces mixed with the decode steps. It protects ITL, at a small cost to TTFT. - Disaggregation: runs prefill and decode on separate GPUs, so we can tune TTFT and TPOT independently, at the cost of moving the KV cache. So, the real goal is not maximum throughput. It is the maximum throughput while meeting the latency targets, like p99 TTFT under 1 second and p99 ITL under 50 ms. This is often called goodput. In the interview, the key line is: throughput is bought with batch size, and batch size is paid for with latency, so we tune it against a latency target.
5
4
1
27
1,043
Outcome School retweeted
This question was asked in AI Engineering interviews at Microsoft, Amazon, NVIDIA, and Cursor. Question: How would you cut LLM serving cost by 10x? Enumerate every lever and rank them. Let's answer it step by step. First, we measure. Cost per request = GPU cost per hour / requests served per hour. So, we can either do less work per request, or serve more requests per GPU. We need the breakdown: input tokens vs output tokens, GPU utilization, cache hit rate, and which traffic uses which model. No single lever gives 10x. We get it by multiplying several levers: 3 x 2 x 2 is already 12x. Here are the levers, ranked from the biggest impact to the smallest: 1. Use a smaller model where it is enough. Most traffic is often easy. A router sends easy requests to a small model and only hard ones to the big model. A distilled or fine-tuned small model for one task can replace a big general model. This is often the largest lever, because the compute per token drops with the model size. 2. Batching and utilization. Decode is limited by memory, so a GPU serving one request at a time is mostly idle. Continuous batching and Paged Attention fit many more users on the same GPU. A badly batched deployment can gain several times here. 3. Quantization. FP8 or INT4 weights cut the memory, so we need fewer GPUs and fit bigger batches. FP8 KV cache fits more users. We must check the quality on our own evals. 4. Do less work per request. - Prefix caching: a long shared system prompt is computed once and reused. - Shorter prompts: trim the retrieved context and the chat history. - Shorter outputs: set the max tokens, and ask for concise answers. Output tokens cost more than input tokens, because each one needs its own decode step. - Semantic caching: for repeated questions, return a stored answer and skip the model. 5. Infrastructure. - Autoscale with the traffic, so GPUs do not sit idle at night. - Move offline jobs, like evals and bulk summaries, to batch processing at low priority. - Choose the right GPU for the job, and use spot or reserved capacity where possible. 6. Speculative decoding. It mainly cuts latency, and the savings shrink at large batch sizes. It helps cost when batches are small. Every lever has a quality or latency risk. So, each change goes behind an eval set and an A/B test, and we track cost per successful request, not just cost per token.
10
4
41
1,530
Outcome School retweeted
This question was asked in AI Engineering interviews at Google DeepMind, Meta, Amazon, and NVIDIA. Question: Compare tensor, pipeline, data, sequence and expert parallelism. When do you combine them? Let's answer it step by step. Each type of parallelism splits a different thing across GPUs. The right choice depends on what does not fit, and on how fast the link between the GPUs is. Data parallelism: split the batch. Every GPU holds a full copy of the model and processes different examples. In training, the gradients are averaged with an all-reduce after every step. But every GPU must fit the full model. ZeRO and FSDP fix this by sharding the weights, gradients, and optimizer states across the GPUs. Tensor parallelism: split each weight matrix. One matrix multiplication is divided across GPUs, as in Megatron-LM. Every layer needs an all-reduce, so communication happens many times per forward pass. That is why we keep it inside one server, on fast NVLink, usually 8 GPUs. Pipeline parallelism: split the layers. GPU 1 runs layers 1 to 20, GPU 2 runs layers 21 to 40, and so on. Only the activations at the boundary move between GPUs, so it works across servers on a slower network. The issue is the bubble: GPUs sit idle while the pipeline fills and drains. We reduce it by splitting the batch into many micro-batches. Sequence parallelism: split along the tokens. In Megatron-LM, it splits the LayerNorm and dropout activations next to tensor parallelism. For very long context, context parallelism gives each GPU a part of the sequence, and the GPUs exchange Keys and Values for attention, as in Ring Attention. Expert parallelism: split the experts of a Mixture of Experts model. Each GPU holds a few experts. A router sends each token to its experts, so tokens travel between GPUs with an all-to-all. The cost is that all-to-all traffic and uneven load when many tokens pick the same expert. When do we combine them? Almost always, for large models. Put the heaviest communication on the fastest link: - Tensor parallelism inside a server, on NVLink. - Pipeline parallelism across servers. - Data parallelism across copies of this whole setup, to scale the throughput. - Context parallelism when the sequence is long. - Expert parallelism when the model is a Mixture of Experts. For example, Llama 3 405B was trained with 4D parallelism: tensor, pipeline, context, and data. For serving, tensor parallelism cuts the latency per token, pipeline parallelism fits a model larger than one server, and data parallelism adds replicas for more users. In the interview, the key line is: choose the split by what does not fit, and map the most communication-heavy split to the fastest interconnect.
6
5
32
1,172
Outcome School retweeted
This question was asked in an AI Engineering interview at NVIDIA. Question: Estimate the GPU memory needed to serve a 70B model: weights, KV cache, activations, fragmentation. Let's answer it step by step. Total memory = weights + KV cache + activations + overhead and fragmentation Let's take a model like Llama 3 70B: 80 layers, 8 KV heads (Grouped-Query Attention), head_dim 128, served in BF16. Step 1: Weights. 70 billion parameters x 2 bytes = 140 GB. In FP8, it becomes 70 GB. In INT4, about 35 GB plus a little for the scales. Step 2: KV cache. KV cache per token = 2 x layers x kv_heads x head_dim x bytes = 2 x 80 x 8 x 128 x 2 = 327,680 bytes, which is 320 KB per token. - One request of 4,096 tokens: 4,096 x 320 KB = 1.25 GB. - 32 users with 4,096 tokens each: 40 GB. - One user with 128K tokens: 40 GB. So, the KV cache decides how many users we can serve, not the weights. Without Grouped-Query Attention, with 64 KV heads, it would be 8 times bigger. Step 3: Activations. During decode, the activations are small, because each request processes one token per step. During prefill, a long prompt creates large temporary buffers. Engines like vLLM run a test forward pass at startup to measure this peak and reserve it. A few GB is a fair estimate. Step 4: Overhead and fragmentation. - The CUDA context, the communication buffers for tensor parallelism, and the CUDA graphs take memory on every GPU. - Engines do not use 100 percent of the GPU. vLLM, by default, uses 90 percent of it. - Fragmentation: if we reserve one big block per request for the maximum length, most of it stays empty. Paged Attention stores the cache in small blocks, so the waste stays only in the last block of each request. Now, let's add it up for 32 users with 4K tokens each: 140 GB weights + 40 GB KV cache + a few GB activations + a few GB overhead per GPU = roughly 190 GB. So: - BF16 on 80 GB GPUs: 2 GPUs give 160 GB, which is not enough. We need 4 GPUs with tensor parallelism. The extra memory becomes room for more users. - FP8 weights: 70 GB + 40 GB = 110 GB plus overhead, which fits on 2 GPUs. One more trade-off: more GPUs also means more memory bandwidth, so each decode step gets faster. In the interview, the key line is: the weights are a fixed cost, but the KV cache grows with users and context length, and that is what sets the real memory budget.
9
20
162
5,941