<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ye Aung on Medium]]></title>
        <description><![CDATA[Stories by Ye Aung on Medium]]></description>
        <link>https://medium.com/@yeaung276?source=rss-b28c8c23a257------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RijqRFe0_nWcaWsthnunhw.png</url>
            <title>Stories by Ye Aung on Medium</title>
            <link>https://medium.com/@yeaung276?source=rss-b28c8c23a257------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:08:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yeaung276/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[RAG Playground: Measure Every Change to Your RAG Chatbot]]></title>
            <link>https://medium.com/@yeaung276/rag-playground-measure-every-change-to-your-rag-chatbot-53670c34b6a7?source=rss-b28c8c23a257------2</link>
            <guid isPermaLink="false">https://medium.com/p/53670c34b6a7</guid>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Ye Aung]]></dc:creator>
            <pubDate>Sun, 11 Oct 2026 06:59:03 GMT</pubDate>
            <atom:updated>2026-10-11T06:59:03.375Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q13U_fY1rP64fR0mSDOZqQ.png" /></figure><h3>The story</h3><p>I was recently tasked with building a question-answering chatbot. On paper it was a familiar problem: put the documents in a vector store, retrieve the relevant pieces for each question, and let a language model write the answer. Retrieval-augmented generation (RAG), the kind of thing most tutorials cover in an afternoon.</p><p>The catch was in the requirements. The answers had to be precise. The bot could not hallucinate or fill gaps with plausible-sounding guesses. If it wasn’t confident, it had to stop and hand the conversation to a human admin instead of answering.</p><p>That changes the problem completely. Building a RAG chatbot is not the hard part. <strong>The hard part is being confident about it.</strong> Every change you make, whether it’s a new chunk size, a different embedding model or a reranker, should come with an answer to one question: <em>did it help, and by how much?</em></p><p>And a typical RAG pipeline has a lot of knobs:</p><ul><li><strong>Chunking</strong>: how documents are split, and how big the pieces are.</li><li><strong>Embeddings</strong>: which model turns text into vectors.</li><li><strong>Search</strong>: keyword search, semantic search, or a hybrid of both.</li><li><strong>Reranking</strong>: whether a second model reorders the results.</li><li><strong>Query rewriting</strong>: techniques like HyDE (Hypothetical Document Embeddings), which searches with a model-written draft answer instead of the raw question.</li><li><strong>Top K</strong>: how many chunks the model gets to read.</li></ul><blockquote><a href="https://medium.com/@yeyintaung.ya276/the-knobs-of-a-rag-system-what-you-can-actually-control-41fa9d85ceae"><em>[REFERENCE: article(s) on RAG tuning knobs]</em></a></blockquote><p>Each knob comes with its own advice, benchmarks and blog posts. None of them tell you what works on <em>your</em> documents and <em>your</em> questions. Tuning by feel (change a setting, ask the bot a few questions, decide it “seems better”) doesn’t hold up when a wrong answer is worse than no answer.</p><p>I needed a way to find the right knob, set it to the right value, and <em>know</em> I had. So I built <strong>RAG Playground</strong>.</p><h3>What RAG Playground is</h3><p>RAG Playground is a self-hosted platform for building retrieval-augmented agents and measuring whether they actually retrieve the right information. It puts the whole loop in one console:</p><ul><li><strong>Build</strong>: agents with prompts, tools, knowledge and handoffs, configured in the UI.</li><li><strong>Ground</strong>: knowledge bases with configurable chunking, hybrid search, reranking and HyDE.</li><li><strong>Measure</strong>: generated question/answer datasets and experiments that score every change.</li><li><strong>Ship</strong>: an embeddable chat widget, with live supervision and human takeover.</li></ul><p>The measure step is the heart of it, so let’s start with the knobs it measures.</p><h3>Every knob, in one form</h3><p>A knowledge base is where the knobs live. Chunking, indexing and retrieval are all set in one form:</p><ul><li><strong>Small-to-big chunking</strong>: documents are split into large <em>parent</em> chunks (by fixed size, recursively, or semantically at topic breaks), and each parent is split into small <em>child</em> chunks. The children are what get searched, and the parents are what the model reads. You get precise matching and full context.</li><li><strong>Hybrid search</strong>: BM25 keyword search plus any number of dense embedding models, merged with reciprocal rank fusion, a method that combines the rankings from several searches into one.</li><li><strong>Reranking</strong>: an optional cross-encoder or late-interaction model reorders the candidates against the original question.</li><li><strong>HyDE</strong>: optionally search with a hypothetical answer instead of the raw question.</li></ul><p>PDFs and scanned images are run through OCR (Typhoon OCR) on the way in, so the same pipeline works on documents that were never text to begin with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcMqGygBUEsflsuID-Iggw.png" /></figure><h3>A test set, generated from your own documents</h3><p>You can’t measure anything without questions that have known answers. Writing them by hand is slow, so the playground generates them.</p><p>Upload a zip of documents, pick a chat model, and choose a mix of question types:</p><ul><li><strong>simple</strong>: answered by one chunk, asked plainly.</li><li><strong>reasoning</strong>: needs an inference over the text, not a lookup.</li><li><strong>multi_context</strong>: needs two or more chunks combined.</li><li><strong>conditional</strong>: the answer depends on a condition in the question.</li></ul><p>Each pair stores the question, the answer, its category, any labels you add, the source file and, most importantly, the <strong>golden text</strong>: the exact passage the answer comes from. The golden text is what makes automatic scoring possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDsvceHSQHv2Wo_AKAoAcA.png" /></figure><h3>Experiments: one run per change</h3><p>An experiment takes a dataset, builds a knowledge base with the settings you choose (or reuses one), searches it with every question, and scores what comes back. A retrieved chunk counts as <strong>relevant</strong> when it comes from the right file and contains at least one golden sentence.</p><p>Every run produces four metrics:</p><ul><li><strong>Context precision</strong>: the share of retrieved chunks that are relevant.</li><li><strong>Context recall</strong>: the share of golden sentences found anywhere in the results.</li><li><strong>Hit rate</strong>: whether any retrieved chunk was relevant at all.</li><li><strong>MRR (mean reciprocal rank)</strong>: how high up the list the first relevant chunk appears.</li></ul><p>Each score is shown against the best run so far on the same dataset: a tick mark on the bar, with the change next to it in green or red. The breakdown by category and label shows <em>where</em> the system is weak, not just <em>that</em> it is. In this run, multi-context questions scored lowest, which makes them the obvious next target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZw0e6ykDyY-zTC3-sJ93Q.png" /></figure><h3>Watching the numbers move</h3><p>The dataset’s Experiments tab charts every metric across every run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzpuNKeShVEsOJQgd1GFFg.png" /></figure><p>Even this small demo set (10 questions from one essay) tells a story:</p><ul><li><strong>Run #1</strong> (top 3, no reranker): context recall was around 0.49.</li><li><strong>Run #3</strong> (top 5, with a reranker): recall jumped to about 0.74, and hit rate and MRR rose from 0.80 to 0.90.</li><li><strong>Run #5</strong> (semantic chunking, a cross-encoder reranker and HyDE): hit rate reached 1.00, MRR 0.93 and recall 0.77.</li></ul><p>One line never moved. Context precision stayed around 0.30 in every run. Pulling back five chunks to find one or two relevant ones means the model also reads three or four it doesn’t need. You’d never notice that trade-off by chatting with the bot, but it’s obvious on a chart.</p><h3>Looking at the misses</h3><p>Averages tell you something is wrong. Individual questions tell you why. Every question in a run is marked <strong>full</strong>, <strong>partial</strong> or <strong>miss</strong>, and opening one shows each retrieved chunk with the golden sentences it caught highlighted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hr14Ki92HAAxVOKHT036Ag.png" /></figure><p>Here a multi-context question scored partial: the top chunk caught the sentences about the Lisp conference talk, but not the whole passage behind the answer. That’s the difference between knowing “recall is 0.77” and knowing exactly which passage your retrieval keeps missing.</p><h3>From measurement to a chatbot</h3><p>Once retrieval is tuned, the same console builds and ships the chatbot itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B3FWVV8O7WcK_Re2CA2npQ.png" /></figure><ul><li><strong>Agents</strong>: each one has its own model, prompt, HTTP tools and knowledge base, and agents can hand a conversation to one another.</li><li><strong>Test runs</strong>: a live trace of every message, tool call, retrieval setting and timing, so you can see exactly what the agent searched for and what came back.</li><li><strong>Chat widget</strong>: two script tags embed the chatbot on any site, with streaming replies.</li><li><strong>Control Panel</strong>: admins see live sessions, can watch any conversation, and can take one over. This is the human-in-the-loop path the original requirement called for.</li></ul><h3>Conclusion</h3><p>Building the RAG chatbot was the easy part. Knowing whether it was any good took a system.</p><p>The biggest shift is that tuning becomes evidence instead of opinion. Without measurement, a change “feels better” after a handful of questions. With it, every change is a numbered run, scored on the same questions, compared against the best so far, and broken down by question type. A regression shows up right away. An improvement comes with a size. Even a metric that doesn’t move, like precision here, tells you something.</p><p>It also changes what you look at first. A chatbot can’t answer correctly from context it never retrieved. All it can do is refuse or make something up. Measuring retrieval first means generation starts from the right material, and “I don’t know” becomes a real signal instead of a symptom of bad search.</p><p>There’s more to do. For now, experiments score retrieval only, and the agent’s final answer isn’t part of the score. The natural next layer is checking the answers themselves: is each one faithful to the retrieved text, and does the bot decline when it should? Until then, the Control Panel keeps a human one click away.</p><p>If you’re building a RAG system where a wrong answer costs more than no answer, my advice is simple: build the evaluation loop before you start tuning. Otherwise you aren’t tuning. You’re guessing.</p><p>The code is on GitHub: <a href="https://github.com/yeaung276/RAG-Playground">github.com/yeaung276/RAG-Playground</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53670c34b6a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turning the Knobs: What the Metrics Actually Told Me]]></title>
            <link>https://medium.com/@yeaung276/turning-the-knobs-what-the-metrics-actually-told-me-3644062edd86?source=rss-b28c8c23a257------2</link>
            <guid isPermaLink="false">https://medium.com/p/3644062edd86</guid>
            <category><![CDATA[raga]]></category>
            <category><![CDATA[evaluation]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[stories]]></category>
            <dc:creator><![CDATA[Ye Aung]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 07:35:18 GMT</pubDate>
            <atom:updated>2026-08-17T07:35:18.868Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ms1fXDRtyIm7BxA347OlTw.jpeg" /></figure><p>You have a RAG system, and it isn’t good enough. So you do what everyone does: reach for the next technique. A reranker, because a tutorial swore by it. Hybrid search, because Claude suggested it. Better chunking, bigger embeddings, query expansion, each one bolted on in the faith that it should help. Some of it moves the numbers. Most of it, you can’t tell.</p><p>I had a real retrieval system running against a real corpus, and the evaluation came back mediocre. Not broken, just unremarkable: the kind of scores that are hard to argue with and impossible to act on. I could keep stacking techniques, but I had no way to say what any single one had bought me, or what it had quietly cost somewhere else.</p><p>This is the story of how I stopped guessing. Not a list of the settings that happened to work for me, but a way to know which knob moves your system, by how much, and at what price.</p><blockquote>This is the second of two pieces. The first, [The Knobs of a RAG System], lays out every dial worth turning across ingestion, indexing, and retrieval. If you already know your way around RAG, start here. If a term like reranking or parent/child indexing needs a refresher, that piece is the map to this one’s journey.</blockquote><p><a href="https://medium.com/@yeyintaung.ya276/the-knobs-of-a-rag-system-what-you-can-actually-control-41fa9d85ceae">The Knobs of a RAG System: What You Can Actually Control</a></p><h3>Setting up: what’s fixed, and how I’ll measure it</h3><p>Every corpus is different, and so is every optimal configuration. The settings I landed on may not be the settings you land on for yours. Tutorials cover what to build, and rarely tell you why. I’ll walk through one real build, on a real corpus, but I won’t stop at every knob or lay out every piece of evidence. Sometimes I’ll move fast, and sometimes you’ll look at the same data and make a different call than I did. That’s fine. The point is to reason from the evidence, not to copy my answers.</p><p>Two things stay fixed throughout. The corpus is <strong>Thai legal text</strong>, which matters because most tooling quietly assumes English. The embedder is <strong>BGE-M3</strong>, pretrained on a decent amount of Thai. Chunking is <strong>parent-child:</strong> semantic parent with recursive children, <strong>search the small chunk, feed the larger parent to the generator</strong>. I’m not tuning the embedding model or the chunking here, because if everything moves at once, no result tells you anything. Fix two things, and everything else becomes the search space.</p><p><strong>You can’t tune what you can’t measure</strong>, so the first build is the metrics and evaluation dataset, not the retriever. The popular choice for RAG is a RAGAS-style suite, but those metrics mostly grade the generation. That isn’t the part I was worried about. A modern LLM, handed the right passage, answers it well. Retrieval is the dominant failure mode and the harder one to measure, so that’s where I pointed the ruler: standard information-retrieval metrics <strong>(context precision, context recall, MRR, MAP, nDCG)</strong>, measuring whether the right chunk comes back at all and where it lands.</p><p>The dataset is built from the same documents the system retrieves against. I extracted the text with Typhoon OCR, then had an LLM generate, a set of questions, a paraphrase of it, an answer, and a verbatim gold quote from the source from each document. It’s a plain QA-with-gold shape, chosen so a failure can be traced to one place. Each item is also typed into one of five categories, so a low score tells you <em>where</em> the system breaks, not just that it did.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bcm3V7sK_jmgRDVAeFofJg.png" /></figure><h3>When the ruler is the bug: fixing the dataset before trusting a number</h3><p>The numbers from the pure baseline came back so low that they didn’t say “mediocre,” they said “something is broken.”</p><p>So I audited the pipeline in order, cheapest suspect first: the metric calculation, then retrieval, then aggregation, then the dataset itself. <strong>The dataset was the fault.</strong> The gold quotes couldn’t be found in the chunks they came from, so correct retrievals scored as misses. Two things caused it. First, <strong>encoding</strong>: Thai writes the same character or word more than one way, and my gold lookup used exact string match, so variants failed silently. Second, <strong>tables</strong>: a table can be stored as HTML or as markdown, so the generated gold and the corpus described the same table in different characters and never matched.</p><p>I had two ways out. <strong>Score by overlap ratio, or normalize the corpus</strong> to one form and keep exact match. I chose to normalize. Overlap scoring has problems. For example, gold that says “expires in 3 months” would pass against a chunk that says “4 months,” a factual miss scored as a hit. It also invites inflation, where generic gold matches boilerplate and credits the wrong chunk. Exact match refuses both. So I normalized the encodings and the tables to one form and tightened until every gold string could be found in the chunk that contained it. I</p><p>If there’s one lesson here, it’s this: <strong>always check the quality of the dataset and do the necessary exploratory analysis and preprocessing.</strong> Because a broken instrument reads exactly like a broken system, and you can waste a long time tuning the wrong one.</p><h3>Baseline BM25: barely over half the evidence retrieved, and the tokenizer is the suspect</h3><p>With the dataset fixed, I ran the evaluation with BM25 on raw OCR text, a plain whitespace-and-regex tokenizer, nothing cleaned. This is the baseline. <strong>Recall climbed roughly linearly with k, up about 140% from 0.236 at k=1 to 0.567 at k=10,</strong> still rising at k=10 with no sign of flattening. However it is barely over half and ~40% of the gold text never surfaces at all.</p><p>The category breakdown says the same thing from another angle. Questions where <strong>the answer lives in a few exact keywords(inference and literal)</strong>, score <strong>highest</strong>. The ones where <strong>the answer is spread across several sentences(list and multi-hop)</strong> score <strong>lowest</strong>. BM25 does fine when the answer is concentrated and falls apart when it’s scattered, because keyword match grabs one fragment and misses the rest.</p><p><strong>The tokenizer is the suspect</strong>. It splits on whitespace, but Thai is written with no spaces between words. So the “tokens” it produces aren’t words, they’re whole runs of text, and BM25 is matching on garbage units. Replace the whitespace split with real Thai word segmentation, and recall should rise, most for the categories that depend on covering many terms rather than one rare keyword: list and multi-hop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*bqsCQA1VLpnDVoN-oMkbBA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*57FkQgDK2sxrvVN-0yoUWw.png" /></figure><h3>Thai word segmentation: teaching the tokenizer where words end lifts the starving categories most</h3><p>Thai is written scriptio continua: no spaces between words, no sentence-final punctuation. The spaces that do exist are unreliable and ambiguous. This means default LangChain and LlamaIndex separators (., \n\n, whitespace word tokenizer) either never fire or fire in the wrong places. Term frequency computed on top of that is near-useless.</p><p>The fix is to teach the pipeline where Thai words actually end. I ran the text through <strong>PyThaiNLP</strong> to segment it into real words and sentences before anything else touched it, so the chunker works on words. Tables are also cleaned up at the same time: strip the HTML tags, break the cell text into words, and keep each number whole, so table content also reaches term frequency as real units instead of markup.</p><p>The result matched the prediction. recall@10 rose <strong>about 9% to 0.619, nDCG@10 about 11% to 0.467</strong> . The categories that were starving gained most: <strong>multi-hop up about 17% to 0.616, list up about 15% to 0.507. Literal moved least, about 7%,</strong> because it was already matching on rare exact tokens and had the least to gain from better coverage. The floor rose where the answer is scattered, which is exactly where segmentation adds terms to match against.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*PpRHVzsp7XM5r3glXGK5xQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*wT6MofeYPhSh6d8RO2lAUA.png" /></figure><h3>Parent-as-child trap: a recall gain that was secretly a regression</h3><p>The next idea was cheap to try. The semantic chunker already produces parent chunks, larger and more coherent than the children. So I added them into <strong>the same index the children live in, parent-as-child, both sitting in one pool that BM25 searches over</strong>. Term frequency computed over the bigger, richer parent text is more stable than the sparse counts on a small child, and better term statistics should mean better scoring. So I expected recall to rise.</p><p>recall@10 did rise, about 4% from 0.619 to 0.641. On the headline it looked like a win. Then I looked at the top of the list. recall@1 had collapsed about 25%, from 0.281 to 0.210, and every ranking metric fell with it: nDCG@10 down about 6%, MRR@10 and MAP@10 both down about 10%. The extra recall was arriving deep in the list while the top ranks got worse.</p><p><strong>The mechanism is IDF</strong>. The parents are large and repetitive, and sitting in the same index they skew the document frequencies BM25 depends on, inflating common terms and flattening the rare ones that make a precise match stand out. The precise small chunks that used to rank first got pushed down by their own parents. A generator only reads the top few results, so a gain that lives deep in the list against a loss at rank 1 is not a gain with a caveat. I dropped parent-as-child and went back to indexing the children alone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ut_8848EIV4ra1Kzk9NVGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Dn7QyFjo-h3UV2q3Ks5Zpg.png" /></figure><h3>Dense vs sparse: the shock that keyword search beat the embeddings</h3><p>The lexical side felt close to its ceiling, so time to bring in dense retrieval with BGE-M3 and cosine similarity, on the same parent-child semantic chunking. Dense matches on meaning rather than tokens, so it should catch the paraphrases BM25 misses and pull ahead where lexical matching structurally can’t.</p><p>It didn’t. Dense trailed BM25 on every aggregate: r<strong>ecall@10 about 4% lower,</strong> 0.605 against 0.633, <strong>nDCG@10 about 6% lower</strong>, 0.495 against 0.526. The only place it edged ahead was list, about 1%, with a tie on inference. This runs against the usual assumption that dense beats sparse.</p><p>The reason is that cosine over two whole-text vectors is blunt. Collapsing a passage into one vector throws away detail, so a chunk that really answers the question can still fail to score as similar. <strong>There is also the question-answer mismatch</strong>, one asks and one states, and cosine could scores them as far apart. <strong>HyDE</strong> fixes this by embedding a hypothetical answer instead of the question, but it adds a generation step and latency, so I left it for later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*CmLjRGXASWvboXUC3gDhRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*-v-bz4M1ZC4TXWM3QECfBg.png" /><figcaption>Recall comparison between dense and sparse</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*h7-Ja3kLMX-wAC7CdxjDGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*4Z4shf3pI-vKwc7YGVWbZw.png" /><figcaption>nDCG comparison between dense and sparse</figcaption></figure><h3>RRF fusion: combining both retrievers barely helped, because they miss the same items</h3><p>Dense and BM25 didn’t just differ in total, they won different categories: dense took list, BM25 kept the rest. <strong>If the two are failing on different items, then combining them should recover both sets and lift the whole thing</strong>. That’s the hope behind RRF, which fuses the two ranked lists into one. If it works, the gain tells me the retrievers are complementary. If it doesn’t, the questions they both miss are simply hard for both, and no amount of fusing lexical and dense will reach them.</p><p><strong>The result barely moved</strong>. recall@10 gained about 2% over the best single retriever, and ranking was flat, nDCG essentially unchanged at 0.528 against 0.526, MRR identical at 0.484. If fusion had found a complementary set, the reordering would have shown up in MRR. It didn’t, which means BM25 and dense are missing the same items, not different ones. There’s no union to recover. The hard questions are hard for both paradigms.</p><p>Reaching them would mean going back further than retrieval, to preprocessing that enriches the chunks with signal to match on, like filterable tags. That’s a bigger effort, and one I set aside for now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*PuIreqS61xl1ON8tN187-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*-XILVhzulX73GMFTHApz9Q.png" /></figure><h3>Widening k: the curve that revealed a ranking problem, not a retrieval one</h3><p>Across every run so far, one thing kept repeating: <strong>recall climbed with k and never flattened.</strong> That’s a loose thread worth pulling before spending on a bigger model. So instead of changing the retriever, I just widened k and watched how far recall would go.</p><p>Recall climbed about 17% from k=10 to k=40, 0.620 to 0.726, and <strong>it was still rising at 40</strong>. Over that same range MRR was pinned, up about 1%, 0.484 to 0.490. Recall rising means the gold enters the candidate pool as the net widens. MRR staying flat means its rank position isn’t improving, it’s just being included at all. Gold in the pool but ranked too deep to use: <strong>that shifts the problem from retrieval to ranking</strong></p><p>List is still worst at k=40, 0.616, well behind the rest even with the net thrown wide. If list’s gold were merely ranked deep, widening k would have pulled it up like the others. It didn’t, so part of list’s problem is upstream, in chunking or retrieval, not ranking alone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*H3HmIq2WBv-ugdzK3iUUog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*9xZfRZdfMWGcVvmTgiP1EQ.png" /></figure><h3>The reranker the data asked for: a cross-encoder fixes ranking where the curve predicted</h3><p>The k-sweep settle the bottleneck is ranking, not retrieval. <strong>The move is retrieve wide, then rerank tight.</strong> I pulled a pool of 50 child candidates and ran a BGE cross-encoder over them.</p><p>A cross-encoder works differently from the bi-encoder. Dense embeds the question and the chunk separately and measures the cosine between them, which is too blunt to tell an answer from an echo. A cross-encoder reads the question and the chunk together and scores how well one answers the other. That joint read is exactly the judgment cosine couldn’t make, which is why it can fix what dense couldn’t.</p><p>If the gold was already in the pool and only ranked too deep, then a reranker should jump the top-rank metrics, and boost recall. From the result, recall@1 rose about 13%(0.409 → 0.464) and MRR@10 about 10% (0.490 → 0.540), while recall@10 shifted only about 3%, to 0.672.</p><p>The reranker runs slow, though. It scores every query-chunk pair at query time, heavy on any hardware and worse on CPU, so a GPU or a late-interaction model like ColBERT is the cheaper path if latency bites. And it didn’t fix everything: list is still worst at recall@10 0.560, so part of its trouble was never ranking. That’s the residual for per-sample error analysis, over-generic gold, boilerplate text, answers split across non-contiguous chunks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*UrAU8cJZeEJ5fPrmIeEM_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*vc4NluzOC7msuc7QSWfNPA.png" /></figure><h3>recall@1 nearly doubled, and the method is why</h3><p>Baseline to final, recall@10 rose about 19%, 0.567 to 0.672, and recall@1 nearly doubled, up about 97%, 0.236 to 0.464. The system got substantially better at putting the right chunk where the generator would actually read it.</p><p>But the number isn’t the point. Every gain came from finding the bottleneck before paying to fix it. Segmentation worked because the tokenizer was the measured fault. Parent-as-child got dropped because the top ranks said so. The reranker worked because the k-curve proved the gold was already in the pool and only ranked too deep, not because a tutorial called it best practice. No knob turned on assumption, each one answered a specific reading of the data.</p><p>That’s the part that transfers. Your corpus will have a different optimum, and your numbers won’t match mine. The loop will: build the ruler first, read every metric before you touch a knob, and let the data name the next move. The configuration is mine. The method is yours to reuse.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3644062edd86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Knobs of a RAG System: What You Can Actually Control]]></title>
            <link>https://medium.com/@yeaung276/the-knobs-of-a-rag-system-what-you-can-actually-control-41fa9d85ceae?source=rss-b28c8c23a257------2</link>
            <guid isPermaLink="false">https://medium.com/p/41fa9d85ceae</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[evaluation]]></category>
            <dc:creator><![CDATA[Ye Aung]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 07:15:36 GMT</pubDate>
            <atom:updated>2026-08-17T07:36:12.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*JRoWOFoLnpeYgUGR79CUuQ.jpeg" /></figure><h3>Introduction</h3><p>A lot of teams treat a RAG system like ordinary software: build it once, ship it, done. But that’s not how these systems behave. The parameters that work for one use case often fall apart on another — the same chunking, the same embedding model, the same retrieval settings won’t transfer cleanly from one corpus to the next.</p><p>RAG systems are better understood as ML systems: non-deterministic, data-driven, and only as good as your ability to observe them. You can’t reason about them purely from the code, because the code isn’t where the behavior lives — the data and the model are. So you need a way to monitor them, evaluate them against real metrics, and evolve them as the corpus and the queries change. Ordinary software benefits from that iterative mindset; for a non-deterministic, hard-to-explain system, it’s not optional.</p><p>Production makes this sharper. Real systems are messy and unpredictable, and the gap between a demo that works and a system that holds up under real queries is exactly the part nobody streamlines.</p><p>Already comfortable with RAG and just want the build story? Skip to [Turning the Knobs], where I tune a real system and let the metrics call every move. Otherwise, read on — this piece is the map that one uses.</p><p><a href="https://medium.com/@yeyintaung.ya276/turning-the-knobs-what-the-metrics-actually-told-me-3644062edd86">Turning the Knobs: What the Metrics Actually Told Me</a></p><h3>Anatomy of a RAG system and the Things you can Control</h3><p>A RAG system breaks into three major components:</p><ol><li>Ingestion pipeline</li><li>Indexing pipeline</li><li>Retrieval pipeline</li></ol><p>Each stage has its own dials and knobs, and each solves a different domain-specific problem. Let’s take them one at a time.</p><h3>Ingestion Pipeline</h3><p>The ingestion pipeline is the first stage, and everything after it inherits what it produces — retrieval, ranking, and generation can’t recover information that was mangled on the way in. So the goal here isn’t just pulling text out of a file; it’s pulling it out with its structure intact. Headings, tables, page boundaries — the indexing stage downstream wants that shape to work with, not a flat, orderless wall of text. That’s structural parsing, and it’s the theme of this stage.</p><p>For a lot of documents this isn’t hard. Formats like DOCX and PPTX carry deliberate semantic structure you can parse programmatically. The trouble starts with scanned documents and complex layout. You need OCR, and not just an OCR model but a pipeline with layout detection in front of it to recover the shape. Whether you even need that depends on your retrieval requirements; some systems don’t need fine structure, and skipping it saves real cost. Luckily layout detection is mature enough that single model can detect structure across a wide variety of languages just fine. The trouble is recognition: some models are good at English but worse in others, some handle tables well but fall apart on math equations, and a document with multiple languages on one page is harder still. Pick the right model for your use case, don’t blindly trust one, and experiment.</p><p>Whatever the format, a document doesn’t come out as one thing — it comes out as text, tables, and images. Three kinds of content, and each behaves differently once you try to make it searchable: a paragraph, a table, and a figure can’t be treated the same way. Getting them out cleanly was ingestion’s job. Deciding what to do with each is where the next stage begins.</p><h3>Indexing Pipeline</h3><p>This is the stage that makes what ingestion produced actually searchable. And here a lot of teams jump straight into vector databases, embedding models, and implementation — which is the wrong first move. Before any of that, set up an evaluation criterion and decide the metric you want to optimize. Remember these systems are non-deterministic and opaque by nature; you don’t always understand how things work at the core. So you set up the evaluation first, then run experiments to find the parameters that actually perform.</p><p>These are the parameters worth experimenting with:</p><ul><li><strong>Chunking strategy</strong> — size, overlap, and boundary method (fixed-token, recursive, semantic, or structural). The most consequential knob, and the most corpus-dependent; there’s no default that’s safe to assume.</li><li><strong>Embedding model</strong> — dimensionality, context window, and how well it fits your corpus language. A model strong in English can embed another language poorly, which quietly wrecks retrieval.</li><li><strong>Sparse, dense, or hybrid</strong> — dense embeddings, keyword/BM25, or both fused. Hybrid is the closest thing to a safe default; keyword search catches exact terms that embeddings miss.</li><li><strong>What you index</strong> — the thing you embed doesn’t have to be the raw chunk. It can be a summary of the chunk (<em>summary indexing</em>), an augmented version carrying surrounding context (<em>contextual retrieval</em>), or synthetic questions the chunk would answer (<em>doc2query</em>), so a query matches against a question instead of raw text</li><li><strong>Parent/child indexing</strong> — embed small chunks so retrieval stays precise, but return the larger parent so the generator gets enough context. What you search on and what you feed the model don’t have to be the same size.</li><li><strong>Modality handling</strong> — how tables and images become searchable: flatten them to text, summarize them, caption them, or embed them directly. A table flattened carelessly is a table lost.</li><li><strong>Metadata and filtering</strong> — page, section, doc type attached to each chunk so retrieval can narrow before it searches. Cheap and underused — but useless unless the query side actually applies the filters.</li><li><strong>Index structure</strong> — a flat vector index, a knowledge graph(GraphRAG), or both. This one reshapes the others: go with a graph and chunking turns into deciding extraction windows, metadata turns into designing an ontology. It earns its cost on multi-hop or aggregate questions, rarely on plain lookup.</li></ul><h3>Retreival Pipeline</h3><p>This is where every upstream choice gets judged. All that work in ingestion and indexing existed for one purpose: so that when a query arrives, the right chunks come back. How you index is driven by how you retrieve. Every indexing choice was a bet about what this stage would need, and this is where you find out whether those bets hold. Same discipline as before: you don’t guess which of these to turn, you measure.</p><p>The knobs worth experimenting with:</p><ul><li><strong>Reranking</strong> — a second-pass model (usually a cross-encoder) reorders the top candidates after the initial search. This is the highest-leverage knob in the whole stage: first-pass retrieval is tuned for recall, reranking buys back precision, and the pattern of retrieve-wide-then-rerank-tight is close to a default worth reaching for before anything fancier.</li><li><strong>Query transformation</strong> — reshape the query before it searches. Embed a hypothetical answer instead of the question (<em>HyDE</em>), rephrase the query into several and pool the results (<em>multi-query</em>), or split a multi-part question into sub-questions and retrieve for each (<em>decomposition</em>).</li><li><strong>Fusion</strong> — when you run dense and sparse together, how you combine their two result lists: reciprocal rank fusion (<em>RRF</em>), or a weighted blend you tune. The build was an indexing decision; how you merge the scores is decided here.</li><li><strong>Metadata filtering</strong> — actually constructing the filter at query time: narrow to a section, a date range, a doc type before searching. The metadata was attached upstream; it does nothing until this step reads the query and sets the predicate.</li><li><strong>Top-k and retrieval depth</strong> — how many candidates you pull, and how many survive to the generator. Too few starves the answer, too many drowns it in noise — and it interacts directly with parent/child, since one small hit can expand into a large passage.</li><li><strong>Routing</strong> — when you hold more than one index or strategy, deciding which one a query goes to. Specialist: it only matters once you have several retrievers, but then picking the wrong one wastes the entire pipeline behind it.</li></ul><p>But a list of knobs isn’t a system. Knowing chunk size matters doesn’t tell you what to set it to — that answer lives in your corpus, your queries, and what the metrics say when you run it. So the real question: once all these knobs exist, how do you know which way to turn them? That’s the next piece — [Turning the Knobs], where I take one real build on a Thai legal corpus and let the metrics decide every move.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41fa9d85ceae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallelism, Topology, and One Bad Config]]></title>
            <link>https://medium.com/@yeaung276/parallelism-topology-and-one-bad-config-f825610c9837?source=rss-b28c8c23a257------2</link>
            <guid isPermaLink="false">https://medium.com/p/f825610c9837</guid>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Ye Aung]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 05:52:54 GMT</pubDate>
            <atom:updated>2026-07-05T06:06:50.344Z</atom:updated>
            <content:encoded><![CDATA[<p>A story about deploying a model across multiple GPUs and what I learned along the way</p><p>Say you have to serve a model to a few hundred concurrent users. To make life easier, assume the GPU is big enough to hold the whole model, so no sharding, no splitting weights across cards. You run it, and the numbers aren’t bad: TTFT and TPOT are both acceptable. But “acceptable” isn’t what you want. You want them lower, and you know they won’t stay where they are as requests start queuing and KV cache fills. You have two nodes with 4 GPUs each, but only 4 are available to you; the rest are reserved. How do you spend them?</p><p>The easy answer is to run an identical copy of the model on every GPU and load balance across them. It works, and it’s simple. But it only buys throughput. Each request is still served by one GPU, so per-request latency doesn’t move. And because replicas don’t pool memory, a request’s KV cache still lives on one card, so the longest prompt you can accept stays capped where it was. You can handle the crowd, but no one waits less and no one can send a longer prompt.</p><p>This post is how I worked through that design, the reasoning, the wrong turns, and the pitfalls I hit getting there. There’s no single right way to spread a model across GPUs, just trade-offs, and what worked for my case won’t be the answer for every case.</p><h3>Designing the system</h3><h4>Data parallelism</h4><p>The obvious starting point is data parallelism. Deploy independent model replicas on each GPU, put a load balancer in front, done. This is operationally clean. Each GPU runs a full independent copy of the model. Failures are isolated to a single replica. Throughput scales linearly with the number of replicas.</p><p>However it does nothing for latency. Each replica still processes requests at the same speed as a single GPU would. A request hitting any one of those replicas experiences the same KV cache pressure and the same compute time. You are distributing load, not accelerating inference. Given that latency in ideal conditions is already barely acceptable, spreading the same slow inference across more GPUs is not a solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0cOiwA8S7GNCdnQLsPh0mA.gif" /></figure><h4>Pipeline parallelism</h4><p>Pipeline parallelism works by partitioning the model’s layers across GPUs, each handling a few layers of the transformer stack and passing activations to the next at the layer boundary. It has low communication cost since only activations cross between GPUs, in small point-to-point transfers. This makes it the natural choice for scaling across nodes that lack high-bandwidth interconnect. It also lets you shard a model across multiple GPUs when a single GPU can’t hold the entire weight set.</p><p>For inference, though, it has a fundamental problem: the pipeline bubble. In training you hide the bubble by filling the pipeline with microbatches while GPU 2 processes batch N, GPU 1 is already working on batch N+1 and the bubble ratio shrinks as the microbatch count grows. Online inference doesn’t have that luxury. Requests arrive one at a time on the latency-critical path, so at low concurrency each stage boundary is idle time a user waits on directly, and other parallelism strategies use the extra GPUs better.</p><p>More to the point, none of this applies to our situation. Pipeline parallelism exists to solve a memory problem: running models that don’t fit on a single GPU. Qwen3.5 9B fits. Using it here would only add inter-GPU communication latency and pipeline bubbles for no architectural benefit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OoY2pr_oDy7jikI1zJYGbg.gif" /></figure><h4>Tensor parallelism</h4><p>Tensor parallelism takes a different approach. Rather than assigning different layers to different GPUs, it distributes the computation within each layer across GPUs. For a matrix multiplication, each GPU holds a shard of the weight matrix, computes its partial result in parallel with the others, then performs an all-reduce to produce the final output. Every layer runs on every GPU simultaneously.</p><p>The effect on latency is direct: the compute time per layer is divided across the GPUs in the tensor parallel group. A matrix multiplication that previously occupied one GPU now completes in roughly half the time across two, with only a single synchronization step per layer to combine results.</p><p>The cost is communication. Every layer requires an all-reduce across the entire tensor parallel group, every GPU, every layer, every request. That chatter adds up, and this is where GPU topology becomes important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EbeAABnLFrQA7miXpnvVbg.gif" /></figure><p>We settled on a hybrid of data and tensor parallelism. On each node, two GPUs run a single Qwen3.5 9B instance under tensor parallelism, improving latency. Traffic is then load balanced across the two nodes, adding fault tolerance when one node is down and throughput when both are up.</p><p>But “two GPUs under tensor parallelism” create a question: <em>which</em> two? On a multi-GPU node the GPUs aren’t all equivalent — how any given pair is wired together sets how fast they can talk. Pick the wrong pair and the synchronization that was supposed to cut latency starts adding it instead.</p><h3>GPU Topology</h3><p>Any distributed or concurrent workload needs a path for processes to exchange data, and the speed of that path bounds how fast the whole system can run. Tensor parallelism is a demanding case: the two GPUs in a TP group must exchange partial results through an all-reduce on every layer, so the link between them sits on the critical path of every request. How fast that exchange is depends entirely on how the GPUs are physically connected.</p><p>That data exchange can happen through three different mechanisms. First, GPU1 can transfer data directly to GPU2 over a dedicated point-to-point physical link (a bridge connector on PCIe, or baseboard traces on SXM2) separate from the motherboard’s PCIe lanes. This is NVLink, and it’s the fastest method. Between that and the host bounce(next) sits PCIe peer-to-peer: if both GPUs hang off the same PCIe switch, they DMA directly across it without staging through host memory.</p><p>Second, the data can be bounced through host memory: GPU2’s data is copied into a CPU-side staging buffer in system RAM, then copied down to GPU1. This is slower because it round-trips through the host. Planned, optimized prefetching can hide some of this latency, but dynamic random access is hard to optimize.</p><p>Third, and slowest: on a dual-socket machine where GPU1 hangs off CPU1 and GPU2 off CPU2, the host bounce additionally has to cross the inter-CPU link (UPI/QPI) between the two sockets, adding another hop.</p><p>vLLM relies on kernels that auto-discover this topology and use whichever channel is best available. This is why, when picking GPUs for a tensor parallel group, you choose the pair with the most direct NVLink connection between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_q_xV5acPBBHJaSREb1fng.png" /></figure><h3>From Design to Deployment</h3><h4>Compute Capability, Driver and Cuda</h4><p>Getting vLLM running meant first understanding three layers of NVIDIA abstraction, each of which has to agree with the others.</p><p>At the bottom is compute capability, a version number describing what the GPU can do. It’s fixed in silicon and decide which features any software above it can use. Above that sits the <strong>driver,</strong> the kernel that actually operates the GPU and sets a ceiling on maximum CUDA version the machine can support. On top is the <strong>CUDA toolkit and runtime</strong>, the software layer that frameworks like PyTorch link against to reach the GPU.</p><p>A vLLM image ships its own PyTorch and CUDA runtime baked in, but that runtime is useless if the GPU’s compute capability is too old for it to support. Choosing an image is really choosing a CUDA version that the driver, the runtime, and the GPU all accept at once.</p><p>The first failure came from exactly this. Running the latest vLLM image, the stack wouldn’t start because the bundled CUDA runtime was newer than the installed driver could support. This gave us two options: update the driver and reboot the server, or drop to an older vLLM image with an older CUDA runtime. Both would have worked. But updating the driver meant a reboot on a production box and a fresh set of things that could break, all to gain nothing — the V100’s compute capability caps how new a CUDA runtime it can ever run, and no driver bump changes that. Downgrading the image cost us nothing and touched nothing else, so we lowered the vLLM version.</p><p>With the CUDA version pinned, the stack came up. Model compilation took around ten minutes on first start, but it pushed through, the application finished initializing, and the smoke tests passed.</p><h4>A Suspicious Bottleneck</h4><p>With the stack running, we wired up Prometheus for vLLM and started load testing. The results were strange. GPU memory utilization sat near 2 percent, yet TTFT spiked as high as 90 seconds. That made no sense, since average prompt and generation lengths stayed flat across the run, so the work per request hadn’t changed. Something was holding requests back before the GPU ever touched them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8b8NakeSWOzNOPdvlMf66Q.png" /></figure><p>Digging into the metrics, the pattern was clear. The scheduler’s running count was pinned at 8 while the waiting queue climbed to 500 at that peak. That is a classic batching bottleneck, the kind you normally see when the GPU is saturated and requests start queuing behind it. But memory utilization here was near 2 percent, so there was plenty of KV cache headroom. Requests were queuing for no physical reason.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*3suE0kL-beg0GmrhSjh-Xg.png" /></figure><p>The cause was a single misconfigured parameter: max-num-seqs. The scheduler was never allowed to run more than 8 sequences at once, so under any real concurrency the rest just waited. (It is also a good reminder not to copy a config straight from Claude without understanding it. 🙃)</p><p>So what is the right number? It turns out to matter a lot. Set it too low and you get exactly this, an artificial ceiling that starves the GPU while requests pile up. Set it too high and the scheduler admits more sequences than the KV cache can hold, then starts swapping KV blocks between GPU and CPU memory to keep up, which thrashes throughput. The right value depends on max-seq-len, available GPU memory for the KV cache, and how much concurrency you actually expect. Once we tuned it, everything settled and ran smoothly. For a moment, anyway. 😂</p><h4>LMCache and KVCache offloading</h4><p>If you’re following along and know about caches, there’s probably a burning question in your head: what about cache locality or cache sharing between two instances? Because of load-balancer request distribution, a prefix computed on one engine isn’t visible to another engine if the next request in that sequence lands elsewhere.</p><p>This is exactly the problem KV cache offloading solves, and this is where we bring in LMCache. Instead of the KV cache living only in one engine’s GPU/CPU memory, it pushes those KV blocks out to a shared external store that every engine instance can read and write to. We used Redis as that shared store, so when engine A computes a prefix, it lands in Redis, and when the next request with that prefix hits engine B, B pulls it from Redis instead of recomputing it from scratch. One thing to actually get right is that every replica has to agree on the same chunking and serialization settings, otherwise two engines writing to the same Redis just end up with cache entries that never line up.</p><p>We also considered a prefix-aware load balancer that hashes the incoming prefix and always routes it to the same engine, so you never even need Redis in the hot path — but that means running a stateful routing layer, and we skipped it for now because the Redis-backed shared cache gets most of the benefit without that extra piece of infrastructure to build and babysit.</p><h3>So… how’d it end?</h3><p>Turns out the GPUs were never the problem. They sat there patiently doing their job while I argued with a misconfigured max-num-seqs for an entire afternoon. I spent days getting topology, parallelism strategy, and cache coherence to behave — and then got taken down by one number I could&#39;ve just read the docs for. Anyway — it works now, and I&#39;ve made my peace with it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f825610c9837" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>