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,027
Outcome School retweeted
This question was asked in AI Engineering interviews at NVIDIA and Together AI. Question: What is speculative decoding? Why is output quality preserved, and when does it not help? Let's answer it step by step. Speculative decoding is a method where a small, fast draft model guesses the next few tokens, and the large target model checks all of them in a single forward pass. We get several tokens for about the cost of one large-model step, with exactly the same output distribution as the large model alone. First, why it works. Decode is memory-bandwidth-bound. Each step reads all the weights to produce one token, while the compute units sit mostly idle. So, checking 5 tokens in one pass takes almost the same time as generating 1. Now, the steps: - Draft: the small model generates k tokens, say 4, one by one. - Verify: the large model runs once on all 4 draft tokens and gives its own probabilities at each position. - Accept or reject: go left to right. Accept each draft token by the rule below. At the first rejection, replace that token with a corrected sample from the large model and drop the rest. - Bonus: if all 4 are accepted, the large model's pass already gives the 5th token for free. So, every round gives at least 1 token and at most k + 1. Why is the quality preserved? Let p(x) be the large model's probability and q(x) the draft model's probability for the draft token x. - Accept x with probability min(1, p(x) / q(x)). - If rejected, sample from the leftover distribution: max(0, p - q), normalized. The papers by Leviathan et al. and Chen et al. prove that this gives exactly the distribution p. Every token is effectively sampled from the large model. The draft model only changes the speed, never the output distribution. With greedy decoding, it is even simpler: accept a draft token only if it equals the large model's top token. Let's see the speedup. If each draft token is accepted with rate a, the expected tokens per round is: (1 - a^(k+1)) / (1 - a) With a = 0.8 and k = 4: (1 - 0.32768) / 0.2 = about 3.4 tokens per large model pass. When does it not help? - Low acceptance rate: the draft model is too weak or trained on different data, or the temperature is high. Most guesses get rejected, and the drafting time is wasted. - Large batch sizes: the GPU is already busy with compute. Verifying extra tokens for every request is no longer free, and the gain shrinks or turns negative. - Slow draft: if the draft model is not much faster than the target, the drafting time eats the savings. In the interview, the most important line is: speculative decoding turns idle compute in memory-bound decode into extra tokens, and the accept-reject rule makes the output distribution exactly the same as the large model, so it is a pure latency win only when acceptance is high and the batch is small. Detailed blog: outcomeschool.com/blog/specu…
2
4
4
257
Outcome School retweeted
This question was asked in AI Engineering interviews at Perplexity and Cursor. Question: How do you keep an index fresh when the underlying corpus changes continuously? Let's answer it step by step. We never rebuild the full index on every change. We detect what changed, re-process only that part, and update the index in place. A full rebuild is kept only for the rare cases that need it. Step 1: Detect the change. - Event-driven: the source tells us. A database change stream (Change Data Capture), a webhook, or a file watcher. - Polling: for sources that cannot push, we check them on a schedule. For the web, we recrawl a page based on how often it changes and how important it is. - For a codebase, we hash every file and build a Merkle tree, a tree of hashes. We compare the root hash, walk down only the branches whose hash changed, and find the changed files fast. Step 2: Re-process only what changed. Each chunk gets a stable ID, like doc_id plus chunk number, and a content hash. We re-chunk the changed document and compare the hashes. A chunk with the same hash keeps its old embedding. Only the new or changed chunks go to the embedding model. For small edits, this saves most of the embedding cost. Step 3: Update the index. - Upsert the changed chunks by ID. - Delete the chunks that no longer exist. Deletes are the most forgotten part. A deleted document that is still retrievable is a stale answer, and for private data, a leak. - Update the keyword index (BM25) and the metadata too, not only the vector index. Step 4: Handle the limits of ANN indexes. Graph indexes like HNSW often handle deletes by only marking them, so quality and speed drop over time. So: - Keep a small fresh index for recent changes and a large main index. Query both and merge the results. - Merge and rebuild the main index in the background on a schedule. Step 5: Full rebuilds with zero downtime. When we change the embedding model or the chunking, every vector must be recomputed. Vectors from two different embedding models cannot be compared. So, we build a new index next to the old one, test it, then switch traffic with an alias. This is a blue-green swap. Step 6: Use time at query time. Store last_updated with each chunk. Boost recent chunks for time-sensitive queries, or filter by date. For breaking news, call a live search instead of trusting the index. Step 7: Monitor freshness. Track the lag between a change in the source and the moment it becomes searchable. Set a target for each source, like 1 minute for prices and 1 day for documentation, and alert on it. In the interview, the most important point is: freshness is an incremental pipeline problem. Detect changes, re-embed only changed chunks by content hash, handle deletes, and do full rebuilds as a background blue-green swap.
3
3
21
781
Outcome School retweeted
AI System Design - A complete guide to learn AI System Design step by step - from LLM inference, GPUs, KV Cache, and caching to RAG, Vector Databases, AI Agents, MCP, Multi-Agent Systems, Voice AI, Guardrails, Evaluation, Observability, Cost Optimization, and a step-by-step framework to crack any AI System Design interview. Everything in one place, explained in simple words, with detailed blogs for every deep dive. Start here: github.com/amitshekhariitbhu…
2
3
29
1,111
Outcome School retweeted
This question was asked in AI Engineering interviews at Cohere, Microsoft, and Perplexity. Question: What is a reranker, when should you use one, and what does a cross-encoder cost you? Let's answer it step by step. A reranker is a second-stage model that takes the candidates from a fast retriever and reorders them by their true relevance to the query, so that the best few go to the LLM. Retrieval works in two stages: - Stage 1, retrieve: BM25 or vector search quickly finds the top 100 to 200 candidates out of millions of documents. - Stage 2, rerank: a more accurate model scores only those candidates. We keep the top 5 or 10. Why do we need stage 2? The fast retriever uses a bi-encoder. It embeds the query and each document separately, and compares the two vectors. The document was embedded without knowing the question. So, fine details get lost in one vector. A reranker is usually a cross-encoder. It reads the query and the document together, as one input. The query tokens and the document tokens attend to each other. It outputs one relevance score. For example, for "What is the capital of France?", a retriever can rank "Berlin is the capital of Germany" high, because it shares the word "capital". A cross-encoder sees that it does not answer the question, and pushes "Paris is the capital and largest city of France" to the top. When should we use one? - When precision at the top matters: RAG, where only the top 5 chunks fit in the prompt. - When recall@100 is good but the right chunk is not in the top 5. - After hybrid search, to put the merged BM25 and dense results into one consistent order. What does a cross-encoder cost us? - No precomputation. The score depends on the query, so we cannot embed documents in advance. Every query needs one model pass per candidate. 100 candidates means 100 pairs through a Transformer. - Latency. This adds a noticeable delay to every request, and it grows with the number of candidates and the document length. - It cannot fix recall. If the right document is not in the candidates, the reranker never sees it. - It cannot replace the retriever. Running it over a million documents for every query is far too slow. The knob is the number of candidates. More candidates gives better accuracy, but more latency and cost. A middle ground is late interaction, like ColBERT. It precomputes one embedding per token for each document, and compares query tokens to document tokens at search time. More precise than a bi-encoder, faster than a cross-encoder, but it needs much more storage. In the interview, the key line is: the retriever is built for recall over millions, the reranker is built for precision over a hundred, and the cross-encoder pays for that precision with one model pass per candidate. Detailed blog: outcomeschool.com/blog/how-d…
2
4
22
863
Outcome School retweeted
This question was asked in AI Engineering interviews at Moonshot AI and Groq. Question: Explain disaggregated prefill/decode serving and when it pays for itself. Let's answer it step by step. Disaggregated serving runs the prefill phase and the decode phase of a request on separate pools of GPUs, and moves the KV cache from the prefill GPU to the decode GPU in between. First, let's understand why we separate them. - Prefill reads the whole prompt in one pass. It is heavy on math. It decides TTFT. - Decode generates one token per step and reads all the weights and the KV cache every step. It is heavy on memory. It decides the time per output token. When both run on the same GPU, they fight. A long prefill stalls the decode of every other user. We can improve TTFT or the time per output token, but improving one hurts the other. Chunked prefill reduces this fight, but every step still carries some prefill work. Now, the flow with disaggregation: - A router sends the request to a prefill worker. - The prefill worker reads the prompt, builds the KV cache, and produces the first token. - The KV cache is copied over a fast network to a decode worker. - The decode worker generates the rest of the answer. What we gain: - No interference. Decode steps are never paused by a long prompt. - We tune and scale each pool on its own. More prefill workers for long prompts, more decode workers for long answers. - Different settings per phase: a different parallelism, batch size, or even a different GPU type for each pool. What it costs: the KV cache transfer. For a model like Llama 3 70B in BF16, the KV cache is about 320 KB per token. A 4,096 token prompt means about 1.25 GB to move. At 400 Gb/s, which is 50 GB/s, that is about 25 ms. Many systems send it layer by layer while the prefill is still running, to hide this time. On a slow network, the transfer eats the gain. So, when does it pay for itself? - Large scale, with enough traffic to keep two separate pools busy. - Long prompts: RAG, documents, code, long chat histories, where prefill is heavy. - Strict targets on both TTFT and the time per output token at the same time. - A fast interconnect between the GPUs, like NVLink or InfiniBand with RDMA. And when it does not: - Small scale or a single GPU. Chunked prefill is simpler and good enough. - Short prompts, where the prefill is cheap and there is little to separate. - No fast network. Systems that use this idea include DistServe, Splitwise, and Mooncake, the serving platform of Moonshot AI for Kimi. In the interview, the key line is: disaggregation removes the interference between prefill and decode, and it pays off only when that interference costs more than moving the KV cache. Detailed blog: outcomeschool.com/blog/prefi…
3
3
18
831
Outcome School retweeted
Preparing for AI Engineering interviews? Here are key RAG (Retrieval-Augmented Generation) topics you should know: - RAG Architecture & Fundamentals - Document Chunking Strategies - Embeddings & Vector Databases - Semantic Search & Hybrid Search - Reranking & Retrieval Optimization - Query Transformation & Expansion - Metadata Filtering - Advanced RAG & Agentic RAG - Multi-Hop Retrieval - RAG Evaluation & Metrics - Handling Hallucinations & Conflicting Information - Multimodal RAG - Production RAG System Design I've compiled interview questions and answers covering these topics and much more. Explore the complete repository: github.com/amitshekhariitbhu…
3
19
120
4,952
Outcome School retweeted
This question was asked in AI Engineering interviews at OpenAI and Cognition. Question: How do you handle tool-call errors, timeouts and retries in an agentic loop? Let's answer it step by step. In an agentic loop, the LLM only recommends a tool and its input. Our code, the loop, runs the tool. So, every error reaches our code first, and our code decides what the LLM gets to see. The rule is simple: never let a tool error crash the loop, and never retry blindly. First classify the error, then decide who handles it, the code or the LLM. Step 1: Validate before running. Check the tool name exists and the arguments match the schema. If the LLM passed a bad argument, do not run the tool. Return a clear message instead: "Error: date must be in YYYY-MM-DD format. You sent 12/05/2026." Step 2: Put a timeout on every tool call. A tool that hangs must not freeze the whole agent. Each tool gets its own deadline, and the full run gets an overall time budget. Step 3: Classify the error. - Transient: timeout, rate limit (429), server error (503), network failure. The same call can work on the next try. - Permanent: bad input (400), not found (404), permission denied (403). The same call will fail again. Step 4: Retry transient errors in code, without the LLM. Use exponential backoff with jitter: wait 1s, 2s, 4s, plus a small random delay, so that many agents do not retry at the same moment. Cap it at 2 or 3 retries. Respect the Retry-After header when the API sends it. Step 5: Send permanent errors back to the LLM as an observation. Write it in plain language: what failed, why, and what to try next. "Error: no customer found with id 4521. Try searching by email." The LLM can then fix the input or pick another tool. A raw stack trace wastes tokens and confuses the model. Step 6: Make retries safe. Retrying a read is harmless. Retrying "send payment" can charge the user twice. For tools with side effects, we pass an idempotency key, so a repeated call does not repeat the action. Step 7: Stop the loop from going in circles. - Detect the same tool with the same input failing again and again, and tell the LLM to try a different approach. - Use a circuit breaker: if a tool keeps failing, mark it unavailable for this run. - Keep the hard limits: max steps, max time, and max cost. Step 8: Fail gracefully. When nothing works, the agent tells the user what it could not do, instead of making up an answer. For risky actions, hand over to a human. Step 9: Log every attempt: tool name, input, error type, latency, and retry count. This is how we find which tool is breaking our agents. In the interview, the most important point is: retry transient errors in code with backoff and idempotency keys, and send permanent errors to the LLM as clear observations so it can change its plan.
4
4
1
18
1,054
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
22
938
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
987