<?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 Parag Patil on Medium]]></title>
        <description><![CDATA[Stories by Parag Patil on Medium]]></description>
        <link>https://medium.com/@patil-parag-oss?source=rss-966c27f82db4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*98RMf2Ek0nu4xc9pZd9Vwg.jpeg</url>
            <title>Stories by Parag Patil on Medium</title>
            <link>https://medium.com/@patil-parag-oss?source=rss-966c27f82db4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 21:00:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@patil-parag-oss/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[Putting It All Together: Optimize the Conversation, Not the Benchmark]]></title>
            <link>https://patil-parag-oss.medium.com/putting-it-all-together-optimize-the-conversation-not-the-benchmark-429f06d7e200?source=rss-966c27f82db4------2</link>
            <guid isPermaLink="false">https://medium.com/p/429f06d7e200</guid>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[local-llm]]></category>
            <category><![CDATA[gpu]]></category>
            <dc:creator><![CDATA[Parag Patil]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 07:25:39 GMT</pubDate>
            <atom:updated>2026-09-21T07:25:39.750Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 7 of the series: </em><strong><em>Stop Wasting Your GPU — A Developer’s Guide to Local LLM Optimization</em></strong></p><p>Over the previous six parts of this series, I broke GPU optimization down into five simple ideas. But after working through all five, I think the most important lesson is actually the one that sits above them: <strong>my goal isn’t to optimize FlashAttention, KV Cache, batching, or even the GPU itself. My goal is to make the conversation better while using the GPU efficiently.</strong></p><p>That distinction matters more than it initially sounds.</p><p>It is surprisingly easy to end up with a system that looks impressive on a benchmark:</p><p>GPU utilization 98%<br>Tokens/sec ↑<br>Batch size ↑<br>Concurrency ↑</p><p>while the user experiences:</p><p>Clicks Send<br> …<br> …<br> …<br>First token appears 6 seconds later</p><p>`Technically efficient?<br>Maybe.<br>Good conversational AI?<br>Probably not.</p><p>So this final article is about putting the previous six parts together and asking the question I should probably have started with:</p><blockquote><strong>What am I actually optimizing for?</strong></blockquote><h3>Where We Started</h3><p>At the beginning of this series, my GPU optimization strategy looked complicated.</p><p>I kept coming across terms such as:</p><ul><li>BF16</li><li>FP16</li><li>FlashAttention</li><li>torch.compile</li><li>KV Cache</li><li>Prefix Caching</li><li>Continuous Batching</li><li>Chunked Prefill</li><li>CUDA Graphs</li><li>Paged KV Cache</li></ul><p>Every one of them seemed important.</p><p>But understanding the individual technologies didn’t necessarily help me decide what to do with them.</p><p>Eventually I reduced the problem to five forms of waste.</p><pre>What am I wasting?         What helps?<br>----------------------------------------<br>Tensor memory              BF16 / FP16<br>Attention memory movement  FlashAttention<br>Execution efficiency       torch.compile<br>Repeated computation       KV Cache<br>GPU parallel capacity      Batching / Bucketing</pre><p>And that became the mental model for this entire series:</p><p><strong>BF16 / FP16</strong> → Make the numbers smaller.<br><strong>FlashAttention </strong>→ Move less data.<br><strong>torch.compile</strong> → Execute operations smarter.<br><strong>KV Cache </strong>→ Don’t calculate the past again.<br><strong>Batching / Bucketing</strong> → Keep the GPU busy.</p><p>Individually, each one is easy enough to understand. The interesting part is what happens when they interact.</p><h3>Let’s Follow One Conversation Through the System</h3><p>Imagine a customer asks my local conversational AI:</p><blockquote>“Based on my application, our previous conversations and the lending policy, why was my loan rejected?”</blockquote><p>The visible question is short. But the application might construct:</p><pre>System instructions        600 tokens<br>Conversation history     2,400 tokens<br>Customer context           700 tokens<br>Retrieved RAG context    4,000 tokens<br>Current question           100 tokens<br>-------------------------------------<br>Total                    7,800 tokens</pre><p>Before the first answer token appears, quite a lot has already happened. The complete flow looks more like:</p><p>User<br> ↓<br>Conversational AI API<br> ↓<br>Authentication / Session<br> ↓<br>Conversation History<br> ↓<br>RAG Retrieval<br> ↓<br>Prompt Construction<br> ↓<br>Request Queue<br> ↓<br>LLM Scheduler<br> ↓<br>GPU Prefill<br> ↓<br>Token Decode<br> ↓<br>Streaming Response<br> ↓<br>User</p><p>Only part of that flow is GPU execution. That realization is important.</p><p>Because if my user waits five seconds and only two seconds are spent inside the model, making the model 20% faster doesn’t magically turn the experience into an instant response.</p><h3>The Five Optimizations Inside That Request</h3><p>Now let’s place the five ideas into the flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*TeTK3_lBIPM1Yo_ixD2P9A.png" /></figure><p>This is the architecture I now have in my head whenever someone says:</p><blockquote>We need to optimize the local LLM.</blockquote><p>Instead of immediately reaching for a configuration flag, I try to identify which part of this flow is hurting.</p><h3>Optimization 1: Make the Numbers Smaller</h3><p>From <a href="https://medium.com/@patil-parag-oss/bf16-vs-fp16-why-smaller-numbers-make-local-llms-faster-5110971e0a69">Part 2</a>:</p><blockquote><strong>BF16 / FP16 → Make the numbers smaller.</strong></blockquote><p>If my workload can safely operate at reduced precision:</p><p>FP32 (32 bits/value)<br> ↓<br>BF16 / FP16 (16 bits/value)</p><p>then many floating-point tensors require less memory.</p><p>The result can be:</p><p>Model/Tensor Memory<strong> ↓</strong><br>Memory Bandwidth Requirement<strong> ↓</strong><br>Available VRAM<strong> ↑</strong></p><p>And the interesting question becomes:</p><blockquote><strong>What do I do with the memory I saved?</strong></blockquote><p>I can potentially spend that headroom on:</p><p>Longer context<br>More KV Cache<br>Larger batches<br>More concurrent conversations</p><p>So BF16 isn’t just a model-size optimization. It can indirectly affect serving capacity.</p><h3>Optimization 2: Move Less Data</h3><p>From <a href="https://medium.com/@patil-parag-oss/flashattention-explained-simply-stop-moving-so-much-gpu-data-9bcb121aeb2d">Part 3</a>:</p><blockquote><strong>FlashAttention → Move less data.</strong></blockquote><p>Attention is computationally expensive, but it can also generate substantial memory traffic.</p><p>Instead of repeatedly materializing large intermediate attention data in HBM, FlashAttention reorganizes the computation into GPU-friendly tiles.</p><p>My mental model remains:</p><p><strong>Traditional Attention</strong><br>Compute<br> ↓<br>HBM<br> ↓<br>Compute<br> ↓<br>HBM<br> ↓<br>Compute<br> <br><strong>FlashAttention</strong><br>Bring useful blocks close to compute<br> ↓<br>Perform related work<br> ↓<br>Accumulate result<br> ↓<br>Move on</p><p>This becomes increasingly interesting as context grows. Which means something else:</p><blockquote><strong>My RAG strategy can affect how much FlashAttention matters.</strong></blockquote><p>If I indiscriminately dump:</p><p><strong>12 retrieved documents + entire conversation history + huge system prompt</strong></p><p>into every request, I am creating a larger GPU problem upstream. Sometimes the cheapest optimization isn’t another GPU kernel.</p><p>Sometimes it’s:</p><blockquote><strong>Stop sending unnecessary tokens.</strong></blockquote><p>That is a systems lesson I didn’t appreciate when I started this series.</p><h3>Optimization 3: Execute Smarter</h3><p>From <a href="https://medium.com/@patil-parag-oss/what-does-torch-compile-actually-do-to-your-llm-4e3766cd18c4">Part 4</a>:</p><blockquote><strong>torch.compile → Execute operations smarter.</strong></blockquote><p>Even with efficient attention, the Transformer still contains many operations. Compilation gives PyTorch an opportunity to see larger pieces of computation and optimize eligible execution.</p><p><strong>Conceptually:</strong></p><p><strong>Eager</strong></p><p>Operation<br> ↓<br>Launch<br> ↓<br>Operation<br> ↓<br>Launch<br> ↓<br>Operation<br> ↓<br>Launch<br> <br><strong>Compiled</strong></p><p>Capture larger computation<br> ↓<br>Optimize eligible regions<br> ↓<br>Generate execution<br> ↓<br>Reuse</p><p>But Part 4 also taught me an important lesson:<br>Compilation Benefit ≠ Free Performance<br>I have to consider:<br>- Warm-up<br>- Graph breaks<br>- Dynamic shapes<br>- Recompilation<br>- Deployment lifetime</p><p>A persistent inference server serving thousands of requests is very different from a container that starts, handles two requests and shuts down.</p><h3>Optimization 4: Don’t Calculate the Past Again</h3><p><a href="https://medium.com/@patil-parag-oss/kv-cache-explained-stop-making-your-llm-recalculate-the-past-1893ff208d44">Part 5</a> gave me the optimization that feels most naturally connected to conversational AI:</p><blockquote><strong>KV Cache → Don’t calculate the past again.</strong></blockquote><p>During autoregressive generation:</p><p>Token 1<br> ↓<br>Token 2<br> ↓<br>Token 3<br> ↓<br>Token 4</p><p>the model repeatedly needs information about previous tokens. KV Cache stores previously computed Key and Value states so they can be reused. That improves decode efficiency.</p><p>But the trade-off is:</p><p>Less Recalculation<br> ↓<br>Faster Decode<br> <br> <strong>BUT<br> </strong><br>More Cached State<br> ↓<br>More VRAM</p><p>And that connects directly to concurrency.</p><h3>Optimization 5: Keep the GPU Busy</h3><p><a href="https://medium.com/@patil-parag-oss/your-gpu-is-powerful-so-why-is-it-sitting-idle-821aefd08836">Part 6</a> moved me from model optimization to serving optimization.</p><blockquote><strong>Batching / Bucketing → Keep the GPU busy.</strong></blockquote><p>One perfectly optimized request at a time can still be a poor use of a massively parallel GPU.</p><p>Continuous batching lets a serving engine combine useful work across active conversations.</p><p><strong>Conceptually:</strong></p><p>A ─┐<br>B ─┤<br>C ─┼── GPU<br>D ─┘</p><p>And as requests finish:</p><p>B ─┐<br>C ─┤<br>D ─┼── GPU<br>E ─┘</p><p>But <a href="https://medium.com/@patil-parag-oss/your-gpu-is-powerful-so-why-is-it-sitting-idle-821aefd08836">Part 6</a> also introduced the trade-off I think matters most in production:</p><p>More batching<br> ↓<br>Higher throughput<br> <br><strong>BUT potentially<br></strong> <br>More queueing<br> ↓<br>Higher user latency</p><p>Which brings everything back to the user.</p><h3>The GPU Doesn’t Know Whether the Conversation Feels Fast</h3><p>This sounds obvious, but I find it useful to say explicitly. The GPU knows about things such as:</p><ul><li>Kernels</li><li>Memory</li><li>Tensor operations</li><li>Batch sizes</li><li>Execution time</li></ul><p>The user cares about:</p><p>Why hasn’t anything appeared yet?<br>Why did the answer stop streaming?<br>Why is this request slower than the last one?</p><p>Those are different perspectives. My job as the developer is to connect them.</p><h3>The Three Latencies I Now Think About</h3><p>I used to talk about:</p><p><strong>LLM latency</strong></p><p>as if it were one number. I no longer do that. For conversational AI, I find three stages more useful.</p><h3>1. Queue Time</h3><p>Before the GPU even begins processing:</p><p>Request arrives<br> ↓<br>Waits for scheduler capacity<br> ↓<br>Processing begins</p><p>If requests spend two seconds in the queue, making FlashAttention 10% faster is not addressing the main problem.</p><p>Queue time tells me whether I’m reaching serving capacity.</p><h3>2. TTFT — Time to First Token</h3><p>The user clicks Send. <br>How long until something appears?</p><p>User:<br> “Why was my application rejected?”<br> ↓<br> …<br> ↓<br> “Based…”</p><p>TTFT includes the pain the user feels before the conversation starts responding.<br>For long prompts, prefill can play a large role here.<br>For overloaded systems, queue time can play an even larger one.</p><h3>3. TPOT / Inter-Token Latency</h3><p>Once generation starts:</p><p>Based<br>Based on<br>Based on your<br>Based on your application…</p><p>how quickly do tokens continue to arrive?</p><p>This determines whether the response feels fluid. A fast TTFT followed by painfully slow generation is still a poor experience.</p><p>Likewise: Slow<strong> TTFT + Fast generation </strong>isn’t necessarily good either.</p><p>I need both.</p><h3>Throughput Is the Other Side of the Equation</h3><p>Users care about latency. Infrastructure teams care about capacity.</p><p>So I also measure:</p><p>Input tokens/sec<br>Output tokens/sec<br>Requests/sec</p><p>These tell me how much useful work the system produces.</p><p>And now the core tension becomes visible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*T7zhV-6HkDqkh3rdUQOMkg.png" /></figure><p>The configuration that maximizes one may hurt the other.</p><h3>A Configuration Can Be Faster and Still Be Worse</h3><p>Imagine two hypothetical configurations.<br><strong>Configuration A</strong></p><pre>P95 TTFT          900 ms<br>TPOT              18 ms<br>Output Throughput 900 tok/s<br>GPU Utilization   72%</pre><p><strong>Configuration B</strong></p><pre>P95 TTFT          4.5 sec<br>TPOT              21 ms<br>Output Throughput 1500 tok/s<br>GPU Utilization   98%</pre><p>Which one is better?</p><p>There isn’t enough information.</p><p>For an overnight document-processing pipeline, I might prefer B. <br>For an interactive customer-facing conversational assistant, I might prefer A.<br>That’s why I increasingly dislike statements such as:<br>“Configuration B is 66% faster.”<br>Faster at what?<br>The metric needs a user or business objective behind it.</p><h3>100% GPU Utilization Can Mean Two Very Different Things</h3><p>Seeing: <strong>GPU Utilization = 99% </strong>can mean:<br><strong>Scenario 1</strong><br>- GPU is efficiently processing well-sized batches <br>- Queue is stable<br>- P95 TTFT meets SLA<br>- TPOT meets SLA<br>Excellent.</p><p>Or it can mean:</p><p><strong>Scenario 2</strong><br>- GPU completely saturated<br>- Queue growing<br>- P95 TTFT deteriorating<br>- Users waiting<br>Not excellent.</p><p>The same 99% appears in both cases. So I now distinguish:</p><blockquote><strong><em>Utilization</em></strong></blockquote><p>from:</p><blockquote><strong><em>Useful utilization within SLA</em></strong></blockquote><p>That is a much more meaningful target.</p><h3>My Real Optimization Objective</h3><p>Instead of:<br><strong>MAX(GPU utilization) </strong>or <strong>MAX(tokens/sec)</strong></p><p>I think about the objective as something closer to:<br><strong>[Maximize useful throughput]</strong><br>subject to:<br>- TTFT SLA<br>- TPOT SLA<br>- Quality Acceptable<br>- VRAM GPU Capacity<br>That’s the engineering problem.</p><h3>And Then There Is Cost</h3><p>Once the latency and throughput targets are clear, infrastructure economics become much easier to reason about.</p><p>Suppose one GPU can serve X conversations/hour while meeting the required TTFT and TPOT.<br>Then, very simplistically:<br><strong>[ CostPerConversation = {SuccessfulConversationsServed} ]</strong></p><p>This is why improving throughput without sacrificing SLA matters.</p><p>If I can make one GPU support:<br><strong>20 concurrent conversations</strong><br>instead of: <strong>10</strong><br>while maintaining the same user experience, I may need fewer GPUs for the same workload.</p><p>That is a real optimization outcome. Not just a better benchmark.</p><h3>An Illustrative Example</h3><p>Suppose a GPU deployment costs: <strong>₹100 per hour</strong><br>Purely illustrative.</p><p>Configuration A sustainably serves: <strong>500 conversations/hour</strong><br>within the required SLA.<br>Then:<br>[ CostPerConversation = <strong>100 / 500 = ₹0.20</strong> ]</p><p>Now after optimization, suppose it serves: <strong>800 conversations/hour</strong><br>within the same SLA.<br>Then:<br>[ CostPerConversation = <strong>100 / 800 = ₹0.125</strong> ]</p><p>That is the kind of outcome I can explain to both Developers &amp; Business stakeholders<br>The GPU optimization has become:</p><blockquote>lower infrastructure cost per successful conversation</blockquote><p>rather than:</p><blockquote>“We enabled FlashAttention.”</blockquote><h3>This Is How I Would Optimize a Real Local LLM</h3><p>If someone gave me a local conversational AI implementation tomorrow and asked me to optimize it, I would not enable every feature simultaneously.</p><p>I would work in stages.</p><h3>Step 1 — Establish a Real Baseline</h3><p>Before changing anything, I want to know where I am.<br>And I don’t benchmark:<br>“Hello”<br>unless “Hello” represents my production workload.<br>I build realistic scenarios.</p><p>For example:<br><strong>Short conversation</strong><br>Prompt ~500 tokens<br>Output ~150 tokens</p><p><strong>Typical RAG conversation</strong><br>Prompt ~4K tokens<br>Output ~500 tokens</p><p><strong>Long-context conversation</strong><br>Prompt ~8K tokens<br>Output ~800 tokens</p><p><strong>Mixed production traffic</strong><br>A realistic distribution<br>of short, medium and long requests</p><p>Then I measure.</p><h3>My Baseline Scorecard</h3><p>I would record something like:</p><pre>Metric                               Baseline<br>---------------------------------------------<br>P50 TTFT <br>P95 TTFT <br>P99 TTFT <br>P50 TPOT <br>P95 TPOT <br>Input tokens/sec <br>Output tokens/sec <br>Requests/sec <br>Peak VRAM <br>KV-cache utilization <br>GPU utilization <br>Queue time <br>Maximum SLA-compliant concurrency</pre><p>This becomes my control.<br>Without it, every optimization discussion becomes subjective.</p><h3>Step 2 — Reduce Precision</h3><p>Then I evaluate <strong>FP32</strong> vs <strong>BF16</strong> vs <strong>FP16 </strong>where relevant.</p><p>Or, if I’m already using weight quantization:<br>- AWQ<br>- GPTQ<br>- other supported format</p><p>I measure:<br>- VRAM<br>- TTFT<br>- TPOT<br>- Throughput<br>- Quality</p><p>The most important question isn’t:</p><blockquote>Did VRAM decrease?</blockquote><p>It’s:</p><blockquote><strong>What can I now do with the freed VRAM?</strong></blockquote><h3>Step 3 — Verify Efficient Attention</h3><p>Next I evaluate the attention backend.<br>Particularly with:<br>512-token prompt<br>2K<br>4K<br>8K+</p><p>I’m looking at:<br>- Prompt processing speed<br>- TTFT<br>- VRAM<br>- Input tokens/sec</p><p>If the optimization becomes more valuable as context grows, I now understand why.</p><h3>Step 4 — Evaluate Compiled Execution</h3><p>Then I look at model execution.<br>I compare:<br>- cold request<br>- warm request<br>- steady-state workload</p><p>I check for:<br>- Compilation time<br>- Recompilation<br>- Dynamic-shape behavior<br>- Graph breaks</p><p>If I’m using a mature inference engine such as vLLM, I verify its optimized execution path rather than blindly wrapping the model in my own torch.compile().</p><h3>Step 5 — Verify KV Cache Behavior</h3><p>Then I focus on decode.<br>I measure:<br>- TPOT<br>- Output tokens/sec<br>- KV-cache utilization<br>- VRAM<br>- Concurrency</p><p>I also determine whether prefix caching is relevant.<br>If every request shares a large stable system prefix, there may be meaningful reuse.<br>If every prompt becomes unique in its first 20 tokens, perhaps not.<br>Again:</p><blockquote>Measure the actual workload.</blockquote><h3>Step 6 — Tune Batching and Scheduling</h3><p>Only after the individual inference path is reasonably efficient do I start pushing concurrency.</p><p>For example:</p><p>1<br> ↓<br>5<br> ↓<br>10<br> ↓<br>20<br> ↓<br>32<br> ↓<br>64<br> ↓<br>128</p><p>At each level:</p><pre>Throughput      ↑  ?<br>P95 TTFT        ↑  ?<br>TPOT            ↑  ?<br>Queue depth     ↑  ?<br>KV Cache        ↑  ?<br>GPU utilization ↑  ?</pre><p>Eventually I reach a knee in the curve.<br>Something like:</p><pre>Concurrency  Throughput     P95 TTFT<br>-------------------------------------<br>1            low            excellent<br>5            ↑              excellent<br>10           ↑              good<br>20           ↑              good<br>32           ↑              acceptable<br>64           ↑ slightly     poor<br>128          flat           terrible</pre><p>The correct answer is probably not: <strong>128 </strong>just because it is the largest number.</p><p>The useful operating point might be: <strong>32 </strong>because that is the highest concurrency that still meets my SLA.</p><h3>This “Knee” Is What I Actually Want to Find</h3><p>The capacity curve often looks conceptually like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*mg8XMe7tRJTPg-YT9FH9ZA.png" /></figure><p>At first, more concurrency produces more throughput. Eventually the GPU becomes saturated. Throughput stops improving significantly. But latency continues getting worse.</p><p>That region is where:</p><p><strong>More Users<br> ↓<br>More Waiting</strong></p><p>rather than</p><p><strong>More useful throughput</strong></p><p>My goal is to operate before that point — with some headroom for bursts.</p><h3>Production Traffic Is Not a Benchmark Dataset</h3><p>There is another thing I wouldn’t ignore.<br>Real traffic has bursts.<br>For example:<br>Normal load <strong>10 concurrent users</strong></p><p>Then suddenly</p><p>50 requests arrive within 2 seconds</p><p>A benchmark based on perfectly uniform request arrival may completely miss this.</p><p>So I test:<br>- Steady load<br>- Burst load<br>- Mixed prompt lengths<br>- Mixed output lengths</p><p>And, if relevant:<br>- Large RAG prompts<br>- Short FAQ prompts<br>- Long agentic requests</p><p>This gives me a much better picture of production behavior.</p><h3>Don’t Forget the Application Outside the GPU</h3><p>At some point I also need to ask:</p><blockquote><strong>Is the GPU even the problem?</strong></blockquote><p>Consider a request breakdown:</p><pre>Authentication          50 ms<br><br>RAG retrieval          700 ms<br><br>Prompt construction     80 ms<br><br>Scheduler queue        900 ms<br><br>LLM prefill            400 ms<br><br>Generation            1200 ms</pre><p>Now suppose I spend two days reducing:</p><p>LLM prefill<br><strong>400 ms → 320 ms<br>I saved: 80 ms</strong><br>Useful.</p><p>But I still have: <strong>700 ms RAG + 900 ms queue </strong>sitting elsewhere.<br>This is why end-to-end observability matters.</p><h3>The User Experiences the Whole Pipeline</h3><p>The user does not care whether latency came from:<br>- Vector database<br>- Network<br>- Prompt construction<br>- GPU queue<br>- Prefill<br>- Decode</p><p>The user experiences:<br>Send<br> ↓<br>Wait<br> ↓<br>Answer<br>Which means a serious optimization effort needs application-level traces such as:</p><p>Request Received<br>↓ Authentication<br>↓ Retrieval<br>↓ Prompt Built<br>↓ Queue Entered<br>↓ GPU Scheduled<br>↓ Prefill Complete<br>↓ First Token<br>↓ Last Token<br>Now I can actually see where the time went.</p><h3>This Is Why “Optimize the Conversation” Became My Final Mental Model</h3><p>When I started this series, the mental model was about GPU waste. By the end, I think the more complete model is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIKKmWEz7kY2VzZ7YySxaQ.png" /><figcaption>Conversational AI Request Journey- From user question to streamed response — beyond the GPU</figcaption></figure><p>The GPU sits inside the conversation. The conversation does not exist to optimize the GPU.</p><p>Now the five optimizations have a clear place in the lifecycle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8PRqptoUhDhCDIy0FvUPw.png" /><figcaption>LLM Inference Lifecycle Five optimizations mapped to the request path</figcaption></figure><h3>The Five Questions I Would Ask in a Performance Review</h3><p>Instead of starting with product names, I would ask the team these five questions.</p><p><strong>1. Are we storing and moving values at higher precision than we need?</strong></p><p>That points toward: <strong><em>BF16 / FP16 / quantization</em></strong></p><p><strong>2. Are long attention workloads creating unnecessary memory traffic?</strong></p><p>That points toward:<em> </em><strong><em>FlashAttention / efficient attention backend</em></strong></p><p><strong>3. Are we paying avoidable execution and launch overhead?</strong></p><p>That points toward: <strong><em>Compiled execution</em></strong></p><p><strong>4. Are we recalculating information we’ve already processed?</strong></p><p>That points toward: <strong><em>KV Cache / Prefix Caching</em></strong></p><p><strong>5. Are requests waiting while useful GPU capacity is available?</strong></p><p>That points toward: <strong><em>Batching / Scheduling / Bucketing</em></strong></p><p>Those five questions are more valuable to me than five configuration flags.</p><h3>And I Would Add a Sixth Question</h3><p>After writing the series, I would now add:</p><blockquote>Are we sending the model more tokens than the conversation actually needs?</blockquote><p>Because every unnecessary token can affect:<br>- Prefill<br>- Attention<br>- KV Cache<br>- Memory<br>- Latency<br>- Throughput</p><p>Prompt optimization is GPU optimization too.</p><p>So is:<br>- Better RAG retrieval<br>- Smaller system prompts<br>- Conversation summarization<br>- Removing duplicated context</p><p>Sometimes the best GPU optimization happens before the request reaches the GPU.</p><h3>A Practical Production Checklist</h3><p>Before I call a local LLM deployment “optimized,” I would want answers to all of these.</p><p><strong>Model</strong><br>- Which precision are we using?<br>- Which quantization, if any?<br>- Which attention backend?<br>- Is compiled execution active?<br>- Is KV caching enabled?</p><p><strong>Serving</strong><br>- What is the scheduler configuration?<br>- Is continuous batching active?<br>- Is prefix caching useful?<br>- Are long prefills chunked?<br>- What is the practical sequence/concurrency limit?</p><p><strong>Workload</strong><br>- What is the P50 prompt length?<br>- P95 prompt length?<br>- P50 output length?<br>- P95 output length?<br>- How bursty is traffic?<br>- How repetitive are prefixes?</p><p><strong>Performance</strong><br>- P50 / P95 / P99 TTFT?<br>- TPOT?<br>- Queue time?<br>- Input tokens/sec?<br>- Output tokens/sec?<br>- Requests/sec?</p><p><strong>Capacity</strong><br>- GPU utilization?<br>- VRAM utilization?<br>- KV-cache utilization?<br>- Maximum SLA-compliant concurrency?</p><p><strong>Quality<br>- </strong>Did reduced precision affect responses?<br>- Did KV-cache quantization affect output?<br>- Are structured responses still reliable?<br>- Are business-critical answers still acceptable?</p><p>That final category is non-negotiable.</p><h3>Performance Without Quality Is Not an Optimization</h3><p>Suppose I reduce latency by 30%.<br>But the model starts:<br>- misreading numbers<br>- breaking JSON output<br>- ignoring instructions<br>- changing important answers</p><p>I haven’t optimized the application. I’ve damaged it.<br>The engineering target is always:</p><p>Performance ↑<br>while<br>Quality ≥ Required Threshold</p><p>Not:<br>Performance ↑ at any cost</p><h3>My Final Benchmark Table Would Look Something Like This</h3><p>I would compare configurations side by side.</p><p>For example:</p><pre>Configuration          P95 TTFT  |  TPOT  |  Output tok/s  |  Peak VRAM  |  Max SLA Concurrency  |  Quality<br>-----------------------------------------------------------------------------------------------------------<br>Baseline      <br><br>+ BF16/FP16      <br><br>+ Efficient Attention      <br><br>+ Compiled Execution      <br><br>+ KV Cache tuning      <br><br>+ Batching tuning      <br><br>Final configuration</pre><p>This table gives me something much more valuable than:</p><p>FlashAttention = ON</p><p>It tells me:</p><blockquote><strong>What did each change actually buy me?</strong></blockquote><h3>If I’m Using vLLM, My Role Changes</h3><p>This series started from low-level GPU concepts. But if my application is served by vLLM or another mature inference engine, many optimizations already exist inside the runtime.</p><p>Then my job becomes less about:</p><ul><li>Implement FlashAttention</li><li>Write my own KV Cache</li><li>Write batching logic</li></ul><p>and more about:</p><ul><li>Select the right model format</li><li>Configure the engine</li><li>Observe metrics</li><li>Benchmark realistic traffic</li><li>Tune scheduler limits</li><li>Validate quality</li><li>Find capacity boundaries</li></ul><p>That is an important architectural shift.</p><p>A good inference engine doesn’t remove the need to understand these concepts.</p><p>It makes understanding them <strong>more useful</strong>, because now I know what its configuration is actually doing.</p><h3>The Command Is Not the Optimization</h3><p>I might eventually end up with something like:</p><pre>vllm serve &quot;$MODEL&quot; \<br>  --quantization awq \<br>  --dtype half \<br>  --max-model-len 4096 \<br>  --gpu-memory-utilization 0.92 \<br>  --max-num-seqs 64 \<br>  --max-num-batched-tokens 8192 \<br>  --enable-prefix-caching \<br>  --enable-chunked-prefill</pre><p>But I would never look at that command and conclude: Optimized.<br>The command is a <strong>hypothesis</strong>.<br>The benchmark tells me whether the hypothesis was correct.</p><h3>My Optimization Loop</h3><p>The process I now trust is simple:</p><p>Observe<br> ↓<br>Identify Bottleneck<br> ↓<br>Form Hypothesis<br> ↓<br>Change One Thing<br> ↓<br>Benchmark<br> ↓<br>Validate Quality<br> ↓<br>Keep / Revert<br> ↓<br>Repeat</p><p>Or even more simply:</p><blockquote><strong>Measure → Change → Measure again.</strong></blockquote><p>That is less exciting than copying a “10× faster LLM configuration” from the internet.<br>It is also much more likely to produce a reliable production system.</p><h3>What This Series Changed for Me</h3><p>At the beginning, I saw these technologies as independent optimizations.<br>- BF16<br>- FlashAttention<br>- torch.compile<br>- KV Cache<br>- Batching</p><p>Now I see a connected system.</p><blockquote>Saving memory with BF16 can create more room for KV Cache.<br>More KV Cache can support more active sequences.<br>More active sequences give the scheduler more batching opportunities.<br>Larger batches may improve throughput.<br>But more concurrency can hurt TTFT.<br>Longer contexts increase KV-cache pressure.<br>Longer contexts also make efficient attention more valuable.<br>Dynamic request shapes can affect compiled execution.<br>Prompt structure can affect prefix-cache reuse.</blockquote><blockquote>Everything connects.</blockquote><p>That is probably the most useful lesson I took from writing this series.</p><h3>The Complete Mental Model</h3><p>So here is the final version.</p><blockquote>STOP WASTING YOUR GPU</blockquote><p>1. BF16 / FP16<br> ↓<br>Make the numbers smaller.<br> ↓<br>Reduce memory and bandwidth pressure.</p><p>2. FlashAttention<br> ↓<br>Move less data.<br> ↓<br>Reduce attention-related memory traffic.</p><p>3. torch.compile<br> ↓<br>Execute operations smarter.<br> ↓<br>Reduce avoidable execution overhead.</p><p>4. KV Cache<br> ↓<br>Don’t calculate the past again.<br> ↓<br>Reduce repeated decode computation.</p><p>5. Batching / Bucketing<br> ↓<br>Keep the GPU busy.<br> ↓<br>Increase useful parallel work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*_wvq4nBRBr9qq4wBYWny-Q.png" /></figure><p>But I would add one final line underneath the diagram:</p><blockquote><strong>Only if the user experience and model quality remain acceptable.</strong></blockquote><h3>The One Thing I Want You to Take Away From the Series</h3><p>If I had to reduce all seven articles to one idea, it would be this:</p><blockquote><strong>GPU optimization is the process of removing waste from the path between a user’s question and the model’s answer.</strong></blockquote><p>Sometimes the waste is:<br><em>Too much memory.</em><br>Sometimes:<br><em>Too much data movement.</em><br>Sometimes:<br><em>Repeated computation.</em><br>Sometimes:<br><em>Execution overhead.</em><br>Sometimes:<br><em>An idle GPU.</em><br>And sometimes the problem isn’t the GPU at all. That’s why I no longer start with:</p><p><em>Which optimization should I enable?</em></p><p>I start with:</p><blockquote><strong>Where is the user actually waiting?</strong></blockquote><p>Once I know that, the technology decision becomes much easier.</p><h3>Closing the Series</h3><p><a href="https://medium.com/@patil-parag-oss/your-llm-is-running-on-a-gpu-but-is-it-running-efficiently-2382a10eae9f"><strong>Part 1</strong></a></p><p><strong>Your LLM Is Running on a GPU. But Is It Running Efficiently?</strong></p><p>I introduced the five-waste mental model.</p><p><a href="https://medium.com/@patil-parag-oss/bf16-vs-fp16-why-smaller-numbers-make-local-llms-faster-5110971e0a69"><strong>Part 2</strong></a></p><p><strong>BF16 vs FP16: Why Smaller Numbers Make Local LLMs Faster</strong></p><p>Make the numbers smaller.</p><p><a href="https://medium.com/@patil-parag-oss/flashattention-explained-simply-stop-moving-so-much-gpu-data-9bcb121aeb2d"><strong>Part 3</strong></a></p><p><strong>FlashAttention Explained Simply: Stop Moving So Much GPU Data</strong></p><p>Move less data.</p><p><a href="https://medium.com/@patil-parag-oss/what-does-torch-compile-actually-do-to-your-llm-4e3766cd18c4"><strong>Part 4</strong></a></p><p><strong>What Does torch.compile() Actually Do to Your LLM?</strong></p><p>Execute operations smarter.</p><p><a href="https://medium.com/@patil-parag-oss/kv-cache-explained-stop-making-your-llm-recalculate-the-past-1893ff208d44"><strong>Part 5</strong></a></p><p><strong>KV Cache Explained: Stop Making Your LLM Recalculate the Past</strong></p><p>Don’t calculate the past again.</p><p><a href="https://medium.com/@patil-parag-oss/your-gpu-is-powerful-so-why-is-it-sitting-idle-821aefd08836"><strong>Part 6</strong></a></p><p><strong>Your GPU Is Powerful. So Why Is It Sitting Idle?</strong></p><p>Keep the GPU busy.</p><p><strong>Part 7</strong></p><p><strong>Putting It All Together: Optimize the Conversation, Not the Benchmark</strong></p><p>And the conclusion:</p><blockquote><strong>The best GPU configuration is not the one that produces the highest benchmark number. It is the one that delivers the required user experience, quality, concurrency and throughput at the lowest practical infrastructure cost.</strong></blockquote><p>That’s the mental model I’ll carry into the next local LLM implementation.</p><p>And the next time somebody tells me:</p><p><em>“We should enable this optimization. It’s faster.”</em></p><p>I know exactly what my first question will be:</p><blockquote><strong>What waste are we trying to remove?</strong></blockquote><p><em>This is Part 7 and the conclusion of </em><strong><em>Stop Wasting Your GPU: A Developer’s Guide to Local LLM Optimization</em></strong><em>.</em></p><p><strong>← Previous: </strong><a href="https://medium.com/@patil-parag-oss/your-gpu-is-powerful-so-why-is-it-sitting-idle-821aefd08836"><strong>Part 6 — Your GPU Is Powerful. So Why Is It Sitting Idle?</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=429f06d7e200" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your GPU Is Powerful. So Why Is It Sitting Idle?]]></title>
            <link>https://patil-parag-oss.medium.com/your-gpu-is-powerful-so-why-is-it-sitting-idle-821aefd08836?source=rss-966c27f82db4------2</link>
            <guid isPermaLink="false">https://medium.com/p/821aefd08836</guid>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[task-batching]]></category>
            <category><![CDATA[llm-optimization]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[gpu-acceleration]]></category>
            <dc:creator><![CDATA[Parag Patil]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 04:45:10 GMT</pubDate>
            <atom:updated>2026-09-21T07:26:35.996Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 6 of the series: </em><strong><em>Stop Wasting Your GPU — A Developer’s Guide to Local LLM Optimization</em></strong></p><p>By this point in the series, I have spent a lot of time making <strong>one LLM request</strong> more efficient.</p><p><em>I reduced tensor size with</em><strong><em> BF16/FP16. </em></strong><em><br>I reduced attention memory traffic with </em><strong><em>FlashAttention</em></strong><em>. <br>I looked at smarter execution with </em><strong><em>torch.compile</em></strong><em>. <br>And I stopped the model from recalculating its past with </em><strong><em>KV Cache</em></strong><em>.</em></p><p>At that point, I could easily convince myself that the GPU was optimized.<br>Then I looked at the system under real concurrent traffic.<br>And a different problem became obvious:</p><blockquote><strong>What if each request is highly optimized, but I still feed requests to the GPU inefficiently?</strong></blockquote><p>A GPU is a massively parallel processor. Giving it one small job at a time can be like buying a 50-seat bus and using it to transport one passenger.<br>The bus is running. It just isn’t being used very well.</p><p>That brings me to the final optimization in this mental model:</p><blockquote><strong>Batching and Bucketing → Keep the GPU busy.</strong></blockquote><h3>A Fast GPU Can Still Be Poorly Utilized</h3><p>Let’s imagine a simple local conversational AI server. Five users send requests at almost the same time:</p><p>User A<br>User B<br>User C<br>User D<br>User E</p><p>A very basic implementation might effectively behave like:<br>User A<br> ↓<br>GPU<br> ↓<br>Response<br> <br>User B<br> ↓<br> GPU<br> ↓<br>Response<br> <br>User C<br> ↓<br> GPU<br> ↓<br>Response</p><p>There is nothing functionally wrong with this. Every user eventually gets an answer. But GPUs are designed to perform huge amounts of parallel work.</p><p>If each individual request cannot occupy enough of the GPU, a significant amount of compute capacity can remain unused.</p><p>So I can have:</p><p>Expensive GPU ✔<br>Fast model ✔<br>Optimized attention ✔<br>KV Cache ✔<br>Low throughput ✘</p><p>because my serving strategy is inefficient.<br>This is the point where GPU optimization stops being only a model problem and becomes a scheduling problem.</p><h3>My Bus Analogy</h3><p>The simplest way I explain batching is with a bus. Imagine I own a bus with 50 seats.</p><p>I can operate it like this:</p><p>Passenger 1<br> ↓<br>Bus leaves with 1 passenger<br> ↓<br>Returns<br> <br>Passenger 2<br> ↓<br>Bus leaves with 1 passenger<br> ↓<br>Returns</p><p>The bus is technically doing its job. But most of its capacity is wasted.</p><p>A better strategy is:</p><p>Passenger 1 ─┐<br>Passenger 2 ─┤<br>Passenger 3 ─┤<br>Passenger 4 ─┼── Bus<br>Passenger 5 ─┘</p><p>That is the basic idea behind <strong>batching</strong>.</p><p>Instead of asking the GPU to process each workload independently, I try to give it useful work from multiple requests together.</p><h3>Why GPUs Like Batches</h3><p>Transformer inference is dominated by matrix operations. GPUs are particularly good at processing these operations in parallel.</p><p>Very simplistically:</p><p><strong>One request<br> ↓<br>Small amount of parallel work<br> ↓<br>GPU partially occupied</strong></p><p>versus:</p><p><strong>Several requests<br> ↓<br>Larger combined work<br> ↓<br>More GPU parallelism<br> ↓<br>Potentially higher throughput</strong></p><p>This means that if I only benchmark my model with: <br>Concurrency = 1<br>I am learning something about single-request latency.<br>I am not necessarily learning much about:</p><blockquote>How efficiently this GPU can serve a production workload?</blockquote><h3>So Why Not Create the Biggest Batch Possible?</h3><p>That was my next thought.</p><p>If batching keeps the GPU busy, then surely:<br>Bigger batch = Better performance</p><p>Not quite. Because conversational AI has an important requirement that offline ML jobs often don’t have:</p><blockquote><strong>A user is waiting for the answer.</strong></blockquote><p>Imagine I wait for 32 requests before running a batch.<br>Request 1 arrives at:<br><strong>10:00:00</strong><br>Request 32 arrives at:<br><strong>10:00:04</strong><br>I may have created an excellent batch. But Request 1 spent four seconds doing absolutely nothing.</p><p>Its <strong>Time to First Token</strong> just became terrible. So I immediately get a trade-off:</p><p>Larger Batch<br> ↓<br>Potentially higher throughput<br> <br>BUT<br> <br>More waiting<br> ↓<br>Potentially higher latency</p><p>This is one of the most important lessons in LLM serving:</p><blockquote><strong>The batch size that maximizes GPU throughput is not necessarily the batch size that creates the best conversational experience.</strong></blockquote><h3>Static Batching Is Easy</h3><p>Traditional batching looks roughly like this:</p><p>Request A ─┐<br>Request B ─┤<br>Request C ─┼── Batch<br>Request D ─┘<br> ↓<br>GPU<br> ↓<br>Wait until the entire batch finishes</p><p>This works nicely when workloads are predictable.</p><p>For example:</p><p>32 images (same size)<br> or<br>64 training samples (same tensor dimensions)</p><p>But LLM requests are anything but predictable.</p><h3>LLM Requests Are Uneven</h3><p>Consider four users.<br><strong>User A</strong><br>Prompt: 120 tokens<br>Output: 80 tokens</p><p><strong>User B</strong><br>Prompt: 650 tokens<br>Output: 300 tokens</p><p><strong>User C</strong><br>Prompt: 4,000 tokens<br>Output: 100 tokens</p><p><strong>User D</strong><br>Prompt: 1,200 tokens<br>Output: 1,000 tokensAll four requests are completely different.</p><p>They differ in:<br>- Prompt length<br>- Generation length<br>- Time spent in prefill<br>- Time spent in decode<br>- KV Cache usage</p><p>If I put these into one rigid batch and require everyone to move together, I create a problem.</p><p>User A may finish quickly.<br>User D may continue generating for much longer.</p><p>Why should the GPU slot previously used by User A remain unavailable until User D finishes?<br>This is where <strong>continuous batching</strong> becomes much more interesting than traditional batching.</p><h3>Continuous Batching Changed My Mental Model</h3><p>Instead of thinking:</p><p>Create batch<br> ↓<br>Run batch<br> ↓<br>Wait<br> ↓<br>Finish batch<br> ↓<br>Create next batch</p><p>I now think:</p><p>GPU Scheduling Iteration 1<br> A<br> B<br> C<br> D</p><p>Maybe Request A finishes.</p><p>On the next scheduling iteration:</p><p>GPU Scheduling Iteration 2<br> B<br> C<br> D<br> E</p><p>Request E can enter without waiting for every request from the previous group to finish. Then perhaps B finishes:</p><p>GPU Scheduling Iteration 3<br> C<br> D<br> E<br> F</p><p>This is <strong>continuous batching</strong>. The active batch is continually changing. Requests can enter as capacity becomes available.</p><p>That makes much more sense for LLMs.</p><h3>The Restaurant Analogy Works Better Here</h3><p>Imagine a restaurant kitchen with four cooking stations.</p><p>Traditional batching says:</p><blockquote><strong>These four tables form Batch 1. Do not accept more kitchen work until all four tables are completely finished.</strong></blockquote><p>That means if three tables finish quickly but one orders a complicated meal, the other stations can sit unused.</p><p>Continuous batching says:</p><blockquote><strong>The moment a station becomes available, give it the next useful piece of work.</strong></blockquote><p>Conceptually:</p><p>Time →<br> Station 1: AAAAA | EEEEEEE<br> Station 2: BBBBBBBBBB<br> Station 3: CCC | FFFFF<br> Station 4: DDDDD | GGG</p><p>The exact GPU execution is obviously more complex. But this gives me the right intuition:</p><blockquote><strong>Do not wait for one slow sequence before admitting useful work from another request.</strong></blockquote><h3>This Is Why vLLM Is More Than model.generate()</h3><p>If I’m using raw PyTorch, I can absolutely build my own batching layer.</p><p>But once I move to an inference engine such as vLLM, request scheduling becomes a major part of what that engine provides.</p><p>Conceptually:</p><p>Incoming Requests<br> <br>[A, B, C, D, E, F]<br> ↓<br>vLLM Scheduler<br> ↓<br>Continuous Batch<br> ↓<br>GPU</p><p>I don’t necessarily write:</p><pre>batch = []<br><br>while len(batch) &lt; 32:<br>    batch.append(next_request())<br><br>model.generate(batch)</pre><p>Instead, I configure the serving engine’s scheduling limits and let it continuously decide how much work should be placed into each GPU iteration.</p><h3>Then Comes Another Problem: Prompt Length</h3><p>Suppose I have:</p><p>Request A = 100 tokens<br>Request B = 130 tokens<br>Request C = 170 tokens<br>Request D = 8,000 tokens</p><p>Traditional tensor batching often requires inputs to have compatible dimensions.</p><p>One common solution is <strong>padding</strong>.</p><p>Conceptually:</p><p>A = 100 + padding padding padding …<br>B = 130 + padding padding padding …<br>C = 170 + padding padding padding …<br>D = 8000</p><p>Now I have potentially created a lot of work involving tokens that carry no useful information.</p><p>That is waste.</p><h3>Bucketing: Put Similar Work Together</h3><p>This is where <strong>bucketing</strong> becomes useful. Instead of grouping requests randomly, I can group them by similar characteristics.</p><p>For example:</p><p><strong>Bucket 1</strong>: 0–512 tokens<br> <br> A = 100<br> B = 130<br> C = 170</p><p>Then:</p><p><strong>Bucket 2</strong>: 4K–8K tokens<br> <br> D = 8,000</p><p>Now the requests in each group are more compatible.</p><p>This can reduce:</p><ul><li>Padding</li><li>Shape variation</li><li>Wasted computation</li></ul><p>So the mental model I use is:</p><blockquote><strong>Batching fills the GPU. Bucketing tries to fill it with similar work.</strong></blockquote><h3>But vLLM Changes the Exact Meaning of Bucketing</h3><p>One important nuance:</p><p>A modern LLM serving engine doesn’t necessarily require me to manually create rigid token-length buckets like a traditional PyTorch batch.</p><p>Continuous scheduling, paged KV-cache management, and token-level scheduling already handle much of the irregularity.</p><p>So when I talk about bucketing in a modern serving stack, I think about it more broadly:</p><ul><li>Group compatible workloads</li><li>Avoid pathological mixing</li><li>Control scheduling budgets</li><li>Keep shapes/workload reasonably predictable</li></ul><p>rather than:</p><p>Every request must literally be copied into a manually constructed fixed-size bucket.</p><p>This is an important distinction between the <strong>mental model</strong> and the <strong>implementation</strong>.</p><h3>Prefill and Decode Compete for the Same GPU</h3><p><a href="https://medium.com/@patil-parag-oss/kv-cache-explained-stop-making-your-llm-recalculate-the-past-1893ff208d44?sharedUserId=patil-parag-oss">Part 5</a> introduced the two major phases of inference:</p><p>PREFILL — Process the prompt<br>DECODE — Generate tokens</p><p>Now imagine these requests are active:</p><p>Request A — Generating token 210<br>Request B — Generating token 87<br>Request C — New 4,000-token prompt arrives</p><p>Request C has a large prefill workload. If the GPU spends a long time processing Request C’s entire prompt, what happens to A and B?</p><p>Their token generation may temporarily slow down.</p><p>From the user’s perspective:</p><p>A was streaming smoothly…<br>then…<br>pause…<br>then continues</p><p>That is not a good conversational experience.</p><h3>Chunked Prefill Helps Balance This</h3><p>One solution is to avoid treating a huge prefill as one indivisible job.</p><p>Instead: 4,000-token Prefill<br>can conceptually become:</p><p>Prefill Chunk 1<br> ↓<br>Decode work for A/B<br> ↓<br>Prefill Chunk 2<br> ↓<br>Decode work<br> ↓<br>Prefill Chunk 3</p><p>Now a large incoming prompt doesn’t necessarily monopolize the whole scheduling iteration.</p><p>This is the idea behind <strong>chunked prefill</strong>.</p><p>In vLLM, chunked prefill allows prefill work to be divided according to the remaining token budget for a scheduler iteration.</p><p>I find the mental model useful:</p><blockquote><strong>Don’t allow one huge prompt to block every conversation that is already generating.</strong></blockquote><h3>Now My Serving Architecture Looks Different</h3><p>Without thoughtful scheduling:</p><p>Requests<br> ↓<br>Process individually<br> ↓<br>GPU</p><p>With a serving engine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*lwiCiAQJb4FESdygqTgJ4Q.png" /><figcaption>Serving Architecture</figcaption></figure><p>And now the GPU can be kept much busier.</p><h3>What Does max-num-seqs Actually Mean?</h3><p>This is where my vLLM configuration becomes easier to reason about.</p><p>Consider:<br>--max-num-seqs 64</p><p>My first instinct might be:<br>The server supports 64 users. That isn’t quite the correct interpretation.<br>I think about it as:</p><blockquote><strong>How many sequences can the scheduler process in a scheduling iteration?</strong></blockquote><p>So:</p><p>max-num-seqs<br> ↓<br>Upper bound on active sequences<br>considered/processed in an iteration</p><p>Increasing it gives the scheduler the opportunity to process more concurrent sequences.</p><p>But more is not automatically better.</p><h3>Why I Would Not Start With 256 Just Because I Can</h3><p>Suppose I configure:<br>--max-num-seqs 256<br>That sounds impressive. But each active sequence may require:<br>-KV Cache<br>-Execution resources<br>-Scheduler capacity</p><p>As I add more concurrent sequences:<br>Concurrency<strong> ↑</strong><br>KV Cache pressure <strong>↑</strong><br>Batch size <strong>↑</strong><br>Potential throughput<strong> ↑</strong></p><p>but potentially:<br>Per-request latency ↑</p><p>At some point, adding more sequences can stop giving meaningful throughput improvements.<br>So I don’t think:<br>256 &gt; 64<br>therefore<br>256 is better</p><p>I think:</p><blockquote>Find the maximum useful concurrency that still meets the user-facing latency target.</blockquote><h3>What Does max-num-batched-tokens Mean?</h3><p>Now consider:</p><p>--max-num-batched-tokens 8192</p><p>This one became much clearer when I stopped thinking of it as:</p><blockquote>My maximum prompt size.</blockquote><p>It isn’t.</p><p>I think of it as:</p><blockquote><strong>How many tokens can the scheduler process during one scheduling iteration?</strong></blockquote><p>For example, conceptually:</p><p>Iteration token budget = 8192</p><p>That budget might contain a mixture such as:</p><pre>Prefill Request A     4000 tokens<br>Prefill Request B     2000 tokens<br>Decode Work            100 tokens<br>Other Work            2092 tokens<br>--------------------------------<br>Total                 8192</pre><p>The real scheduling details are more sophisticated, but this mental model is enough to understand the parameter.</p><h3>And This Parameter Has a Trade-Off Too</h3><p>A larger token budget allows more prefill work to happen in an iteration.</p><p>That may improve prompt-processing throughput and TTFT in some workloads.</p><p>But if I allow large prefills to consume too much of the iteration, decode requests can get less frequent service. Then streaming smoothness can suffer.</p><p>So I get another balance:<br>Larger token budget<br> ↓<br>More prefill throughput</p><p>BUT</p><p>Potentially more competition with decode</p><p>Current vLLM tuning guidance reflects exactly this kind of trade-off: smaller token budgets can favor inter-token latency, while larger budgets can favor TTFT and throughput depending on workload and hardware.</p><p>This is why I benchmark instead of copying a number from someone else’s configuration.</p><h3>Throughput and Latency Are Different Goals</h3><p>This is probably the most important section of this article.</p><p>Imagine <strong>Configuration A:</strong><br>GPU utilization — 70%<br>TTFT — 700 ms</p><p>Smooth streaming : 1000 tokens/sec aggregate</p><p>Now <strong>Configuration B:</strong><br>GPU utilization — 99%<br>TTFT — 4 seconds</p><p>Occasional streaming pauses : 1600 tokens/sec aggregate</p><blockquote><strong>Which configuration is better?</strong></blockquote><p>If I’m running an offline summarization service:<br><strong><em>Configuration B might be attractive.</em></strong></p><p>If I’m running an interactive banking assistant:<br><strong><em>Configuration A might be much better.</em></strong></p><p>So there isn’t one universal definition of:<br>Optimal GPU Configuration</p><p>There is only:</p><blockquote>Optimal for the workload I am actually serving.</blockquote><h3>The Metrics I Care About Now</h3><p>In previous parts, I measured:</p><ul><li>VRAM</li><li>TTFT</li><li>TPOT</li><li>tokens/sec</li></ul><p>Now that batching enters the picture, I add more serving-level metrics.</p><h3>1. Request Queue Time</h3><p>Before the model even starts processing:</p><p>How long did the request sit in the queue?</p><p>A model can be extremely fast but still produce terrible application latency if requests spend seconds waiting for scheduler capacity.</p><h3>2. TTFT</h3><p><strong>Time to First Token</strong></p><p>Still critical. Batching can increase throughput while accidentally hurting TTFT.</p><h3>3. TPOT / Inter-Token Latency</h3><p>Once the answer starts, does it stream smoothly?</p><p>Large competing prefills can affect this.</p><h3>4. Requests per Second</h3><p>How many completed requests does the system handle?</p><h3>5. Input Tokens per Second</h3><p>How quickly can prompts be processed?</p><p>This becomes particularly relevant for RAG-heavy conversational systems.</p><h3>6. Output Tokens per Second</h3><p>How efficiently are generated tokens produced?</p><h3>7. GPU Utilization</h3><p>Now this metric becomes more meaningful.</p><p>If utilization is consistently low <strong>while requests are waiting</strong>, I may have a scheduling/batching problem.</p><h3>8. KV Cache Utilization</h3><p>More concurrent sequences consume more cache capacity.</p><p>So I need to watch memory pressure at the same time.</p><h3>I Care About P95 More Than a Pretty Average</h3><p>Suppose my TTFT measurements are:</p><p>500 ms<br>550 ms<br>520 ms<br>490 ms<br>6,000 ms</p><p>The average can hide the fact that some users are having a terrible experience.</p><p>For production conversational AI, I care about percentiles:</p><p>P50<br>P95<br>P99</p><p>For example:</p><p>P50 TTFT = 700 ms<br>P95 TTFT = 1.8 s<br>P99 TTFT = 4.5 s</p><p>That tells me far more than:</p><p>Average TTFT = 1.1 s</p><p>This becomes increasingly important as concurrency grows.</p><h3>The Load Test I Would Actually Run</h3><p>I wouldn’t jump directly to:<br>256 concurrent users<br>I would increase concurrency gradually.<br>For example:</p><p>1<br> ↓<br>5<br> ↓<br>10<br> ↓<br>20<br> ↓<br>32<br> ↓<br>64<br> ↓<br>128</p><p>At every step I record:</p><pre>Metric                What I’m looking for<br>---------------------------------------------<br>P50 TTFT              Typical responsiveness<br>P95/P99 TTFT          Worst-user experience<br>TPOT                  Streaming smoothness<br>Requests/sec          Overall throughput<br>Input tokens/sec      Prefill capacity<br>Output tokens/sec     Decode capacity<br>GPU utilization       Compute usage<br>VRAM                  Memory pressure<br>KV-cache utilization  Sequence capacity<br>Queue depth           Scheduler pressure</pre><p>Eventually I’ll see something like: Concurrency</p><pre>1      throughput ↑<br>5      throughput ↑<br>10     throughput ↑<br>20     throughput ↑<br>32     throughput ↑<br><br>64     throughput ↑ slightly<br>       TTFT       ↑ significantly<br><br>128    throughput ≈ flat<br>       TTFT       ↑↑<br>       queue      ↑↑</pre><p>That tells me:</p><blockquote><strong>Somewhere around 32–64 active requests is probably the useful operating region for this particular workload.</strong></blockquote><p>The exact number could be completely different for another model or GPU.</p><p>That’s why there is no magic max-num-seqs.</p><h3>I Would Test More Than One Prompt Distribution</h3><p>This is easy to miss.</p><p>Benchmark A:</p><p>Every prompt = <strong>512 tokens</strong><br>Every output = <strong>128 tokens</strong></p><p>is very easy to optimize.</p><p>Production may look like:</p><p>20% → 200-token prompts<br>40% → 1K prompts<br>25% → 4K prompts<br>15% → 8K prompts</p><p>with output lengths that vary just as much. So I prefer at least three workload profiles:</p><p><strong>Short-chat workload</strong><br><em>Small prompt<br>Small response<br>High concurrency</em></p><p><strong>RAG workload<br></strong><em>Large prompt<br>Moderate response</em></p><p><strong>Mixed production workload</strong><br><em>Different prompt lengths<br>Different response lengths<br>Realistic request arrival pattern</em></p><p>The third one is usually the most valuable.</p><h3>Burst Traffic Matters Too</h3><p>Average concurrency can also be misleading.</p><p>Suppose my application averages: <strong>10 requests/sec</strong></p><p>but every minute receives a burst of: <strong>50 requests within 2 seconds</strong></p><p>The scheduler suddenly has a very different problem.</p><p>So I test:</p><p><strong>Steady traffic</strong><br> &amp;<br><strong>Burst traffic</strong></p><p>because queue behavior can be completely different.</p><p>This is particularly relevant to enterprise applications where users often arrive in clusters:</p><ul><li>Start of business day</li><li>Campaign notification</li><li>Batch job completion</li><li>Customer event</li><li>Call-center peak period</li></ul><h3>Where Bucketing Still Helps Me</h3><p>Even with a sophisticated serving engine, I still find the bucketing mental model useful.</p><p>For example, I may decide that extremely long-context workloads should not compete directly with short interactive requests.</p><p>I could conceptually separate:</p><p><strong><em>Interactive Queue </em></strong><em><br></em> 0–4K context<br>Short responses<br>Latency sensitive</p><p>from:</p><p><strong><em>Heavy Queue</em></strong><br>8K–32K context<br>Long responses<br>Throughput oriented</p><p>Those could eventually map to:</p><p>Different scheduling rules<br>Different replicas<br>Different GPUs<br>Different SLAs</p><p>So bucketing is not only about tensor padding. It can become an architectural workload-classification strategy.</p><h3>A Banking Assistant Example</h3><p>Imagine my local conversational AI supports two request types.</p><h3>Request Type A</h3><p>Customer asks:</p><p>“What is today’s EMI due?”</p><p><strong>Prompt:</strong> ~600 tokens <strong>Expected response:</strong> ~80 tokens</p><p>The user expects a near-immediate answer.</p><h3>Request Type B</h3><p>Customer asks:</p><p>“Review my application history, policy conditions, bureau information and explain why the loan was rejected.”</p><p><strong>Prompt:</strong> ~8,000 tokens <strong>Expected response:</strong> ~1,000 tokens</p><p>These are technically requests to the same LLM. Operationally, they are very different workloads.</p><p>If I blindly batch them together, a large analytical request may interfere with latency-sensitive conversational traffic.</p><p>That suggests an architectural question:</p><blockquote><strong>Should all requests really have the same scheduling priority and SLA?</strong></blockquote><p>GPU optimization eventually becomes workload engineering.</p><h3>This Is Also Where Horizontal Scaling Starts</h3><p>Suppose I have tuned:</p><ul><li>BF16 / AWQ</li><li>FlashAttention</li><li>Compilation</li><li>KV Cache</li><li>Continuous batching</li></ul><p>and one GPU still cannot meet: <strong>Required concurrency + Required latency</strong></p><p>That doesn’t mean the optimization failed. It may simply mean I’ve reached the useful capacity of one GPU.</p><p>At that point:</p><p>One GPU<br> ↓<br>Known capacity<br> ↓<br>Required workload &gt; capacity<br> ↓<br>Scale horizontally</p><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*WPbfDR85GPmzLMcv_OoLuA.png" /></figure><p>Optimization determines:</p><blockquote><strong>How much useful capacity I get from each GPU before I need another one.</strong></blockquote><p>That is directly connected to infrastructure cost.</p><h3>My Mental Model Has Now Changed</h3><p>At the beginning of the series, I thought of GPU performance mainly as:</p><p><em>How fast does one model inference run?</em></p><p>Now I think:</p><blockquote><strong>How efficiently does the whole serving system convert GPU capacity into useful user responses?</strong></blockquote><p>That includes:<br>- Model execution<br>- Memory<br>- KV Cache<br>- Scheduling<br>- Queueing<br>- Batching<br>- Workload shape<br>- Concurrency</p><p>GPU optimization is no longer just about CUDA. It is a systems problem.</p><h3>How the Five Optimizations Finally Fit Together</h3><p>We can now connect all five ideas.</p><h3>BF16 / FP16</h3><p><strong>Make the numbers smaller.</strong></p><p>Reduces: Tensor memory + Memory bandwidth</p><h3>FlashAttention</h3><p><strong>Move less data.</strong></p><p>Reduces: Attention-related memory traffic</p><h3>torch.compile</h3><p><strong>Execute operations smarter.</strong></p><p>Reduces: Execution/framework overhead + Missed optimization opportunities</p><h3>KV Cache</h3><p><strong>Don’t calculate the past again.</strong></p><p>Reduces: Repeated autoregressive computation</p><h3>Batching / Bucketing</h3><p><strong>Keep the GPU busy.</strong></p><p>Reduces: Idle GPU capacity + Poor serving efficiency</p><p>Put them together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*eZl-SDGavZ8Nt5aJt6AlwQ.png" /><figcaption>Mental Model</figcaption></figure><p>Now the mental model is complete.</p><h3>One Mistake I Would Avoid</h3><p>I would not look at:</p><p>GPU Utilization = 99% and declare victory.</p><p>Suppose I achieved 99% utilization while:</p><p>P95 TTFT = 8 seconds<br>TPOT = unstable<br>Queue depth = increasing</p><p>That is not optimization. That is saturation.<br>There is a difference.</p><h3>High utilization</h3><p>means: The GPU is busy.</p><h3>Efficient utilization</h3><p>means: The GPU is busy doing useful work while meeting my latency target.</p><p>That distinction is critical.</p><h3>The Developer Question I Now Ask</h3><p>Whenever I see low GPU utilization, I don’t immediately say: <br>Increase batch size.<br>I ask:</p><ul><li>Are requests waiting?</li><li>Is the workload CPU-bound?</li><li>Is tokenization slow?</li><li>Is RAG retrieval the bottleneck?</li><li>Is KV cache full?</li><li>Are batches too small?</li><li>Are prompts badly mixed?</li><li>Is the GPU actually waiting for work?</li></ul><p>Because low utilization is a symptom.<br>Batching is useful only if insufficient parallel GPU work is actually the problem.</p><p>That brings me back to the central theme of this entire series:</p><blockquote><strong>Optimize the bottleneck, not the technology.</strong></blockquote><h3>The One Thing I Want You to Remember</h3><p>If you remember only one line from this article:</p><blockquote><strong>Batching isn’t about making one request faster. It is about getting more useful work through the GPU at the same time.</strong></blockquote><p>And:</p><blockquote><strong>Bucketing helps make that concurrent work more compatible.</strong></blockquote><p>My shortest mental model remains:</p><p>Batching / Bucketing<br> ↓<br>Keep the GPU busy.</p><p>But now I add an important condition:</p><blockquote><strong>Keep the GPU busy without making users wait unnecessarily.</strong></blockquote><p>That second sentence is what turns a benchmark optimization into a production optimization.</p><h3>What Comes Next?</h3><p>We now have all five optimizations.</p><p><strong>BF16 / FP16</strong> → Make the numbers smaller.<br><strong>FlashAttention </strong>→ Move less data.<br><strong>torch.compile</strong> → Execute operations smarter.<br><strong>KV Cache </strong>→ Don’t calculate the past again.<br><strong>Batching / Bucketing</strong> → Keep the GPU busy.</p><p>But there is one final question. <br>Suppose I enable all five.<br>How do I know whether my system is actually better?<br>Do I optimize for:</p><ul><li>GPU utilization?</li><li>Tokens/sec?</li><li>TTFT?</li><li>TPOT?</li><li>Concurrency?</li><li>VRAM?</li><li>Cost?</li></ul><p>And what happens when improving one metric makes another worse?<br>That is where the final article in this series begins.</p><h3>Part 7 — Putting It All Together: Optimize the Conversation, Not the Benchmark</h3><p>In the conclusion, I’ll bring all five optimizations together and look at:</p><ul><li>the complete request lifecycle,</li><li>TTFT vs TPOT,</li><li>throughput vs latency,</li><li>VRAM vs concurrency,</li><li>why 100% GPU utilization can be a bad sign,</li><li>how I would create a baseline,</li><li>how I would introduce optimizations one at a time,</li><li>how I would load-test the final system,</li><li>and how all of this eventually translates into <strong>cost per conversation</strong>.</li></ul><p>The final mental model will be:</p><blockquote><strong>The goal isn’t to optimize the GPU. The goal is to optimize the conversation.</strong></blockquote><p><em>This is Part 6 of </em><strong><em>Stop Wasting Your GPU: A Developer’s Guide to Local LLM Optimization</em></strong><em>.</em></p><p><strong>← Previous: </strong><a href="https://medium.com/@patil-parag-oss/kv-cache-explained-stop-making-your-llm-recalculate-the-past-1893ff208d44?sharedUserId=patil-parag-oss"><strong>Part 5 — KV Cache Explained: Stop Making Your LLM Recalculate the Past</strong></a></p><p><strong>Next → </strong><a href="https://patil-parag-oss.medium.com/putting-it-all-together-optimize-the-conversation-not-the-benchmark-429f06d7e200?sharedUserId=patil-parag-oss"><strong>Part 7 — Putting It All Together: Optimize the Conversation, Not the Benchmark</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=821aefd08836" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KV Cache Explained: Stop Making Your LLM Recalculate the Past]]></title>
            <link>https://patil-parag-oss.medium.com/kv-cache-explained-stop-making-your-llm-recalculate-the-past-1893ff208d44?source=rss-966c27f82db4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1893ff208d44</guid>
            <category><![CDATA[llm-optimization]]></category>
            <category><![CDATA[kv-cache]]></category>
            <category><![CDATA[local-llm]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <dc:creator><![CDATA[Parag Patil]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 13:40:20 GMT</pubDate>
            <atom:updated>2026-09-15T13:40:20.771Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 5 of the series: </em><strong><em>Stop Wasting Your GPU — A Developer’s Guide to Local LLM Optimization</em></strong></p><p>There was one thing about LLM inference that bothered me when I first understood how text generation works.</p><p>An LLM does not generate an entire answer in one shot.</p><p>It generates:</p><p>one token<br>then another token<br>then another token<br>then another…</p><p>And every new token depends on everything that came before it.</p><p>That immediately made me wonder:</p><blockquote><strong>If the model has already processed the previous tokens, why should it calculate the same information again while generating the next one?</strong></blockquote><p>That question leads directly to one of the most important optimizations in LLM inference:</p><p><strong>KV Cache.</strong></p><p>The mental model for this part of the series is simple:</p><blockquote><strong>KV Cache → Don’t calculate the past again.</strong></blockquote><h3>Let’s Start With How an LLM Actually Generates a Response</h3><p>Suppose I ask my local conversational AI:</p><blockquote><strong>“Why was my loan application rejected?”</strong></blockquote><p>The model might generate:</p><p><strong>Your</strong><br>then:<br><strong>Your loan</strong><br>then:<br><strong>Your loan application</strong><br>then:<br><strong>Your loan application was</strong><br>and eventually:<br><strong>Your loan application was rejected because…</strong></p><p>From the user’s perspective, the answer appears to be continuously written.</p><p>Inside the model, however, each step is a new inference operation.</p><p><strong>Conceptually:</strong></p><p>Prompt<br> ↓<br>Generate Token 1<br> ↓<br>Generate Token 2<br> ↓<br>Generate Token 3<br> ↓<br>Generate Token 4<br> ↓<br> …</p><p>This phase is called <strong>autoregressive decoding</strong>.</p><p>The important word here is:</p><blockquote>autoregressive</blockquote><p>The next token depends on the tokens that already exist.</p><h3>A Simplified Example</h3><p>Let’s ignore tokenization details and imagine the model is generating this sentence:<br><strong>The loan was approved</strong><br>At the beginning, the model processes:</p><p><strong>The</strong><br>To generate the next token, it considers:<br><strong>The</strong><br>and produces:<br><strong>loan</strong><br>Now the sequence is:<br><strong>The loan</strong><br>To generate the next token, it needs information from:<br><strong>The loan</strong><br>Then:<br><strong>The loan was</strong><br>And eventually:<br><strong>The loan was approved</strong></p><p>Without some form of caching, the model would repeatedly perform attention-related work for tokens it had already processed.</p><p><strong>Conceptually:</strong></p><p>Generate<strong> “loan”</strong></p><p>Process:<br><strong>The</strong></p><p>Then:<br>Generate <strong>“was”</strong></p><p>Process:<br><strong>The<br>loan</strong></p><p>Then:<br>Generate <strong>“approved”</strong></p><p>Process:<br><strong>The<br>loan<br>was</strong></p><p>As the sequence gets longer, the amount of historical information grows. This is where KV Cache becomes useful.</p><h3>Where Do K and V Come From?</h3><p>In <a href="https://medium.com/@patil-parag-oss/flashattention-explained-simply-stop-moving-so-much-gpu-data-9bcb121aeb2d">Part 3</a>, while discussing FlashAttention, I introduced the attention operation:</p><p>[ Attention(Q,K,V) = Softmax ( )V ]</p><p>My simple interpretation was:</p><p>Q → What am I looking for?<br>K → What information is available?<br>V → What information should I retrieve?</p><p>Every Transformer attention layer creates:</p><p>Query<br>Key<br>Value</p><p>representations for tokens.</p><p>During generation, the <strong>Key and Value representations of previous tokens do not need to be recreated from scratch every time</strong>.</p><p>They can be stored. That stored information is the:<br><strong>Key-Value Cache</strong><br>or simply:<br><strong>KV Cache</strong></p><h3>Without KV Cache</h3><p>Imagine my initial prompt contains: <strong>4,000 tokens</strong></p><p>The model processes those tokens.</p><p>Now it generates token: <strong>4001</strong></p><p>Without caching, it would need to recreate attention-related Key and Value information for the existing sequence.</p><p>Then it generates: <strong>4002</strong></p><p>and again much of the historical work would have to be performed.</p><p>Conceptually:</p><p><strong>Token 4001</strong><br>Previous 4000 tokens<br> ↓<br>Calculate K/V again<br> ↓<br>Generate token</p><p>Then:</p><p><strong>Token 4002<br></strong> Previous 4001 tokens<br> ↓<br>Calculate K/V again<br> ↓<br>Generate token</p><p>Then:</p><p><strong>Token 4003<br></strong> Previous 4002 tokens<br> ↓<br>Calculate K/V again<br> ↓<br>Generate token</p><p>I don’t need to be a GPU expert to see the problem.<br>We already calculated information for those previous tokens.<br>Why keep recalculating it?</p><h3>With KV Cache</h3><p>Now let’s store the K and V representations.</p><p>The first time the model processes the prompt:</p><p>Prompt<br> ↓<br>Transformer<br> ↓<br>Calculate K and V<br> ↓<br>Store them in KV Cache</p><p>Then when generating the next token:</p><p>New token<br> ↓<br>Calculate Q/K/V for new token<br> ↓<br>Reuse previous K/V<br> ↓<br>Attention<br> ↓<br>Generate next token</p><p>And repeat.</p><p><strong>Conceptually:</strong></p><p><strong>KV CACHE</strong><br>Token 1 → K1 V1<br>Token 2 → K2 V2<br>Token 3 → K3 V3<br>…<br>Token N → Kn Vn<br> ↓<br>Reuse previous state<br> ↓<br>Generate next token</p><p>This is the idea that made KV Cache intuitive for me:</p><blockquote><strong>Calculate the historical K/V states once. Store them. Reuse them.</strong></blockquote><h3>My Spreadsheet Analogy</h3><p>The analogy I use is a spreadsheet. Imagine I have calculated:</p><p>A1<br>A2<br>A3<br>…<br>A1000</p><p>and stored all the results.</p><p>Now I need to calculate: <strong>A1001</strong></p><p>One approach would be:</p><p><strong>Delete A1:A1000<br>Recalculate everything<br>Then calculate A1001</strong></p><p>That would be ridiculous. I already have the previous results. A much more sensible approach is:</p><p><strong>Keep A1:A1000<br>Calculate A1001<br>Store it<br>Continue</strong></p><p>That is how I think about KV Cache.</p><h3>Why KV Cache Matters So Much for Conversational AI</h3><p>A conversational AI system often deals with long input sequences.</p><p>For example:</p><pre>System Prompt             500 tokens<br>Conversation History    2,500 tokens<br>RAG Context             4,000 tokens<br>Current Question          100 tokens<br>------------------------------------<br>Input                   7,100 tokens</pre><p>The model first processes those <strong>7,100 tokens.</strong><br>Then perhaps generates: <strong>800 output tokens</strong><br>During generation, I do not want the model to keep recomputing the entire <strong>7K+ token history.</strong><br>KV Cache allows that historical information to remain available. So:</p><p>Long Prompt<br> ↓<br>Prefill<br> ↓<br>Build KV Cache<br> ↓<br>Token 1<br> ↓<br>Reuse cache<br> ↓<br>Token 2<br> ↓<br>Reuse cache<br> ↓<br>Token 3<br> ↓<br> …</p><p>This is one of the reasons modern LLM inference can generate tokens efficiently.</p><h3>This Also Helped Me Understand Prefill vs Decode</h3><p>In <a href="https://medium.com/@patil-parag-oss/flashattention-explained-simply-stop-moving-so-much-gpu-data-9bcb121aeb2d?sharedUserId=patil-parag-oss">Part 3</a>, I briefly separated inference into two phases.</p><p>KV Cache makes that distinction much clearer.</p><h3>Phase 1 — Prefill</h3><p>The model receives:<br><strong><em>System Prompt + Chat History + RAG Context + User Question</em></strong></p><p>Suppose that totals: <strong>7,000 tokens</strong><br>The model processes the entire input. During this step it builds the initial KV state.</p><p><strong>Conceptually:</strong><br>7,000 tokens<br> ↓<br>Transformer<br> ↓<br>Build KV Cache<br> ↓<br>Ready to generate<br>This is <strong>prefill</strong>.</p><h3>Phase 2 — Decode</h3><p>Now the model generates:</p><p><strong>Token 7001</strong><br>then:<br><strong>Token 7002</strong><br>then:<br><strong>Token 7003</strong></p><p>During this phase:</p><p>previous K/V<br> ↓<br>reuse + new token<br> ↓<br>generate next token</p><p>This is <strong>decode</strong>. So I now think of the inference lifecycle as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*Saa_SDKw1hGkGualwZYMLw.png" /><figcaption>Inference Lifecycle</figcaption></figure><p>And different GPU optimizations affect these phases differently. <strong>FlashAttention can be especially useful during large prefill workloads. <br>KV Cache becomes critical during decode.</strong></p><h3>So KV Cache Must Be Free Performance, Right?</h3><p>This was my next assumption.</p><blockquote><strong>If caching removes repeated computation, why wouldn’t I always use as much cache as possible?</strong></blockquote><p>Because caching introduces another cost:</p><blockquote><strong>Memory</strong></blockquote><p>The KV states need to live somewhere.</p><p>Typically: <strong>GPU VRAM</strong><br>So KV Cache gives me an important trade-off:</p><p>Less computation<br> BUT<br>More memory</p><p>Or:</p><p>Faster decode<br> ↕<br>Higher VRAM consumption</p><p>And this becomes particularly important when serving multiple users.</p><h3>One User Is Easy. Concurrency Changes Everything.</h3><p>Imagine one conversation.</p><p>It has: <strong>8,000 cached tokens</strong><br>Now imagine: <strong>10 concurrent conversations</strong><br>Potentially: <strong>10 separate KV caches</strong></p><p>Then:</p><p><strong>50 concurrent conversations</strong><br>Now I have significant KV-cache memory pressure.<br><strong>Conceptually:</strong></p><pre>User A ████████ KV Cache<br>User B ████████ KV Cache<br>User C ████████ KV Cache<br>User D ████████ KV Cache<br>... <br>User 50 ████████ KV Cache</pre><p>The model weights are mostly shared. But each active sequence has its own token history and associated cache state. This is why KV Cache can become one of the main limits on LLM serving concurrency.</p><h3>A More Useful Way to Think About GPU Memory</h3><p>Before understanding KV Cache, I used to think about GPU memory roughly as:</p><p>GPU VRAM<br> ↓<br>Model</p><p>Now I think more like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*XTmMZEHcSfcSCoIocd89ew.png" /></figure><p>And as concurrency increases:</p><p>Model Weight Memory ≈ mostly fixed<br> <br> KV Cache Memory<br> ↑ with active sequences<br> ↑ with sequence length</p><p>That distinction is important. A model fitting into GPU memory does <strong>not</strong> mean the serving workload will fit.</p><h3>What Determines KV Cache Size?</h3><p>The exact calculation depends on the model architecture.</p><p>But from a developer perspective, the important variables are:</p><p>Number of layers<br>Number of KV heads<br>Head dimension<br>Sequence length<br>KV datatype — Bytes Per Element<br>Number of concurrent sequences — Batch Size</p><p>The intuition is:</p><p>KV Cache Bytes = 2 * Number of layers * Sequence Length * ( Number of KV heads * Head dimension) * Bytes Per Element * Batch Size</p><p>There are two values being stored: K &amp; V so both contribute.</p><p>I don’t need to calculate this manually every time. But understanding the variables tells me what makes KV memory grow.</p><h3>Context Length Is Not Just an Attention Problem</h3><p>Suppose I increase: max context<br> 4K<br> ↓<br> 8K<br> ↓<br> 16K<br> ↓<br> 32K</p><p>There are multiple consequences. Longer context affects attention workload. But it also means:</p><p>more tokens<br> ↓<br>more K/V states<br> ↓<br>larger KV cache</p><p>So increasing context length potentially affects both: Compute &amp; Memory<br>This explains why:<br><strong>“My model supports 32K context” </strong><br>doesn’t automatically mean:<br><strong>“I can serve 100 users at 32K context on one GPU.” </strong><br>Those are completely different claims.</p><h3>KV Cache and Concurrency Are Connected</h3><p>Suppose I have enough VRAM after loading the model to hold:</p><p><strong>100,000 cached tokens</strong></p><p>I’m using round numbers purely for illustration. I could theoretically allocate that capacity in several ways:</p><p>1 user × 100K tokens<br>10 users × 10K tokens<br>20 users × 5K tokens<br>100 users × 1K tokens</p><p>Obviously real inference engines are more sophisticated than this.</p><p>But the trade-off is useful:</p><blockquote><strong>Long context consumes capacity that could otherwise support additional concurrent sequences.</strong></blockquote><p>This is why I think about:</p><p><strong>Context Length<br> vs.<br>Concurrency</strong></p><p>as an architectural trade-off rather than two unrelated settings.</p><h3>What Happens When the KV Cache Fills?</h3><p>This becomes interesting in production.</p><p>Suppose requests continue to arrive and the available KV-cache memory becomes constrained. The inference engine has to manage that pressure.</p><p>Depending on the serving engine and workload, this can lead to behavior such as:</p><p><strong><em>Requests waiting<br>Cache blocks being reused/reclaimed<br>Sequences being scheduled differently<br>Reduced concurrency<br>Potential re-computation/preemption in some situations</em></strong></p><p>So I don’t just monitor: <strong>GPU utilization</strong><br>I also want visibility into: <strong>KV Cache utilization</strong><br>because the GPU may have plenty of compute available while cache memory is becoming the actual bottleneck.</p><h3>Another Anology: A Desk vs Filing Cabinet</h3><p>Imagine the LLM is an employee working at a desk.</p><p>The model weights are the employee’s knowledge. The KV Cache is the material currently spread across the desk.</p><p>One customer arrives:<strong> small stack of documents</strong><br>Fine.<br>Five customers: <strong>more documents</strong><br>Still manageable.<br>Fifty customers: <strong>documents everywhere</strong></p><p>Eventually the desk becomes the bottleneck. Making the employee think faster doesn’t solve the problem. I need better workspace management.</p><p>That’s how I think about KV Cache in a multi-user LLM system.</p><h3>Does BF16 Affect KV Cache?</h3><p>Yes.</p><p>This connects <a href="https://medium.com/@patil-parag-oss/bf16-vs-fp16-why-smaller-numbers-make-local-llms-faster-5110971e0a69?sharedUserId=patil-parag-oss">Part 2</a> directly to Part 5. The KV Cache itself contains floating-point values.</p><p>If those values use:<strong> FP16 / BF16</strong><br>each generally requires: <strong>2 bytes per element</strong>.</p><p>Some inference stacks and GPUs also support lower-precision KV cache formats such as: FP8 which can potentially reduce cache memory further.</p><p><strong>Conceptually:</strong></p><pre>FP16 KV Cache<br>████████████████<br>        ↓<br>FP8 KV Cache<br>████████</pre><p>That can potentially translate into:</p><p>More cache capacity<br> ↓<br>More concurrent sequences<br> or<br>Longer contexts</p><p>But I treat KV-cache quantization as something to benchmark carefully. We’re reducing numerical representation again.</p><p>So I want to validate:</p><p><strong>Output quality <br>Latency<br>Memory savings<br>Hardware/backend support</strong></p><p>before treating it as a free optimization.</p><h3>Now Let’s talk about Prefix Caching</h3><p>This is where terminology can get confusing.</p><p>I often hear: KV Cache &amp; Prefix Cache used as though they are the same thing. They are related. But I find it useful to separate them.</p><h3>Normal KV Cache</h3><p>Imagine one request:<br><strong>System Prompt + Conversation History + Question</strong></p><p>During generation, the model stores K/V states for that sequence.</p><p>Request A<br> ↓<br>KV Cache A<br> ↓<br>Generate next tokens efficiently</p><p>That is the basic KV-cache use case.</p><p>The goal is:</p><blockquote><strong>Don’t recompute previous tokens during this sequence’s generation.</strong></blockquote><h3>Prefix Caching</h3><p>Now imagine many conversations all start with exactly the same large prefix. For example, my banking conversational AI might prepend:</p><p>You are a lending assistant. <br>Follow these policies…<br>Never disclose…<br>Use the following product rules…<br>…</p><p>Suppose that common system/agent instruction consumes: <strong>2,000 tokens</strong></p><p>Customer A asks: <strong>Common 2K prefix + Question A</strong><br>Customer B asks: <strong>Common 2K prefix + Question B</strong><br>Customer C asks: <strong>Common 2K prefix + Question C</strong></p><p>Without prefix caching:</p><p><strong>Request A</strong><br> ↓<br>Process common prefix<br><strong>Request B</strong><br> ↓<br>Process same common prefix again<br><strong>Request C</strong><br> ↓<br>Process same common prefix again</p><p>There is clearly repeated work.</p><p>Prefix caching allows an inference engine to reuse cached KV state corresponding to matching prefixes.</p><p>Conceptually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*GqbYPNFVqEEJbaH694QJuw.png" /><figcaption>Prefix Caching</figcaption></figure><p>This is a different level of reuse.</p><h3>My Mental Model for the Difference</h3><p>I think about them this way:</p><p><strong>KV Cache</strong></p><blockquote><strong>Reuse the past within an active sequence.</strong></blockquote><p><strong>Prefix Cache</strong></p><blockquote><strong>Reuse an already-computed beginning across compatible requests.</strong></blockquote><p>That distinction cleared up a lot of confusion for me.</p><h3>Why Prefix Caching Can Matter in Enterprise Conversational AI?</h3><p>Enterprise prompts often have huge common sections.</p><p>For example:</p><p><em>System instructions<br>Safety policies<br>Agent role<br>Product rules<br>Compliance instructions<br>Output format<br>Tool definitions</em></p><p>These may be repeated on every request.</p><p>Imagine:</p><p><strong>Common Prefix 3,000 tokens<br>Unique User Content 500 tokens</strong></p><p>for thousands of requests.</p><p>If the prefix is identical and the serving engine can reuse it, I may avoid repeatedly processing a large amount of identical input. This can improve: <strong>TTFT, Prompt processing work, GPU efficiency</strong> for requests that actually hit the cache.</p><h3>But Prefix Caching Needs an Exact Match</h3><p>This is where application design starts affecting GPU optimization.</p><p>Consider these prompts:</p><p><strong>Request A:</strong> <br> You are a lending assistant.<br> Current date: 26-Aug-2026.<br> Customer ID: 12345.<br> …<br>and:<br><strong>Request B</strong>: <br> You are a lending assistant.<br> Current date: 26-Aug-2026.<br> Customer ID: 99821.<br> …</p><p>If customer-specific data is injected too early in the prompt, the shared prefix can diverge much sooner.</p><p><strong>Conceptually:</strong></p><p>Common<br>Common<br>Common<br>DIFFERENT<br>Different<br>Different</p><p>The reusable prefix becomes shorter. So prompt construction can influence prefix-cache effectiveness.</p><p><strong>A better structure may be:</strong></p><p>Stable System Instructions<br> ↓<br>Stable Product Rules<br> ↓<br>Stable Tool Definitions<br> ↓<br>Customer-Specific Context<br> ↓<br>Current Question</p><p>Now more of the beginning is identical across requests. That gives the cache more opportunity for reuse. This is a good example of an application-level design decision affecting GPU efficiency.</p><h3>Prompt Engineering Is Suddenly a Systems Problem</h3><p>This was an interesting realization for me. I used to think prompt structure was mostly about: <strong>Model behavior, Accuracy, Instruction following</strong></p><p>But once I care about prefix caching, prompt structure can also influence: <strong>Inference performance</strong></p><p>If I continuously change content near the beginning:</p><p><em>timestamp<br>request ID<br>random identifier<br>customer-specific data</em></p><p>I may destroy potential cache reuse.</p><p>So another developer question I now ask is:</p><blockquote><strong>Which parts of my prompt are stable, and which parts are dynamic?</strong></blockquote><p>That isn’t only a prompt-engineering question anymore. It can be an infrastructure optimization question.</p><h3>How This Maps to My vLLM Deployment</h3><p>In my local deployment, the serving command may include:</p><p><strong>— enable-prefix-caching</strong></p><p>That doesn’t replace the ordinary per-sequence KV Cache. It adds another opportunity for reuse when requests share cached prefixes. So my mental model becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*saG1907jXCLf0cgIZzbvBg.png" /></figure><p>Both are trying to remove repeated work. They just operate in different situations.</p><h3>What I Would Measure</h3><p>Just enabling cache-related features doesn’t tell me whether they helped.</p><p>For conversational AI, I would measure at least:</p><ol><li><strong>TPOT — Time Per Output Token: </strong>KV caching should be directly relevant to decode efficiency.</li><li><strong>Output Tokens per Second : </strong>How quickly is the model generating tokens/sec?</li><li><strong>TTFT : </strong>Normal KV Caching is more decode-focused. Prefix Cache-Hits, however, can improve prompt-processing behavior and therefore TTFT for eligible repeated prefixes.</li><li><strong>KV Cache Utilization : </strong>How much of my cache capacity is being consumed?<br>This tells me whether memory — rather than compute — is becoming the limiting resource.</li><li><strong>Maximum Stable Concurrency :</strong></li></ol><p>I would test:</p><p>1 user<br>5 users<br>10 users<br>25 users<br>50 users<br>100 users</p><p>and record:</p><p>TTFT<br>TPOT<br>KV usage<br>VRAM<br>Throughput</p><p>Eventually there will be a point where adding more active sequences creates unacceptable latency or memory pressure.</p><p>That is the number I care about.</p><h3>I Would Also Measure Prefix Cache Hit Rate</h3><p>If I’ve enabled prefix caching but requests rarely share useful prefixes, the feature may contribute little.</p><p>Suppose:<br><strong>10%</strong> prefix cache hit rate<br>versus:<br><strong>80%</strong> prefix cache hit rate</p><p>Those are very different workloads. This means I also need to understand:</p><ul><li>How repetitive are my prompts?</li><li>How stable is my system prompt?</li><li>How often do requests share product/policy context?</li><li>Where does dynamic content enter?</li></ul><p>Again, the application architecture matters.</p><h3>A Simple Test I Would Run</h3><p>I would create two workload groups.</p><p><strong>Group A — Shared Prefix</strong></p><p>Same system prompt<br>Same policies<br>Same tool definitions<br>Different user questions</p><p><strong>Group B — No Shared Prefix</strong></p><p>Different prefixes<br>Different context<br>Different questions</p><p>Then compare:</p><p>TTFT <br>Input tokens/sec<br>GPU workload<br>Prefix-cache hit rate</p><p>That tells me whether prefix caching is actually relevant to my conversational AI.</p><h3>The Biggest Trade-Off: Speed vs Memory</h3><p>At this point, my KV-cache mental model has two sides.</p><p><strong>Benefit</strong></p><p>Remember previous computation<br> ↓<br>Avoid repeating it<br> ↓<br>Faster generation</p><p><strong>Cost</strong></p><p>Remember previous computation<br> ↓<br>Store it somewhere<br> ↓<br>Consume VRAM</p><p>So the real optimization problem is:<br><strong>How much history can I cache while still supporting the required concurrency?</strong><br>This is very different from:</p><blockquote><strong>“KV Cache is good, so make it as large as possible.”</strong></blockquote><h3>This Is Why More Free VRAM Has Real Value</h3><p><a href="https://medium.com/@patil-parag-oss/bf16-vs-fp16-why-smaller-numbers-make-local-llms-faster-5110971e0a69?sharedUserId=patil-parag-oss">Part 2</a> now becomes even more relevant.</p><p>Suppose BF16 or AWQ saves several gigabytes of model-weight memory. What can I do with that space?</p><p>One answer is:<br><strong>More KV Cache which can mean:<br>Longer conversations <br> or <br>More concurrent users</strong></p><p>So the optimization chain starts connecting:</p><p>AWQ / BF16<br> ↓<br>Reduce model memory<br> ↓<br>More VRAM available<br> ↓<br>Larger effective KV capacity<br> ↓<br>Potentially more concurrent conversations</p><p>This is why I prefer to think about GPU optimizations as a system rather than five isolated switches.</p><h3>And FlashAttention Fits Here Too</h3><p>FlashAttention and KV Cache can sound similar because both involve attention. But they address different waste.</p><p><strong>FlashAttention</strong><br>During attention computation:</p><blockquote><strong>Move less intermediate data.</strong></blockquote><p><strong>KV Cache</strong><br>During generation:</p><blockquote><strong>Don’t calculate previous K/V states again.</strong></blockquote><p><strong>Conceptually:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*oc6VqxOvXafBZDMLWYUOLw.png" /></figure><p>That distinction is worth remembering.</p><h3>What About torch.compile?</h3><p>Part 4 gave me:</p><blockquote><strong>Execute operations smarter.</strong></blockquote><p>KV Cache gives me:</p><blockquote><strong>Avoid executing unnecessary operations in the first place.</strong></blockquote><p>Those are also different.</p><p>Imagine I have an incredibly optimized compiled operation. If I execute it ten unnecessary times, it is still waste. So:</p><p><strong>torch.compile</strong> → Make required computation efficient<br><strong>KV Cache</strong> → Avoid repeating computation that isn’t required</p><p>This is another example of why these techniques complement each other.</p><h3>The Four Optimizations So Far</h3><p>We’re now building a fairly complete mental model.<br><strong>1. BF16 / FP16</strong><br>Make the numbers smaller.<br>Reduces: <strong>Tensor memory + Memory bandwidth</strong></p><p><strong>2. FlashAttention</strong><br>Move less data.<br>Reduces: <strong>Attention-related HBM traffic</strong></p><p><strong>3. torch.compile</strong><br>Execute operations smarter.<br>Reduces: <strong>Execution overhead + Missed optimization opportunities</strong></p><p><strong>4. KV Cache</strong><br>Don’t calculate the past again.<br>Reduces: <strong>Repeated autoregressive computation</strong></p><p>Put them together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*nfUc1sxm5GD0pbogjy9L2g.png" /></figure><p>We’re now making individual inference much more efficient. But one major problem remains.</p><h3>What If I Optimize One Request Perfectly…</h3><p>…and then serve every user one at a time?</p><p>Imagine:</p><p>User A<br> ↓<br>GPU<br> ↓<br>Finish<br> <br>User B<br> ↓<br>GPU<br> ↓<br>Finish<br> <br>User C<br> ↓<br>GPU</p><p>Even if each request uses: BF16, FlashAttention, torch.compile, KV Cache My expensive GPU may still spend too much time below its useful parallel capacity.</p><p>That brings us to the final optimization in this series.</p><h3>My Developer Mental Model</h3><p>If I remember only one sentence from this article, it is:</p><blockquote><strong>KV Cache stores the Key and Value states of tokens the model has already processed so they can be reused instead of recalculated while generating future tokens.</strong></blockquote><p>But my practical version is even shorter:</p><blockquote><strong>Don’t calculate the past again.</strong></blockquote><p>And I keep the trade-off beside it:</p><p>Less recomputation<br> ↓<br>Faster decode<br> <br> BUT<br> <br>More cached state<br> ↓<br>More VRAM</p><p>So whenever I tune KV Cache, I don’t ask only: <br><strong>How fast is token generation?</strong><br>I also ask:</p><blockquote><strong>How much cache memory does each active conversation consume, and what does that do to my concurrency?</strong></blockquote><p>That is the production question.</p><h3>What Comes Next?</h3><p>We have now optimized a single request surprisingly well.<br>But GPUs are massively parallel processors.<br>Serving requests one by one can still leave enormous amounts of hardware capacity unused.</p><p>Suppose:<br><strong>50 users </strong>ask questions at almost the same time.<br>Should I process:</p><p><strong>User 1</strong><br> then<br><strong>User 2</strong><br> then<br><strong>User 3</strong><br>…</p><p>Or can I give the GPU useful work from several conversations at once?</p><p>And if I batch them together, what happens when one prompt is: <strong>200 tokens</strong><br>and another is: <strong>8,000 tokens</strong><br>That’s where batching and bucketing enter the picture.</p><p><strong>Part 6 — Your GPU Is Powerful. So Why Is It Sitting Idle?</strong></p><p>In Part 6, I’ll look at:</p><ul><li>why a GPU can be fast but still poorly utilized,</li><li>why one-request-at-a-time serving wastes parallel capacity,</li><li>what static and dynamic batching mean,</li><li>why LLM batching is harder than normal ML batching,</li><li>why different sequence lengths create padding waste,</li><li>what bucketing solves,</li><li>what continuous batching changes,</li><li>why throughput and user latency can fight each other,</li><li>what max-num-seqs and max-num-batched-tokens mean in a vLLM deployment,</li><li>and how I would find the practical concurrency limit of a GPU.</li></ul><p>The mental model will be:</p><p><strong>Batching / Bucketing → Keep the GPU busy.</strong></p><p><em>This is Part 5 of </em><strong><em>Stop Wasting Your GPU: A Developer’s Guide to Local LLM Optimization</em></strong><em>.</em></p><p><strong>← Previous: </strong><a href="https://medium.com/@patil-parag-oss/what-does-torch-compile-actually-do-to-your-llm-4e3766cd18c4"><strong>Part 4 — What Does torch.compile() Actually Do to Your LLM?</strong></a></p><p><strong>Next → Part 6 — Your GPU Is Powerful. So Why Is It Sitting Idle?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1893ff208d44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Does torch.compile() Actually Do to Your LLM?]]></title>
            <link>https://patil-parag-oss.medium.com/what-does-torch-compile-actually-do-to-your-llm-4e3766cd18c4?source=rss-966c27f82db4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e3766cd18c4</guid>
            <category><![CDATA[gpu-optimization]]></category>
            <category><![CDATA[local-llm]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[gpu]]></category>
            <dc:creator><![CDATA[Parag Patil]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 19:14:47 GMT</pubDate>
            <atom:updated>2026-09-13T19:16:27.192Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 4 of the series: </em><strong><em>Stop Wasting Your GPU — A Developer’s Guide to Local LLM Optimization</em></strong></p><p>By this point in the series, I have made the numbers smaller with <a href="https://medium.com/@patil-parag-oss/bf16-vs-fp16-why-smaller-numbers-make-local-llms-faster-5110971e0a69?sharedUserId=patil-parag-oss">BF16/FP16</a> and reduced unnecessary attention-memory movement with <a href="https://medium.com/@patil-parag-oss/flashattention-explained-simply-stop-moving-so-much-gpu-data-9bcb121aeb2d">FlashAttention</a>.</p><p>But there is still another question I need to answer:</p><blockquote><strong>Even if individual operations are efficient, is PyTorch executing the entire model efficiently?</strong></blockquote><p>That question is what led me to torch.compile().</p><p>And, just like <a href="https://medium.com/@patil-parag-oss/flashattention-explained-simply-stop-moving-so-much-gpu-data-9bcb121aeb2d?sharedUserId=patil-parag-oss">FlashAttention</a>, I initially found the name slightly misleading.</p><p>When I hear “compile,” I naturally think:</p><p>Source Code<br> ↓<br>Compiler<br> ↓<br>Executable</p><p>Something like C, C++, or Java.</p><p>But that isn’t quite the right mental model for what happens when I write:</p><pre>model = torch.compile(model)</pre><p>The model doesn’t suddenly become a completely different program.</p><p>Instead, PyTorch gets an opportunity to look at larger portions of the computation, understand how operations fit together, and execute eligible parts more efficiently.</p><p>The simple mental model I use is:</p><p><strong>torch.compile → Execute operations smarter.</strong></p><p>Let’s unpack what that actually means.</p><h3>First, What Is PyTorch Doing Without torch.compile?</h3><p>Consider a very simplified Transformer block.</p><p>Conceptually, it might contain:</p><p>LayerNorm<br> ↓<br>Linear Projection<br> ↓<br>Attention<br> ↓<br>Residual Add<br> ↓<br>LayerNorm<br> ↓<br>Linear<br> ↓<br>SiLU / GELU<br> ↓<br>Linear<br> ↓<br>Residual Add</p><p>Of course, a real LLM is more complicated.</p><p>And then this block may be repeated:</p><p>20 times/32 times/40 times/80 times</p><p>depending on the model.</p><p>So even though I see:</p><pre>output = model(input)</pre><p>as one line of Python, the GPU sees a large number of operations.</p><h3>PyTorch Eager Execution</h3><p>PyTorch traditionally uses what is called <strong>eager execution</strong>.</p><p>I actually like eager execution as a developer.</p><p>I write:</p><pre>x = layer_norm(x)<br>x = linear(x)<br>x = activation(x)<br>x = x + residual</pre><p>and those operations execute as the program reaches them.</p><p>The mental model is:</p><p>Python sees operation 1<br> ↓<br>Run operation 1<br> <br>Python sees operation 2<br> ↓<br>Run operation 2<br> <br>Python sees operation 3<br> ↓<br>Run operation 3</p><p>That makes development flexible.</p><p>I can:</p><ul><li>add Python conditions,</li><li>print tensors,</li><li>change model logic,</li><li>debug easily,</li><li>inspect intermediate results,</li><li>and write normal Python code.</li></ul><p>This flexibility is one of the reasons PyTorch became so developer-friendly.</p><p>But flexibility has a cost.</p><h3>The GPU Doesn’t Run Python Operations Directly</h3><p>Suppose I write:</p><pre>x = torch.relu(x)</pre><p>The GPU isn’t executing Python’s relu() function.</p><p>PyTorch eventually launches GPU work that performs the operation.</p><p>A simplified picture looks like this:</p><p>Python<br> ↓<br>PyTorch<br> ↓<br>CUDA operation / GPU kernel<br> ↓<br>GPU</p><p><strong>For another operation:</strong></p><p>Python<br> ↓<br>PyTorch<br> ↓<br>Another GPU kernel<br> ↓<br>GPU</p><p><strong>And another:</strong></p><p>Python<br> ↓<br>PyTorch<br> ↓<br>Another GPU kernel<br> ↓<br>GPU</p><p>Now imagine this happening thousands of times while an LLM processes a request.</p><p>That is where execution overhead starts becoming interesting.</p><h3>What Is a GPU Kernel?</h3><p>I don’t need to understand CUDA kernel programming to understand torch.compile.</p><p>I just need one simple idea:</p><blockquote><strong>A GPU kernel is a piece of work launched onto the GPU.</strong></blockquote><p>For example, different kernels may perform things such as:</p><ul><li>Matrix multiplication</li><li>Element-wise addition</li><li>Normalization</li><li>Activation</li><li>Softmax</li><li>Tensor transformation</li></ul><p>Each kernel may execute extremely quickly.</p><p>But launching thousands of small kernels still involves coordination.</p><p><strong>Conceptually:</strong></p><p>CPU / Python<br> ↓<br>Launch kernel<br> ↓<br>GPU executes<br> ↓<br>Launch next kernel<br> ↓<br>GPU executes<br> ↓<br>Launch next kernel</p><p>This gives me another form of GPU waste:</p><blockquote><strong>The GPU may be fast, but I can still feed it work inefficiently.</strong></blockquote><h3>A Restaurant Analogy</h3><p>The analogy that works for me is a restaurant kitchen.</p><p>Imagine the chef is extremely fast.</p><p>But the waiter operates like this:</p><ul><li>Bring one tomato.</li><li>Chef cuts tomato.</li><li>Return to customer.</li><li>Bring one onion.</li><li>Chef cuts onion.</li><li>Return.</li><li>Bring one spice.</li><li>Chef adds spice.</li></ul><p>The chef isn’t slow.</p><p>The <strong>workflow</strong> is slow.</p><p>A better process would be:</p><p>Bring all required ingredients<br> ↓<br>Chef performs related steps together<br> ↓<br>Return finished dish</p><p>That is roughly how I think about compilation.</p><p>The GPU is the chef.</p><p>PyTorch’s execution layer is responsible for giving the chef work.</p><p>torch.compile tries to improve that execution plan.</p><h3>So What Does torch.compile() Actually Do?</h3><p>At the simplest level:</p><pre>compiled_model = torch.compile(model)</pre><p>asks PyTorch to capture portions of the computation graph and optimize them.</p><p>The conceptual flow becomes:</p><p>PyTorch Model<br> ↓<br>Observe Operations<br> ↓<br>Capture Computation Graph<br> ↓<br>Analyze Graph<br> ↓<br>Optimize Eligible Operations<br> ↓<br>Generate Optimized GPU Code<br> ↓<br>GPU</p><p>Under the hood, two names are worth knowing:</p><p>TorchDynamo<br> ↓<br>Graph Capture<br> <br>TorchInductor<br> ↓<br>Code Generation / Optimization</p><p>I don’t need to become an expert in either one to use torch.compile.</p><p>But knowing their roles makes the architecture less mysterious.</p><h3>TorchDynamo: Understand What I’m Doing</h3><p>Imagine my code contains:</p><pre>x = self.norm(x)<br>x = self.linear1(x)<br>x = torch.nn.functional.silu(x)<br>x = self.linear2(x)<br>x = x + residual</pre><p>Instead of treating these as completely unrelated operations forever, TorchDynamo attempts to capture the PyTorch computation into a graph.</p><p>Conceptually:</p><p>Input<br> ↓<br>LayerNorm<br> ↓<br>Linear<br> ↓<br>SiLU<br> ↓<br>Linear<br> ↓<br>Add<br> ↓<br>Output</p><p>Once PyTorch can see this graph, the compiler has more information to work with.</p><p>That is important.</p><p>Because optimization becomes much easier when I can see:</p><p>Operation A feeds B, which feeds C, which feeds D.</p><p>rather than receiving each operation independently.</p><h3>TorchInductor: Find a Better Way to Execute It</h3><p>After the graph has been captured, PyTorch’s compiler backend can generate optimized execution.</p><p>TorchInductor is the default backend used by torch.compile.</p><p>Conceptually:</p><p>Captured Graph<br> ↓<br>TorchInductor<br> ↓<br>Analyze operations<br> ↓<br>Fuse / reorganize eligible work<br> ↓<br>Generate optimized kernels<br> ↓<br>GPU</p><p>On NVIDIA GPUs, generated code may involve technologies such as Triton and CUDA.</p><p>But again, I don’t need to write Triton kernels myself.</p><p>From my perspective:</p><pre>model = torch.compile(model)</pre><p>can allow PyTorch to do much of that work below my application layer.</p><h3>Kernel Fusion Is Where the Idea Becomes Intuitive</h3><p>Consider this deliberately simplified sequence:</p><pre>x = x + bias<br>x = torch.relu(x)<br>x = x * scale</pre><p><strong>Without fusion</strong>, I might conceptually have:</p><p>Kernel 1<br> Add Bias<br> ↓<br> Write result<br> <br> Kernel 2<br> Read result<br> Run ReLU<br> ↓<br> Write result<br> <br> Kernel 3<br> Read result<br> Multiply<br> ↓<br> Write result</p><p>There are multiple launches.</p><p>There can also be intermediate memory traffic.</p><p>A compiler may recognize that compatible operations can be executed together more efficiently.</p><p>Conceptually:</p><p><strong>Fused Kernel</strong><br> <br> Input<br> ↓<br> Add Bias<br> ↓<br> ReLU<br> ↓<br> Multiply<br> ↓<br> Output</p><p>I don’t have to materialize every intermediate in exactly the same way.</p><p>And I don’t necessarily need three separate launches.</p><p>This connects nicely to what I learned in Part 3.</p><p><a href="https://medium.com/@patil-parag-oss/flashattention-explained-simply-stop-moving-so-much-gpu-data-9bcb121aeb2d">FlashAttention </a>said:</p><p>Stop moving so much attention data.</p><p>Compilation says:</p><p>Stop executing the broader model as a collection of unnecessarily isolated operations.</p><h3>This Does Not Mean Everything Gets Fused</h3><p>This is important.</p><p>The mental model is useful, but I don’t want to turn it into an incorrect rule like:</p><p>torch.compile converts the entire Transformer into one giant GPU kernel.</p><p>It doesn’t.</p><p>Some operations:</p><ul><li>already call highly optimized libraries,</li><li>cannot be fused,</li><li>need separate execution,</li><li>contain unsupported behavior,</li><li>or sit across graph boundaries.</li></ul><p>So the actual result might look more like:</p><p><strong>Original Model</strong><br> <br> Operation 1<br> Operation 2<br> Operation 3<br> Operation 4<br> Operation 5<br> Operation 6<br> Operation 7<br> <br><strong>Compiled Execution</strong><br> <br>Optimized Region A<br> ↓<br>Specialized Kernel<br> ↓<br>Optimized Region B<br> ↓<br>Library Operation<br> ↓<br>Optimized Region C</p><p>The objective is not:</p><p>One kernel.</p><p>The objective is:</p><blockquote><strong>A better overall execution plan.</strong></blockquote><h3>What Does This Mean for My Local LLM?</h3><p>Imagine my conversational AI receives:</p><p>System prompt<br> +<br>Conversation history<br> +<br>RAG context<br> +<br>Current question</p><p>The Transformer then performs:</p><p>Embedding<br> ↓<br>Transformer Layer 1<br> ↓<br>Transformer Layer 2<br> ↓<br>Transformer Layer 3<br> ↓<br>…<br> ↓<br>Transformer Layer N</p><p>Each Transformer layer contains many operations.</p><p>So there are two different optimizations happening in our series now.</p><h3>FlashAttention</h3><p>Optimizes a critical operation:</p><p>Attention</p><h3>torch.compile</h3><p>Looks more broadly at:</p><p>Model execution</p><p>That distinction is important.</p><p>I think about the relationship like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*RJZUKEUwOTsCs3QNcOcoYw.png" /></figure><p>They aren’t alternatives.</p><p>They solve different problems.</p><h3>The Code Change Looks Almost Too Easy</h3><p>At its simplest:</p><pre>import torch<br><br>model = load_model()<br>model = model.cuda()<br><br>model = torch.compile(model)<br><br>Then:<br><br>output = model(inputs)<br><br>Or perhaps:<br><br>compiled_model = torch.compile(model)<br><br>output = compiled_model(inputs)</pre><p>That makes torch.compile look like a free performance switch.</p><p>And this is where I need to be careful.</p><p>Because compilation introduces trade-offs.</p><p>The first one is impossible to miss.</p><h3>Why Is My First Compiled Request Slower?</h3><p>Suppose I benchmark this:</p><pre>start_timer()<br><br>output = compiled_model(inputs)<br><br>stop_timer()</pre><p>and compare it against eager mode.</p><p>I may conclude:</p><blockquote>torch.compile made my model slower!</blockquote><p>But the first request is paying for something that later requests may reuse:</p><p>Capture graph<br> ↓<br>Analyze graph<br> ↓<br>Generate optimized code<br> ↓<br>Compile kernels<br> ↓<br>Execute</p><p>This is <strong>compilation overhead</strong>.</p><p>PyTorch uses just-in-time compilation, so the first calls to a new compiled path can pay a substantial cold-start cost. Current PyTorch guidance explicitly warns that the first one or two invocations can be slower for this reason.</p><p>This changed how I benchmark.</p><p><strong>I don’t compare:</strong></p><p>First eager request<br> vs.<br>First compiled request</p><p><strong>I compare:</strong></p><p>Eager steady state<br> vs.<br>Compiled steady state</p><p>after appropriate warm-up.</p><h3>My Benchmark Should Look More Like This</h3><p>Conceptually:</p><pre>compiled_model = torch.compile(model)<br><br># Warm-up<br>for _ in range(10):<br>    compiled_model(inputs)<br><br>torch.cuda.synchronize()<br><br># Benchmark<br>start = time.perf_counter()<br><br>for _ in range(100):<br>    compiled_model(inputs)<br><br>torch.cuda.synchronize()<br><br>elapsed = time.perf_counter() - start</pre><p>The exact benchmark depends on my model and serving architecture.</p><p>But the principle is:</p><blockquote><strong>Don’t include compilation time in a benchmark intended to measure steady-state inference speed.</strong></blockquote><p>Unless cold-start latency itself matters to my application.</p><p>And sometimes it absolutely does.</p><h3>Cold Start Can Matter in Production</h3><p>Imagine a persistent LLM server.</p><p>It starts once.</p><p>Runs for days.</p><p>Processes thousands of requests.</p><p>Then compilation overhead may be easy to amortize.</p><p>Server Start<br> ↓<br>Compile / Warm Up<br> ↓<br>Request<br>Request<br>Request<br>Request<br>Request<br>…</p><p>But imagine an environment that frequently:</p><p>Starts container<br> ↓<br>Handles few requests<br> ↓<br>Shuts down</p><p>Now compilation overhead becomes much more important.</p><p>So I don’t ask:</p><blockquote>Is torch.compile faster?</blockquote><p>I ask:</p><blockquote><strong>Does the steady-state improvement justify the compilation cost for my deployment model?</strong></blockquote><h3>Then I Discovered Graph Breaks</h3><p>Graph capture sounds straightforward until normal Python gets involved.</p><p>Suppose some part of my model contains behavior the compiler cannot capture cleanly.</p><p>PyTorch may need to stop the current graph and return temporarily to normal Python/eager execution.</p><p><strong>Conceptually:</strong></p><p>Compiled Graph<br> ↓<br>Operation<br> ↓<br> <br><strong>GRAPH BREAK</strong><br> <br> ↓<br>Python / Eager Work<br> ↓<br>Capture another graph<br> ↓<br>Compiled Graph</p><p>This is called a <strong>graph break</strong>.</p><p>One graph break doesn’t automatically destroy all performance.</p><p>But lots of graph breaks can reduce the amount of useful work available for optimization.</p><p>So if I see disappointing results, one question I ask is:</p><blockquote>Is the model actually being compiled into useful regions, or am I constantly falling back across graph boundaries?</blockquote><p>PyTorch provides tooling for diagnosing this.</p><p>For me, the important lesson is simpler:</p><blockquote><strong>Calling torch.compile() does not guarantee that every line of the model is actually compiled.</strong></blockquote><h3>Dynamic Shapes Make Conversational AI Interesting</h3><p>Now things get especially relevant to LLMs.</p><p>Suppose I send these requests:</p><pre>Request A<br>500 tokens<br> <br>Request B<br>1,200 tokens<br><br>Request C<br>4,000 tokens<br> <br>Request D<br>780 tokens<br> <br>Request E<br>8,000 tokens</pre><p>The tensor shapes can vary because sequence length varies.</p><p>That creates an interesting compiler problem.</p><p>Compilers generally have an easier time optimizing something predictable like:</p><pre>Always 1024 tokens<br>than:<br>437 tokens<br> <br>1389 tokens<br> <br>4096 tokens<br> <br>7832 tokens</pre><p>If compiled code becomes overly specialized to one shape, another shape may require a new compiled version.</p><p>Conceptually:</p><p>500 tokens<br> ↓<br>Compile Graph A<br> <br>1200 tokens<br> ↓<br>Different shape<br> ↓<br>Compile Graph B<br> <br>4000 tokens<br> ↓<br>Different shape<br> ↓<br>Compile Graph C</p><p>Now I am repeatedly paying compilation cost.</p><p>That is called <strong>recompilation</strong>.</p><h3>PyTorch Does Have Dynamic Shape Support</h3><p>Modern torch.compile can handle dynamic dimensions.</p><p>So the situation isn’t simply:</p><p>Different sequence length = always compile again.</p><p>PyTorch can recognize dimensions that vary and generate graphs capable of handling multiple sizes in appropriate situations.</p><p>But dynamic shapes introduce another trade-off:</p><p>Highly specialized graph<br> ↓<br>Potentially stronger optimization<br> <br>More dynamic graph<br> ↓<br>Greater shape flexibility</p><p>The compiler has to find a practical balance.</p><p>Current PyTorch defaults attempt to detect when dimensions vary and can move toward more dynamic handling after recompilation.</p><p>As a developer, that means I usually don’t start by forcing every possible dimension to be dynamic.</p><p>I start by measuring the default behavior.</p><h3>This Connects Directly to Bucketing</h3><p>Remember one of the optimizations still coming later in the series:</p><p>Batching / Bucketing → Keep the GPU busy</p><p>Bucketing also has an interesting relationship with compiled execution.</p><p>Suppose I organize requests into approximate sequence-length groups:</p><pre>Bucket A<br>0–512<br> <br>Bucket B<br>513–1024<br> <br>Bucket C<br>1025–2048<br> <br>Bucket D<br>2049–4096</pre><p>Now the model sees a more predictable set of shapes.</p><p>That can help multiple parts of the stack:</p><ul><li>Less padding waste</li><li>Better batching behavior</li><li>More predictable execution shapes</li></ul><p>So these GPU optimizations don’t live in complete isolation.</p><p>They start reinforcing one another.</p><h3>Static Workloads Are the Compiler’s Happy Place</h3><p>Imagine an offline job:</p><pre>Batch Size = 32<br><br>Sequence Length = 2048<br><br>Same model<br><br>Thousands of iterations</pre><p>This is a highly predictable workload.</p><p>Compilation has a great opportunity to amortize startup cost.</p><p>Now compare that with an interactive chatbot:</p><pre>User A = 83 tokens<br><br>User B = 7,920 tokens<br><br>User C = 413 tokens<br><br>User D = 2,370 tokens<br><br>Traffic comes and goes</pre><p>The second workload is much more dynamic.</p><p>That doesn’t mean torch.compile is useless.</p><p>It means:</p><blockquote><strong>The benefit has to be measured in the context of the serving workload.</strong></blockquote><h3>Another Trap: Compiling generate()</h3><p>When developers first discover torch.compile, an obvious idea is:</p><pre>model.generate = torch.compile(model.generate)</pre><p>or simply compile everything surrounding generation.</p><p>But LLM generation contains more than one repeated tensor computation.</p><p>There can be:</p><ul><li>Python orchestration,</li><li>stopping logic,</li><li>sampling,</li><li>cache management,</li><li>shape changes,</li><li>control flow,</li><li>token-by-token loops.</li></ul><p>Sometimes the most valuable approach is compiling appropriate model forward paths rather than assuming every surrounding piece of application control flow belongs inside one compiled graph.</p><p>This is one reason dedicated inference engines become interesting.</p><h3>What Changes When I Use vLLM?</h3><p>In the implementation I am currently thinking about, the local LLM is served using an inference engine such as vLLM.</p><p>That changes my responsibility.</p><p>With raw PyTorch I might explicitly write:</p><pre>model = torch.compile(model)</pre><p>With an inference engine, compilation and CUDA execution optimizations may already be integrated into the serving stack.</p><p>So I don’t automatically wrap the model myself.</p><p>My mental model changes from:</p><p>I need to implement torch.compile</p><p>to:</p><p><strong>I need to verify that the serving engine’s optimized execution path is active</strong></p><p>That means checking:</p><ul><li>Is eager mode being forced?</li><li>Is compilation enabled?</li><li>Are CUDA Graphs being used?</li><li>Are there repeated recompilations?</li><li>How long is warm-up?</li><li>What happens to TTFT?</li><li>What happens to TPOT?</li></ul><p>This is a broader engineering principle I keep seeing throughout this series:</p><blockquote><strong>Once I use a mature inference engine, my job moves from implementing low-level optimizations to configuring and measuring them correctly.</strong></blockquote><h3>torch.compile and CUDA Graphs Are Related but Not the Same Thing</h3><p>Another term that appears around compiled inference is:</p><p>CUDA Graphs</p><p>The names can make them sound interchangeable.</p><p>They’re not.</p><p>At a high level:</p><h3>torch.compile</h3><p>Focuses on:</p><p>Understanding computation<br> ↓<br>Optimizing computation<br> ↓<br>Generating better execution</p><h3>CUDA Graphs</h3><p>Help reduce repeated CPU-side launch overhead by capturing a sequence of GPU operations that can be replayed efficiently.</p><p><strong>Very simplified:</strong></p><p><strong>Normal execution</strong><br> <br>CPU<br> ↓<br>Launch A<br> ↓<br>Launch B<br> ↓<br>Launch C<br> ↓<br>Launch D<br> <br><strong>CUDA Graph replay</strong><br> <br>CPU<br> ↓<br>Replay captured GPU work</p><p>The technologies can complement one another.</p><p>Current torch.compile configurations can use CUDA Graph-related optimizations on GPU, and serving engines may combine these techniques themselves.</p><p>Again, I don’t need to manually implement all of this to understand the objective:</p><blockquote><strong>Reduce the orchestration required to keep repeating predictable GPU work.</strong></blockquote><h3>How Does This Affect TTFT and TPOT?</h3><p>Let’s connect compilation to the conversational AI metrics from Part 1.</p><h3>TTFT — Time to First Token</h3><p>Compilation can affect TTFT in two opposite ways.</p><h3>Cold path</h3><p>Request<br> ↓<br>Compilation required<br> ↓<br>Higher TTFT</p><h3>Warm steady state</h3><p>Request<br> ↓<br>Reuse compiled execution<br> ↓<br>Potentially lower model execution latency</p><p>That’s why I need to distinguish:</p><p>Cold TTFT<br> vs.<br>Warm TTFT</p><p>If I don’t, my benchmark can be misleading.</p><h3>TPOT — Time Per Output Token</h3><p>During decode, the model repeatedly executes a forward path to generate the next token.</p><p>If that repeated execution can use an optimized compiled path, small improvements can accumulate over hundreds of generated tokens.</p><p>Conceptually:</p><p>Token 1 — — — -save a little<br>Token 2 — — — -save a little<br>Token 3 — — — -save a little<br>…<br>Token 500 — — — cumulative saving</p><p>This is one reason repetitive inference workloads can benefit from compilation.</p><h3>What About Throughput?</h3><p>Suppose my GPU serves multiple conversations.</p><p>If compilation reduces overhead per model execution:</p><p>Less overhead/request<br> ↓<br>More useful GPU work/time<br> ↓<br>Potentially higher throughput</p><p>But throughput may still be dominated by completely different things:</p><ul><li>Memory bandwidth</li><li>Attention</li><li>KV-cache capacity</li><li>Batch size</li><li>Model size</li><li>Request scheduling</li></ul><p>So I never assume:</p><p>torch.compile enabled<br> ↓<br>throughput automatically fixed</p><p>It removes one category of waste.</p><p>That’s all.</p><h3>The Benchmark I Would Actually Run</h3><p>For my local conversational AI, I would compare:</p><p><strong>Eager / baseline execution<br> vs.<br>Compiled execution</strong></p><p>under realistic workloads.</p><p>Not one prompt.</p><p>Several.</p><pre>Prompt sizes<br>Short<br>~512 tokens<br> <br>Medium<br>~2K tokens<br> <br>Long<br>~4K tokens<br> <br>Very Long<br>~8K tokens<br><br>Output sizes<br>Short answer<br>~100 tokens<br> <br>Normal answer<br>~500 tokens<br> <br>Long answer<br>~1K tokens<br><br>Concurrency<br>1<br>5<br>10<br>25<br>50</pre><p>Then measure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*4y-2DbRB1FYuVFB-O6GaPQ.png" /></figure><p>That last metric is especially important.</p><p>Because an impressive warm benchmark on one fixed sequence length can hide a completely different production behavior.</p><h3>I Would Warm Up More Than One Shape</h3><p>Suppose production traffic commonly contains:</p><p>512-token prompts<br> <br>2K-token prompts<br> <br>4K-token prompts</p><p>Then warming up only:</p><p>512 tokens</p><p>may not represent the actual runtime.</p><p>A more useful warm-up might include representative shapes:</p><p>Warm up<br> ↓<br>Short<br> <br>Warm up<br> ↓<br>Medium<br> <br>Warm up<br> ↓<br>Long</p><p>Then benchmark the real traffic mix.</p><p>That is a more realistic way to evaluate a compiled conversational workload.</p><h3>When Might torch.compile Not Help Much?</h3><p>This is important because technical articles often stop at:</p><p>Enable this and your model gets faster.</p><p>Reality is less convenient.</p><p>I would expect limited benefit or additional complexity when:</p><h3>1. The workload changes constantly</h3><p>Highly variable shapes and control flow may reduce reusable compiled execution.</p><h3>2. The model already spends nearly all its time inside highly optimized kernels</h3><p>If 95% of execution is dominated by one already-optimized operation, reducing Python overhead around the remaining 5% can only help so much.</p><h3>3. The process is extremely short-lived</h3><p>If I compile for 30 seconds and run inference for 5 seconds, compilation wasn’t a good trade.</p><h3>4. Graph breaks are frequent</h3><p>Large portions of the program may remain outside optimized graphs.</p><h3>5. My bottleneck is somewhere else</h3><p>For example:</p><ul><li>GPU memory capacity</li><li>KV-cache pressure</li><li>Poor batching</li><li>Network latency</li><li>Slow tokenization</li><li>RAG retrieval</li><li>CPU preprocessing</li></ul><p>torch.compile cannot fix those problems.</p><h3>This Is Why Profiling Comes Before Optimization</h3><p>Suppose my end-to-end request takes:</p><p><strong><em>1000 ms</em></strong></p><p>and the breakdown is:</p><p><strong><em>RAG retrieval 400 ms<br> <br>Prompt processing 300 ms<br> <br>Token generation 250 ms<br> <br>Other 50 ms</em></strong></p><p>Even if torch.compile somehow improved model execution substantially, it cannot eliminate the 400 ms retrieval time.</p><p>Likewise:</p><p><strong><em>User waits 5 seconds in scheduler queue</em></strong></p><p>cannot be fixed with kernel fusion.</p><p>This is why I keep coming back to:</p><blockquote><strong>Optimize the bottleneck, not the technology.</strong></blockquote><h3>Before vs After: My Mental Picture</h3><h3>Eager Execution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*txtyfxz8PVt6QWfR3FbwZQ.png" /></figure><h3>Compiled Execution</h3><p>PyTorch Model<br> ↓<br>Graph Capture<br> ↓<br>Graph Optimization<br> ↓<br>Optimized Execution Regions<br> ↓<br>GPU</p><p>The math hasn’t magically disappeared.</p><p>The model isn’t smarter.</p><p>The answer isn’t supposed to become more accurate.</p><p>The execution is simply being organized more intelligently.</p><h3>How the First Three Optimizations Now Fit Together</h3><p>The architecture is starting to become interesting.</p><h3>BF16 / FP16</h3><p>Make the numbers smaller.</p><p>This attacks:</p><p>Tensor memory + Memory bandwidth</p><h3>FlashAttention</h3><p>Move less data.</p><p>This attacks:</p><p>Attention-related memory IO</p><h3>torch.compile</h3><p>Execute operations smarter.</p><p>This attacks:</p><p>Framework overhead + Kernel-launch overhead + Missed graph optimization opportunities</p><p>Together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*dy_9gBLVEAJBi7HtEpXLYw.png" /></figure><p>But there is still a huge inefficiency left.</p><h3>The LLM Is Generating One Token at a Time</h3><p>Imagine the model generates:</p><p>Your<br>Your loan<br>Your loan application<br>Your loan application has<br>Your loan application has been<br>Your loan application has been approved</p><p>Every next token depends on everything that came before it.</p><p>And that raises an obvious question:</p><blockquote><strong>Do I really need to calculate the previous token information again and again?</strong></blockquote><p>I don’t.</p><p>And that is exactly what the next optimization is about.</p><h3>My Developer Mental Model</h3><p>If I remember only one sentence about torch.compile, it is:</p><blockquote><strong>torch.compile gives PyTorch a chance to understand more of my computation before executing it, so eligible work can be organized and generated more efficiently.</strong></blockquote><p>Or in the simplified mental model for this series:</p><blockquote><strong>Execute operations smarter.</strong></blockquote><p>I think about it like this:</p><p><strong>Without compilation</strong><br> <br>Do operation<br> ↓<br>Launch<br> ↓<br>Do operation<br> ↓<br>Launch<br> ↓<br>Do operation<br> ↓<br>Launch<br> <br><strong>With compilation</strong><br> <br>Understand larger computation<br> ↓<br>Optimize eligible regions<br> ↓<br>Generate better execution<br> ↓<br>Reuse it</p><p>And I keep three warnings next to that mental model:</p><ul><li>Compilation has a startup cost.</li><li>Dynamic workloads can trigger recompilation.</li><li>Not everything can or should be compiled.</li></ul><p>Those three points are just as important as the potential speed improvement.</p><h3>What Comes Next?</h3><p>We have now removed three different kinds of GPU waste:</p><p>Too much tensor memory<br> ↓<br><a href="https://medium.com/@patil-parag-oss/bf16-vs-fp16-why-smaller-numbers-make-local-llms-faster-5110971e0a69?sharedUserId=patil-parag-oss"> BF16 / FP16</a><br> <br> Too much attention memory traffic<br> ↓<br> <a href="https://medium.com/@patil-parag-oss/flashattention-explained-simply-stop-moving-so-much-gpu-data-9bcb121aeb2d">FlashAttention</a><br> <br> Execution overhead<br> ↓<br> torch.compile</p><p>But during autoregressive generation, the model has another opportunity for waste.</p><p>It has already calculated information about the previous tokens.</p><p>Why calculate that information again?</p><p>That brings us to:</p><blockquote>Part 5 — KV Cache Explained: Stop Making Your LLM Recalculate the Past</blockquote><p>In Part 5, I’ll explore:</p><ul><li>why LLM generation happens token by token,</li><li>what Key and Value tensors actually represent,</li><li>what happens without a KV cache,</li><li>what gets stored in a KV cache,</li><li>why KV cache dramatically changes decode performance,</li><li>why longer conversations increase KV-cache memory,</li><li>why cache memory can become the real concurrency limit,</li><li>how prefix caching differs from normal KV caching,</li><li>and what I would measure in a local conversational AI system.</li></ul><p>The mental model will be:</p><p><strong>KV Cache → Don’t calculate the past again.</strong></p><p><em>This is Part 4 of </em><strong><em>Stop Wasting Your GPU: A Developer’s Guide to Local LLM Optimization</em></strong><em>.</em></p><p><strong>← Previous: Part 3 — </strong><a href="https://medium.com/@patil-parag-oss/flashattention-explained-simply-stop-moving-so-much-gpu-data-9bcb121aeb2d?sharedUserId=patil-parag-oss"><strong>FlashAttention Explained Simply: Stop Moving So Much GPU Data</strong></a></p><p><strong>Next → Part 5 — KV Cache Explained: Stop Making Your LLM Recalculate the Past</strong></p><h3>Technical references</h3><p>The technical behavior described here aligns with current PyTorch documentation for torch.compile, including TorchDynamo graph capture, TorchInductor as the default backend, graph breaks, dynamic-shape behavior, recompilation, and cold-start compilation overhead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e3766cd18c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MSOCK Through a Banking Lens: What Changes When Enterprise Knowledge Becomes…]]></title>
            <link>https://patil-parag-oss.medium.com/understanding-msock-through-a-banking-lens-what-changes-when-enterprise-knowledge-becomes-fe95b904dc60?source=rss-966c27f82db4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe95b904dc60</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[enterprise-ai]]></category>
            <category><![CDATA[banking-technology]]></category>
            <category><![CDATA[enterprise-architecture]]></category>
            <dc:creator><![CDATA[Parag Patil]]></dc:creator>
            <pubDate>Wed, 09 Sep 2026 17:56:21 GMT</pubDate>
            <atom:updated>2026-09-09T17:56:21.628Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding MSOCK Through a Banking Lens: What Changes When Enterprise Knowledge Becomes Connected?</h3><blockquote><strong>Disclaimer:</strong> This article is based purely on my understanding of the publicly available MSOCK documentation. I have used banking examples, simplified flows, and conceptual diagrams to explain how I interpret the idea. These are illustrative and should not be taken as a representation of Purple Fabric’s actual architecture, product implementation, or enterprise solution.</blockquote><p>I have been following <a href="https://purplefabric.ai/"><strong>Purple Fabric</strong></a> since its early days, and it has been interesting to see how the platform has evolved over the years.</p><p>What started as an interesting direction around enterprise AI and knowledge has gradually moved towards a much broader problem:</p><blockquote><strong>how do we make AI genuinely useful inside a complex enterprise where knowledge is distributed across applications, people, documents, APIs, databases, infrastructure and processes?</strong></blockquote><p>The recently released <a href="https://purplefabric.ai/msock/"><strong>MSOCK — Multidimensional-Multilayer System of Connected Knowledge</strong></a><strong> — </strong>is an interesting evolution in that journey.</p><p>Congratulations to the Purple Fabric team on the MSOCK release.</p><p>Rather than trying to explain MSOCK purely through its architecture or terminology, I wanted to look at it from a perspective I am more familiar with: <strong>a banking enterprise.</strong></p><p>Because, in my view, the easiest way to understand MSOCK is to ask a simple question:</p><blockquote><strong>How would a bank handle a change today, and how could the same change be handled if its enterprise knowledge were connected through something like MSOCK?</strong></blockquote><p>Let us take a practical example.</p><h3>A simple banking change that is rarely simple</h3><p>Assume a bank offers Personal Loans.</p><p>The current maximum eligible loan amount configured for a particular product is: <strong>₹20 lakh</strong></p><p>The business decides to increase it to: <strong>₹25 lakh</strong></p><p>At first glance, this sounds like a configuration change.</p><p>Change <strong>₹20 lakh</strong> to <strong>₹25 lakh</strong>.</p><p>Done.</p><p>Anyone who has worked on a large banking platform knows that it is rarely that simple.</p><p>That number may appear in several places.</p><p>For example:</p><ul><li><em>Product configuration</em></li><li><em>Loan Origination System</em></li><li><em>Eligibility rules</em></li><li><em>Credit decision engine</em></li><li><em>Mobile application validation</em></li><li><em>Internet banking</em></li><li><em>API validations</em></li><li><em>Database configuration</em></li><li><em>Sanction letter generation</em></li><li><em>Underwriting workflow</em></li><li><em>Reporting</em></li><li><em>Test cases</em></li><li><em>Operational procedures</em></li></ul><p>There may even be systems where the <strong>₹20 lakh</strong> limit is not obvious at all but influences another rule indirectly.</p><p>And this is where the real problem starts.</p><h3>The bank without MSOCK</h3><p>Imagine the business raises the following change request:</p><blockquote><strong>Increase the maximum Personal Loan amount from ₹20 lakh to ₹25 lakh.</strong></blockquote><p>The Business Analyst starts analyzing the requirement.</p><p>The natural first question is:</p><blockquote><strong><em>What will this change impact?</em></strong></blockquote><p>The answer often depends on whom you ask.</p><ul><li><em>The product team understands the product configuration.</em></li><li><em>The LOS team understands loan origination.</em></li><li><em>The credit team understands eligibility rules.</em></li><li><em>The API team understands service integrations.</em></li><li><em>The mobile team understands customer-facing validations.</em></li><li><em>The database team understands the underlying schema.</em></li><li><em>The DevOps team understands deployment configuration.</em></li><li><em>The compliance team understands applicable controls.</em></li><li><em>QA understands the regression scenarios.</em></li></ul><p>All of these teams may have the correct answer from their respective perspective.</p><p>The problem is that <strong>no individual perspective represents the complete system</strong>.</p><p>So the organization starts connecting the dots manually.</p><p>A typical exercise may look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYG-9QPWIaHdnWkv_8ysWg.png" /><figcaption>Requirement Impact Assessment Workflow</figcaption></figure><p>This is not necessarily an inefficient organization.</p><p>It is simply the reality of large enterprises.</p><p>Over the years, systems evolve. Teams change. Applications are modernized. New channels are introduced. APIs are added. Some business rules move into rule engines while others remain inside application code. Documentation and implementation do not always evolve at exactly the same speed.</p><p>Eventually, a significant part of the organization’s architectural understanding exists in people’s heads.</p><h3>And this creates an interesting risk</h3><p>Suppose the first impact assessment identifies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*zmjYqbD4FCKG_hl0bx6urg.png" /><figcaption>Impact Assessment</figcaption></figure><p>This looks reasonable.</p><p><strong><em>Development starts.</em></strong></p><p><strong><em>During testing, someone discovers that the mobile application still has a ₹20 lakh validation.</em></strong></p><p><strong><em>That gets fixed.</em></strong></p><p><strong><em>Later, the sanction-letter service rejects an amount above ₹20 lakh because of an old validation.</em></strong></p><p><strong><em>That gets fixed too.</em></strong></p><p><strong><em>During UAT, reporting identifies another downstream dependency.</em></strong></p><p>None of these problems individually is extraordinary.</p><p>The underlying issue is more fundamental:</p><blockquote><strong>The organization had the knowledge, but the knowledge was distributed.</strong></blockquote><p>Humans had to reconstruct the relationship every time a change occurred.</p><h3>Now imagine the same bank with MSOCK</h3><p>This is where I find the MSOCK concept interesting.</p><p>Instead of looking at enterprise assets independently, imagine that the bank has a connected knowledge model that understands relationships across different layers of the enterprise.</p><p>For example:</p><p>Personal Loan Journey<br> ├── <em>Product</em><br> ├── <em>Business Rules</em><br> ├── <em>User Interfaces</em><br> ├── <em>APIs</em><br> ├── <em>Services</em><br> ├── <em>Databases</em><br> ├── <em>Events</em><br> ├── <em>Infrastructure</em><br> ├── <em>Operations</em><br> └── <em>Controls</em></p><p>Now let us look again at:</p><blockquote><strong>Maximum Personal Loan Amount</strong></blockquote><p>Instead of this being merely a field in a product table, the knowledge model could understand that it is related to:</p><p>Maximum Personal Loan Amount<br> ├── <em>Personal Loan Product</em><br> ├── <em>Eligibility Rule</em><br> ├── <em>Loan Application Journey</em><br> ├── <em>Eligibility API</em><br> ├── <em>Eligibility Service</em><br> ├── <em>Product Configuration</em><br> ├── <em>Database Attribute</em><br> ├── <em>Mobile Validation</em><br> ├── <em>Web Validation</em><br> ├── <em>Sanction Process</em><br> ├── <em>Reports</em><br> └── <em>Test Cases</em></p><p>That changes the nature of the problem.</p><p>Instead of asking several teams to first discover the system, we can start by asking:</p><blockquote><strong>What is connected to this business rule?</strong></blockquote><p>And more importantly:</p><blockquote><strong>Which of those connected objects are actually affected if this rule changes?</strong></blockquote><p>That distinction is important.</p><h3>Connected does not always mean impacted</h3><p>Consider an EMI calculation service.</p><p>It is connected to the Personal Loan product.</p><p>But changing the maximum eligible loan amount from <strong>₹20 lakh</strong> to <strong>₹25 lakh</strong> may not require any code change in EMI calculation because the service already accepts arbitrary principal amounts within a broader range.</p><p>Similarly, Collections is connected to a Personal Loan account, but the maximum origination amount may not change Collections behavior at all.</p><p>So blindly following every dependency would create another problem:</p><blockquote><strong>everything would appear impacted.</strong></blockquote><p>This is where the blast-radius concept becomes particularly relevant.</p><p>The useful question is not:</p><blockquote>What is connected?</blockquote><p>It is:</p><blockquote><strong>What must change, what should be regression-tested, and what can safely remain untouched?</strong></blockquote><p>For our example, the result might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*uPftHsyudf5AmAFreUnyHw.png" /><figcaption>Blast Radius of the Personal Loan Eligibility Change</figcaption></figure><p>The value is not merely producing this table.</p><p>The real value would be the ability to answer:</p><blockquote><strong>Why is each item present in this table?</strong></blockquote><h3>Evidence makes the difference</h3><p>Imagine the system says that the Mobile Loan Application must change.</p><p>An architect or developer should be able to follow the reasoning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNr2eGkBXhqbUMmsjS-2dQ.png" /><figcaption>From Business Rule to Technical Impact: A Traceable Reasoning Path</figcaption></figure><p>This is an important distinction between simply asking an LLM a question and giving AI access to connected enterprise knowledge.</p><p>An LLM can generate a plausible answer.</p><p>An enterprise needs an answer that can be <strong>examined, challenged and validated</strong>.</p><p>Particularly in banking.</p><h3>The same enterprise, viewed differently</h3><p>Another aspect of MSOCK that I find useful is the idea that the same underlying enterprise can be viewed from different perspectives.</p><p>Take our Personal Loan example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vt8V8fu0g4ZM7_AifM8zrA.png" /><figcaption>One Enterprise, Multiple Perspectives: MSOCK’s Multidimensional View</figcaption></figure><p>Traditionally, these may exist as five different diagrams maintained by five different teams.</p><p>Over time, they can diverge.</p><p>The more interesting model is:</p><blockquote><strong>Different views of the same connected knowledge.</strong></blockquote><p>That is how I interpret the “multidimensional” aspect of MSOCK in practical enterprise terms.</p><h3>Why this becomes especially relevant with AI agents</h3><p>This discussion becomes even more important as banks begin adopting AI-assisted development and agentic engineering.</p><p>Consider a coding agent receiving this instruction:</p><blockquote><strong>Change the Personal Loan maximum eligibility from ₹20 lakh to ₹25 lakh.</strong></blockquote><p>If the agent only has access to one Git repository, it may correctly find:</p><p><strong>MAX_LOAN_AMOUNT = 2000000</strong></p><p>and change it to:</p><p><strong>MAX_LOAN_AMOUNT = 2500000</strong></p><p>The code change may be perfectly correct.</p><p>But the enterprise change may still be incomplete.</p><p>This is one of the challenges I see with enterprise adoption of coding agents.</p><blockquote><strong>Coding intelligence is not the same as enterprise understanding.</strong></blockquote><p>The agent may understand Java extremely well.</p><p>It may understand Spring Boot.</p><p>It may write excellent unit tests.</p><p>But does it know that the same rule affects:</p><ul><li>a mobile journey,</li><li>another API,</li><li>a product configuration,</li><li>a sanction process,</li><li>a reporting flow,</li><li>and three regression scenarios?</li></ul><p>That knowledge exists outside the immediate code-generation problem.</p><p>With connected enterprise context, the same request could first become:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PgJ7Y0jAHztifsvINB4_Lg.png" /><figcaption>From Business Change to Implementation: MSOCK-Guided Impact Analysis Flow</figcaption></figure><p>That, to me, is where MSOCK becomes more interesting than simply another AI coding capability.</p><h3>Consider a regulatory change instead</h3><p>The value becomes even clearer with regulatory requirements.</p><p>Imagine a new regulatory requirement changes how customer consent must be captured and retained.</p><p>Where does customer consent exist in a bank?</p><p>Potentially in:</p><ul><li><em>Mobile Banking</em></li><li><em>Internet Banking</em></li><li><em>Loan Origination</em></li><li><em>Credit Cards</em></li><li><em>CRM</em></li><li><em>WhatsApp Banking</em></li><li><em>Marketing</em></li><li><em>Data Platforms</em></li><li><em>Analytics</em></li><li><em>Third-party Integrations</em></li><li><em>Document Management</em></li></ul><p>Now add:</p><ul><li><em>consent APIs,</em></li><li><em>customer tables,</em></li><li><em>audit tables,</em></li><li><em>retention policies,</em></li><li><em>privacy controls,</em></li><li><em>screen journeys,</em></li><li><em>documents,</em></li><li><em>downstream systems.</em></li></ul><p>The difficult part of such a change is often not writing the code.</p><p>The difficult part is answering:</p><blockquote><strong>Have we identified everything that needs to change?</strong></blockquote><p>Traditional enterprise analysis depends heavily on SMEs, documentation and workshops to establish that confidence.</p><p>A connected enterprise knowledge model potentially changes that starting point.</p><p>It does not eliminate the SME.</p><p>In fact, I would argue that the SME becomes more valuable.</p><p>Instead of spending most of the time discovering dependencies, the SME can spend more time <strong>validating decisions, challenging assumptions and assessing business risk.</strong></p><p>That is an important distinction.</p><h3>Another example: a production incident</h3><p>Consider a simpler operational situation.</p><p><strong>Customers suddenly start reporting that Personal Loan applications are failing after PAN verification.</strong></p><p>Without connected context, investigation may begin independently across:</p><ul><li>Mobile logs</li><li>API Gateway logs</li><li>KYC service</li><li>External PAN provider</li><li>Customer service</li><li>Eligibility service</li><li>Messaging platform</li><li>LOS</li><li>Recent deployments</li></ul><p>Eventually the team discovers that a schema change in an event generated by the KYC service is causing the Eligibility service to fail.</p><p>Experienced operations teams are very good at this investigation.</p><p>But much of their time goes into reconstructing the dependency chain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*Xwb6PN9rJJiZb2N46Al-OA.png" /><figcaption>End-to-End Dependency Trace: From PAN Verification to Loan Application</figcaption></figure><p>If this relationship is already part of living enterprise knowledge, incident investigation starts several steps ahead.</p><p>Again, AI does not magically solve the incident.</p><p>But it begins with significantly better context.</p><h3>So what really changes?</h3><p>I would summarize the difference this way.</p><h3>A bank without MSOCK</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GT_U42wHgvd6eXtjn_A6tQ.png" /><figcaption>Without MSOCK: Enterprise Knowledge Exists in Silos and People Connect the Dots</figcaption></figure><h3>A bank with MSOCK</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TCHq8xauZdpKElzbxziYkA.png" /><figcaption>With MSOCK: Connected Enterprise Knowledge Becomes Shared Context for People and AI</figcaption></figure><p>That is perhaps the simplest mental model I have found for MSOCK.</p><h3>MSOCK versus RAG</h3><p>It is also useful not to confuse this with conventional enterprise RAG.</p><p>RAG is extremely useful when the problem is:</p><blockquote><strong>Find the information relevant to my question.</strong></blockquote><p>MSOCK, as I interpret it, is addressing a different question:</p><blockquote><strong>Understand how the things in my enterprise relate to each other.</strong></blockquote><p>For example, RAG might find a document that describes the Personal Loan eligibility rule.</p><p>Connected enterprise knowledge should help answer:</p><ul><li><em>Which journey uses this rule?</em></li><li><em>Which API implements it?</em></li><li><em>Which service executes it?</em></li><li><em>Which data objects support it?</em></li><li><em>Which applications depend on it?</em></li><li><em>Which controls apply?</em></li><li><em>Which tests prove it works?</em></li><li><em>What happens if I change it?</em></li></ul><p>These are related problems, but they are not the same problem.</p><h3>The larger opportunity</h3><p>For years, enterprises have invested heavily in creating individual sources of truth:</p><ul><li>API catalogues</li><li>Data catalogues</li><li>CMDBs (Configuration Management Database)</li><li>Architecture repositories</li><li>Code repositories</li><li>Process repositories</li><li>Knowledge bases</li><li>Observability platforms</li><li>Requirement management systems</li></ul><p>Each solves an important problem.</p><p>But an enterprise itself does not operate in these individual repositories.</p><ul><li>A customer journey crosses all of them.</li><li>A regulatory change crosses all of them.</li><li>A production incident crosses all of them.</li><li>A modernization program crosses all of them.</li></ul><p>That is why I find the idea of a <strong>connected knowledge layer across the enterprise</strong> compelling.</p><p>Not because it replaces these systems.</p><p>But because it potentially connects their meaning.</p><h3>My interpretation of MSOCK</h3><p>If I had to explain MSOCK to a banking technology team in one line, I would say:</p><blockquote><strong>Think of MSOCK as an attempt to build a living knowledge model of the bank’s technology estate, connecting business intent all the way down to the systems that implement and operate it.</strong></blockquote><p>In simplified terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CYPN1dcSQFPeclUoNMHRg.png" /><figcaption>From Customer Journey to Operations: The Connected Enterprise Knowledge Chain</figcaption></figure><p>And once those relationships are available to both humans and AI, some very interesting questions become possible:</p><blockquote>If I change this rule, what will break?</blockquote><blockquote>If I retire this API, who is actually using it?</blockquote><blockquote>Which applications are affected by this regulation?</blockquote><blockquote>Why is this customer journey failing?</blockquote><blockquote>Which business capabilities depend on this legacy platform?</blockquote><blockquote>What exactly should be regression-tested for this release?</blockquote><p>These are questions enterprise architects, developers, business analysts, QA teams and operations teams already ask every day.</p><p>The difference is that today, answering them often requires people to manually reconstruct knowledge that already exists somewhere inside the organization.</p><h3>A final thought</h3><p>I don’t think the interesting question around enterprise AI is going to be only:</p><blockquote><strong>How intelligent is the model?</strong></blockquote><p>The bigger question may become:</p><blockquote><strong>How well does the model understand the enterprise in which it is being asked to operate?</strong></blockquote><p>A very capable AI working with incomplete enterprise context can still make an incomplete decision.</p><p>That distinction becomes particularly important in banking, where systems are interconnected, changes have downstream consequences, regulatory obligations matter, and decisions need to be explainable.</p><p>This is why I find the direction behind MSOCK worth following.</p><p>The evolution from enterprise knowledge to <strong>connected, multidimensional and actionable enterprise knowledge</strong> addresses a problem that anyone who has worked on large banking transformations will immediately recognize.</p><p>Congratulations again to the <a href="https://purplefabric.ai/">Purple Fabric</a> team on the <a href="https://purplefabric.ai/msock/">MSOCK </a>release.</p><p>I will be watching with interest to see how this evolves from the concept into real enterprise implementations — particularly around change impact assessment, regulatory change, modernization and AI-assisted engineering.</p><p>Because ultimately, the real test of any enterprise AI platform is not how impressive the demonstration looks.</p><p>It is whether it can understand the complexity of the enterprise well enough to help people make <strong>better, safer and more informed decisions in production.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe95b904dc60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FlashAttention Explained Simply: Stop Moving So Much GPU Data]]></title>
            <link>https://patil-parag-oss.medium.com/flashattention-explained-simply-stop-moving-so-much-gpu-data-9bcb121aeb2d?source=rss-966c27f82db4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bcb121aeb2d</guid>
            <category><![CDATA[local-llm-optimization]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <dc:creator><![CDATA[Parag Patil]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 09:39:23 GMT</pubDate>
            <atom:updated>2026-09-15T08:53:59.088Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3 of the series: </em><strong><em>Stop Wasting Your GPU — A Developer’s Guide to Local LLM Optimization</em></strong></p><p>In <a href="https://medium.com/@patil-parag-oss/bf16-vs-fp16-why-smaller-numbers-make-local-llms-faster-5110971e0a69">Part 2</a>, I looked at BF16 and FP16 through one simple mental model:</p><blockquote><strong>Make the numbers smaller.</strong></blockquote><p>That helped me understand how reducing precision can create more GPU headroom.</p><p>But after reducing tensor sizes, I ran into another question:</p><blockquote><strong>If modern GPUs are so incredibly fast at matrix multiplication, why does attention still become expensive as the prompt gets longer?</strong></blockquote><p>The answer changed the way I thought about GPU optimization.</p><p>Sometimes the problem isn’t how much computation the GPU performs.</p><p>Sometimes the problem is <strong>how much data we make the GPU move around while performing that computation</strong>.</p><p>And that is the problem FlashAttention helps solve.</p><h3>The Problem Became Obvious When My Prompts Got Longer</h3><p>Short prompts rarely exposed the issue clearly.</p><p>Something like:</p><blockquote><strong>User: “What is a home loan?”</strong></blockquote><p>isn’t particularly demanding for a modern local LLM.</p><p>But my conversational AI workload looked more like this:</p><pre>System instructions         500 tokens<br>Conversation history      2,000 tokens<br>Retrieved RAG context     4,000 tokens<br>Customer information        500 tokens<br>Current question             80 tokens<br>--------------------------------------<br>Total                     7,080 tokens</pre><p>And the next request could easily be larger.</p><p>At that point, I wasn’t just asking the model to process a sentence.</p><p>I was asking it to understand relationships across thousands of tokens.</p><p>That is where attention enters the picture.</p><h3>First, What Is Attention Actually Doing?</h3><p>I don’t find it useful to start with a research-paper definition.</p><p>As a developer, I think about attention like this:</p><p>For every token being processed, the model needs a way to determine which other tokens are relevant to it.</p><p>Imagine the sentence:</p><p>“The customer applied for a home loan because <strong>he</strong> wanted to purchase an apartment.”</p><p>When processing “he”, the model needs to understand that it is related to “customer”.</p><p>At scale, the model is doing this across many tokens and multiple attention heads.</p><p>Transformer attention is commonly represented as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*RMnlBCOhyWfKWvLWKXo6vg.png" /></figure><p>When I first saw this equation, it didn’t help me much.</p><p>The developer-friendly version is:</p><p><strong><em>Q = What am I looking for?<br> <br> K = What information does each token represent?<br> <br> V = What information should I retrieve from it?</em></strong></p><p>Then:</p><p><strong><em>Q compares with K<br> ↓<br> Attention scores<br> ↓<br> Softmax<br> ↓<br> Use scores to combine V<br> ↓<br> Attention output</em></strong></p><p>Or even more simply:</p><blockquote><strong>Q asks. K matches. V provides the information.</strong></blockquote><p>That is enough context to understand why FlashAttention matters.</p><h3>The Expensive Part Is Not Just the Math</h3><p>Suppose my model has a sequence length of:</p><p><strong><em>4096 tokens</em></strong></p><p>A simplified attention-score matrix for one attention head can contain:</p><pre>4096 × 4096 = 16,777,216 values</pre><p>Now imagine multiple attention heads.</p><p>For example: <strong><em>32 heads</em></strong></p><p>Conceptually, the score tensors can represent hundreds of millions of values.</p><p>If those values are FP16: <strong><em>2 bytes per value</em></strong></p><p>the raw score data alone can become very large.</p><p>And that is before thinking about:</p><p><strong>· multiple Transformer layers <br>· softmax intermediates<br>· masks<br>· other activations<br>· KV cache<br>· model weights<br>· and runtime buffers</strong></p><p>But memory capacity is only part of the story. The GPU also has to move this information around.</p><h3>How I Initially Imagined Attention</h3><p>My first mental picture looked something like this:</p><pre>Q + K<br>   ↓<br>Q × Kᵀ<br>   ↓<br>Large attention matrix<br>   ↓<br>Softmax<br>   ↓<br>Multiply by V<br>   ↓<br>Output</pre><p>Nothing obviously wrong with that.</p><p>But then I started thinking about where each intermediate result lives.</p><p>A more realistic mental picture is:</p><pre>Q + K<br>   ↓<br>GPU computes QKᵀ<br>   ↓<br>Write intermediate results to GPU memory<br>   ↓<br>Read those results back<br>   ↓<br>Run Softmax<br>   ↓<br>Write intermediate results again<br>   ↓<br>Read them again<br>   ↓<br>Multiply with V<br>   ↓<br>Output</pre><p>That is the part I had been missing.</p><p>The GPU isn’t only calculating.</p><p>It is constantly:</p><p><strong>Compute<br>↕<br>Memory</strong></p><h3>GPU Compute Is Fast. Memory Movement Is Expensive.</h3><p>Modern GPUs contain an enormous amount of compute capability.</p><p>For Transformer workloads, Tensor Cores can perform matrix operations at extraordinary rates.</p><p>But the compute units can’t calculate on data they don’t have.</p><p>The data often needs to travel from GPU high-bandwidth memory — HBM or VRAM — into faster memory closer to the compute units.</p><p>A very simplified GPU memory hierarchy looks like:</p><pre>        GPU Compute Units<br>        / Tensor Cores<br>               │<br>               ▼<br>       Registers / SRAM<br>       Very fast, small<br>               │<br>               ▼<br>         L2 Cache<br>               │<br>               ▼<br>          HBM / VRAM<br>       Large, but farther</pre><p>The exact hardware is much more sophisticated than this, but this mental model is enough.</p><p>Moving something from:</p><blockquote><strong>HBM<br> ↓<br> Compute<br> ↓<br> HBM<br> ↓<br> Compute</strong></blockquote><p>repeatedly has a cost.</p><p>That cost is often referred to as memory IO or memory traffic. And this is where <strong>FlashAttention </strong>clicked for me.</p><h3>FlashAttention Is an IO Optimization</h3><p>The easiest mistake is to think:</p><p>FlashAttention avoids the expensive attention calculation.</p><p>It doesn’t.</p><p>Attention still requires a significant amount of computation.</p><p>For normal full attention, sequence-length-related computation is still fundamentally quadratic.</p><p>FlashAttention changes how that computation is organized on the GPU.</p><p>Instead of materializing the entire large attention matrix in HBM, it processes attention in smaller blocks, or tiles.</p><p>Conceptually:</p><p>Traditional Approach:</p><pre><br>Q × Kᵀ<br>   ↓<br>Huge intermediate matrix<br>   ↓<br>HBM<br>   ↓<br>Softmax<br>   ↓<br>HBM<br>   ↓<br>× V</pre><p>FlashAttention thinks more like:</p><pre>Take Q block<br>Take K block<br>Take V block<br>      ↓<br>Process them close to GPU compute<br>      ↓<br>Update result<br>      ↓<br>Move to next block</pre><p>So I stopped thinking:</p><p>FlashAttention performs less attention.</p><p>And started thinking:</p><blockquote><strong>FlashAttention performs attention while avoiding unnecessary trips to GPU memory.</strong></blockquote><p>That is the core idea.</p><h3>My Warehouse Analogy</h3><p>This was the analogy that made it stick for me.</p><p>Imagine I am assembling something in a workshop.</p><p>All the components are stored in a large warehouse across the building.</p><p>A bad workflow looks like:</p><blockquote><strong>Get component A from warehouse<br> ↓<br> Work on it<br> ↓<br> Return result to warehouse</strong></blockquote><blockquote><strong>Get result back<br> ↓<br> Combine with component B<br> ↓<br> Return result to warehouse</strong></blockquote><blockquote><strong>Get result back again<br> ↓<br> Perform next operation</strong></blockquote><p>The calculations may be fast.</p><p>But I spend a lot of time walking between the workshop and the warehouse.</p><p>Now imagine instead:</p><blockquote><strong>Bring a useful batch of components into the workshop <br> ↓<br>Perform several related operations locally <br> ↓<br>Return only the required result</strong></blockquote><p>That is roughly how I think about FlashAttention.</p><p>The warehouse is:</p><p><strong><em>GPU HBM / VRAM</em></strong></p><p>The workshop is:</p><p><strong><em>fast on-chip GPU memory</em></strong></p><p>And FlashAttention tries to keep useful work inside the workshop longer.</p><h3>Why Does Tiling Help?</h3><p>Suppose I have:</p><p><strong>Q<br>K<br>V</strong></p><p>for a long sequence.</p><p>Instead of processing everything as one giant intermediate structure, FlashAttention divides the problem into smaller pieces.</p><p>Conceptually:</p><p>Q<br> ┌── ┐<br> │ Q1 │<br> ├─ ─┤<br> │ Q2 │<br> ├── ┤<br> │ Q3 │<br> └── ┘</p><p>and similarly:</p><p>K V <br> ┌─ ─┐ ┌─ ─┐<br> │ K1 │ │ V1 │<br> ├─ ─┤ ├─ ─┤<br> │ K2 │ │ V2 │<br> ├─ ─┤ ├─ ─┤<br> │ K3 │ │ V3 │<br> └─ ─┘ └─ ─┘</p><p>Then it processes combinations of these blocks using fast on-chip memory.</p><p>The actual algorithm is more sophisticated because softmax normally depends on the entire row of attention scores.</p><p>FlashAttention uses an online form of softmax that allows those results to be accumulated correctly across blocks.</p><p>As a developer, I don’t need to implement that algorithm myself.</p><p>The important thing for my mental model is:</p><blockquote><strong>Tiling allows the attention calculation to be reorganized so that a giant attention-score matrix does not need to live in HBM as a normal intermediate.</strong></blockquote><h3>So Is FlashAttention Approximate?</h3><p>This was another question I had.</p><blockquote><strong>If we’re processing things in blocks, are we trading accuracy for speed?</strong></blockquote><p>For standard FlashAttention, the answer is no in the algorithmic sense.</p><p><strong><em>It is designed as exact attention, not an approximation technique that simply drops token relationships.</em></strong></p><p>The execution order is different, so small floating-point differences can occur compared with another backend, just as they can between different GPU kernels.</p><p>But conceptually we are still calculating the same attention operation.</p><p>So:</p><p><strong>Normal Attention</strong> → Same attention semantics<br><strong>FlashAttention</strong> → Same attention semantics executed differently</p><p>This distinction matters because there are other techniques that actually change the attention mechanism to reduce complexity.</p><p>FlashAttention is primarily about executing full attention more efficiently.</p><h3>What Changes in PyTorch?</h3><p>Years ago, developers often needed special libraries or explicit FlashAttention integration.</p><p>Modern PyTorch makes the situation much simpler.</p><p>Rather than manually implementing:</p><pre>scores = query @ key.transpose(-2, -1)<br>scores = scores / math.sqrt(head_dim)<br><br>attention = torch.softmax(scores, dim=-1)<br><br>output = attention @ value</pre><p>I can use PyTorch’s scaled dot-product attention API:</p><pre>import torch.nn.functional as F<br><br>output = F.scaled_dot_product_attention(<br>    query,<br>    key,<br>    value,<br>    is_causal=True,<br>)</pre><p>For supported CUDA workloads, PyTorch can select an optimized attention implementation automatically.</p><p>That may include a FlashAttention backend.</p><p>This changes an important developer assumption.</p><p>I should not automatically conclude:</p><p>I didn’t install a package called <strong><em>flash-attn</em></strong> therefore <strong><em>I’m not using FlashAttention</em></strong></p><p>The framework may already be dispatching the operation to an optimized backend.</p><p>That is something I verify rather than guess.</p><h3>What About vLLM?</h3><p>This matters even more if I’m running my conversational AI through an inference engine such as vLLM.</p><p>With raw PyTorch, I think about:</p><p>Which attention implementation<br> does this operation use?</p><p>With vLLM, a lot of that backend selection and serving optimization happens inside the inference engine.</p><p>So my job changes.</p><p>I’m less interested in implementing FlashAttention manually.</p><p>I’m more interested in confirming:</p><blockquote><strong>Which attention backend is active?<br>Is it supported by my GPU?<br>Is it compatible with my model?<br>Does it improve my workload?<br>What happens to TTFT and VRAM?</strong></blockquote><h3>Where I Expect FlashAttention to Help Most</h3><p>Now consider two requests.<br><strong><em>Request A</em></strong><br>Prompt length: 300 tokens<br><strong><em>Request B</em></strong><br>Prompt length: 8,000 tokens<br><strong><em>FlashAttention may help both.<br></em></strong>But I expect the optimization to become much more interesting as sequence lengths grow.</p><p>Why?</p><p>Because attention workload grows very rapidly with sequence length.<br>Conceptually:<br>1K context<br> ↓<br><strong>attention work</strong><br> <br>4K context<br> ↓<br><strong>much more attention work</strong><br><br>8K context<br> ↓<br><strong>even more</strong><br> <br>16K context<br> ↓<br><strong>attention efficiency becomes critical</strong><br>This is why FlashAttention is particularly relevant to applications involving:<br>· long conversation histories<br>· RAG with substantial retrieved context<br>· document conversations<br>· large system prompts<br>· agent traces<br>· tool outputs<br>· long-context coding assistants.</p><h3>Conversational AI Makes This Easy to Miss</h3><p>There is a trap here.</p><p>A developer tests:</p><blockquote><strong>“Hello, explain home loans.”</strong></blockquote><p>Everything is fast.</p><p>Then the production application sends:</p><p><strong>System Prompt + 10 previous turns + Customer profile + 4 retrieved documents + Agent instructions +Current question</strong></p><p>The model is technically the same.</p><p>The GPU workload is not.</p><p>That is why I now include <strong>prompt length</strong> as a first-class dimension in my GPU benchmarks.</p><h3>Prefill vs Decode: Where FlashAttention Fits</h3><p>Another concept that helped me is separating LLM inference into two phases.</p><p><strong>Phase 1: Prefill</strong><br>The model processes the input prompt.<br>For example:<br>7,000 input tokens<br> ↓<br>Transformer<br> ↓<br>Context understood</p><p>The whole prompt needs to pass through the Transformer.<br>This is where long-sequence attention can become expensive.<br><strong>FlashAttention is especially relevant here.</strong></p><p><strong>Phase 2: Decode<br></strong>Then the model generates:<br>Token 1<br>Token 2<br>Token 3<br>…<br>one token at a time.<br>With a KV cache, previously calculated K/V values are reused.<br>That means decode has a different computational profile.<br>So I think about FlashAttention primarily as:</p><blockquote><strong>A major optimization for large attention workloads, especially prompt processing, rather than a magic fix for every part of token generation.</strong></blockquote><p>We’ll get much deeper into decode when we reach KV Cache in Part 5.</p><h3>Does FlashAttention Reduce VRAM?</h3><p>Yes, but I phrase this carefully.</p><p>Traditional attention can require large intermediate attention tensors.</p><p>FlashAttention avoids materializing some of those large intermediates in HBM.</p><p>So:</p><p><strong>Attention intermediate memory<br> ↓ significantly</strong></p><p>But, just like BF16 from <a href="https://medium.com/@patil-parag-oss/bf16-vs-fp16-why-smaller-numbers-make-local-llms-faster-5110971e0a69">Part 2</a>:</p><p><strong>Entire application VRAM ≠ automatically reduced by the same percentage</strong></p><p>The GPU is still storing:</p><p><strong><em>Model weights<br>KV Cache<br>Other activations<br>CUDA/runtime allocations<br>Execution workspace<br>Other application tensors</em></strong></p><p>So the correct mental model is:</p><p><strong><em>Attention memory pressure ↓ <br>Attention HBM traffic ↓ <br>Total application VRAM ↓ potentially</em></strong></p><p>rather than:</p><p><strong><em>FlashAttention → Entire GPU memory becomes tiny</em></strong></p><h3>FlashAttention Does Not Give Me a Longer Context Window for Free</h3><p>This is another subtle point.</p><p>If FlashAttention reduces attention-related memory usage, it can make longer contexts more practical.</p><p>But maximum context length is still affected by:</p><p><strong><em>Model architecture + Position encoding limits + KV Cache + Available VRAM + Inference engine + Batch size + Concurrent users</em></strong></p><p>So I wouldn’t say:</p><p><strong><em>Enable FlashAttention and your 4K model becomes a 32K model.</em></strong></p><p>That’s not how it works.</p><p>A better statement is:</p><blockquote><strong>FlashAttention can reduce one of the major costs associated with processing long sequences.</strong></blockquote><h3>A Simple Before-and-After Mental Model</h3><p>Without efficient attention:</p><p><strong>Long Prompt<br> ↓<br>Q / K / V<br> ↓<br>QKᵀ<br> ↓<br>Large intermediate<br> ↓<br>HBM<br> ↓<br>Softmax<br> ↓<br>HBM<br> ↓<br>× V<br> ↓<br>Output</strong></p><p>With FlashAttention:</p><p><strong>Long Prompt</strong><br> ↓<br><strong>Q / K / V</strong><br> ↓<br><strong>Attention in tiles <br></strong><em>Q block<br>K block<br>V block</em><strong><em><br></em>Online Softmax<br>Accumulate Output</strong><br><strong> ↓<br> Output</strong></p><blockquote>Same useful attention work but less unnecessary HBM traffic</blockquote><h3>What I Would Actually Benchmark</h3><p>I wouldn’t test FlashAttention using only one prompt size.</p><p>I’d create something closer to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*H2WMsj_5-NYRORAA9qsG-w.png" /></figure><p>Then compare the attention backends available for my setup.</p><p>I would measure:</p><h3>TTFT</h3><p>Because attention during prefill has a direct relationship with how quickly long prompts can be processed.</p><h3>Peak VRAM</h3><p>To see whether the optimized backend reduces attention-related memory pressure.</p><h3>Prompt tokens/sec</h3><p>How quickly is the input being processed?</p><p>This is particularly useful for FlashAttention testing.</p><h3>End-to-end latency</h3><p>Because users ultimately care about the whole request.</p><h3>Maximum stable concurrency</h3><p>A memory saving isn’t very useful if it doesn’t help the system support more practical workload.</p><h3>I Would Also Test Short Prompts</h3><p>This may sound strange.</p><p>If FlashAttention matters most for long contexts, why benchmark short prompts?</p><p>Because optimization isn’t free from context.</p><p>For my actual application, maybe:</p><blockquote><strong>90% of prompts &lt; 1K tokens<br>10% of prompts &gt; 8K tokens</strong></blockquote><p>Or perhaps the opposite.</p><p>The aggregate production benefit depends on the real request distribution.</p><p>So I prefer:</p><p><strong><em>Real workload<br>→ benchmark<br>→ decision</em></strong></p><p>over:</p><p><strong><em>Technology sounds fast<br>→ enable<br>→ assume success</em></strong></p><h3>What I Would Not Do</h3><p>I wouldn’t write:</p><blockquote><strong>“FlashAttention makes LLM inference 3× faster.”</strong></blockquote><p>Without specifying:</p><p><strong><em>Which model?<br>Which GPU?<br>Which sequence length?<br>Which batch size?<br>Which precision?<br>Which attention backend was the baseline?<br>Training or inference?<br>Prefill or decode?</em></strong></p><p>A performance number without workload context isn’t particularly useful.</p><p>This is one reason I’ve intentionally avoided presenting a magical percentage improvement in this article.</p><p>My objective isn’t to prove that FlashAttention is always faster.</p><p>My objective is to understand:</p><blockquote><strong>What bottleneck is it designed to remove?</strong></blockquote><p>Once I know that, I can benchmark whether that bottleneck exists in my system.</p><h3>My Developer Mental Model</h3><p>For BF16, I had:</p><blockquote><strong>Make the numbers smaller.</strong></blockquote><p>For FlashAttention, I now use:</p><blockquote><strong>Move less data.</strong></blockquote><p>More specifically:</p><p><strong>Long sequence<br> ↓<br>Large attention workload<br> ↓<br>Don’t materialize huge intermediates unnecessarily<br> ↓<br>Process attention in GPU-friendly tiles<br> ↓<br>Reduce HBM traffic<br> ↓<br>Use GPU compute more efficiently</strong></p><p>That’s enough for me to reason about the optimization without needing to become a CUDA kernel developer.</p><h3>How It Fits With Part 2</h3><p>Now the optimization stack is starting to make more sense.</p><h3>BF16 / FP16</h3><p>Make each floating-point value smaller.</p><h3>FlashAttention</h3><p>Avoid moving unnecessary intermediate attention data.</p><p>Together:</p><p><strong><em>Smaller data + Less movement<br> ↓<br>More efficient GPU memory usage</em></strong></p><p>But there is still another type of waste.</p><p>Even with smaller tensors and efficient attention, PyTorch can execute thousands of model operations through its normal eager execution path.</p><p>That raises the next question:</p><blockquote>Can we optimize <strong>how the whole computation graph is executed</strong>, not just attention?</blockquote><p>That’s where torch.compile comes in.</p><h3>The One Thing I Want You to Remember</h3><p>If you remember only one line from this article:</p><blockquote><strong>FlashAttention doesn’t primarily make attention faster by doing less attention. It makes attention more GPU-efficient by moving less data.</strong></blockquote><p>Or in the mental model for this series:</p><p>BF16 / FP16 → <strong>Make the numbers smaller.</strong><br>FlashAttention →<strong> Move less data.</strong></p><p>We’re now removing two different kinds of GPU waste:</p><p><strong>Too much tensor memory<br> ↓<br>BF16 / FP16</strong></p><p><strong>Too much attention memory traffic<br> ↓<br>FlashAttention</strong></p><p>The next optimization tackles a completely different problem.</p><h3>What Comes Next?</h3><p>Imagine our local LLM now has</p><p>BF16 / FP16 ✔<br>Efficient attention ✔</p><p>The model still contains thousands of operations:</p><p><strong><em>LayerNorm<br>Linear<br>RoPE<br>Attention<br>Residual Add<br>MLP<br>SiLU<br>More Linear operations<br>…</em></strong></p><p>In normal PyTorch eager execution, those operations are dispatched dynamically.</p><p>Can PyTorch look at that larger execution graph and generate a better GPU execution plan?</p><p>That’s what I’ll explore next.</p><h3>Part 4 — What Does torch.compile() Actually Do to Your LLM?</h3><p>The mental model will be:</p><blockquote><strong><em>torch.compile</em> → Execute operations smarter.</strong></blockquote><p>We’ll look at:</p><ul><li>what PyTorch eager execution actually means,</li><li>what a GPU kernel launch is,</li><li>why thousands of small operations create overhead,</li><li>what graph capture and kernel fusion mean,</li><li>what torch.compile() changes,</li><li>why the first compiled request can be misleadingly slow,</li><li>when dynamic shapes can hurt compilation benefits,</li><li>and how I would benchmark it in a local conversational AI workload.</li></ul><p><em>This is Part 3 of </em><strong><em>Stop Wasting Your GPU: A Developer’s Guide to Local LLM Optimization</em></strong><em>.</em></p><p><strong>← Previous: </strong><a href="https://medium.com/@patil-parag-oss/bf16-vs-fp16-why-smaller-numbers-make-local-llms-faster-5110971e0a69"><strong>Part 2 — BF16 vs FP16: Why Smaller Numbers Make Local LLMs Faster</strong></a></p><p><strong>Next → </strong><a href="https://medium.com/@patil-parag-oss/what-does-torch-compile-actually-do-to-your-llm-4e3766cd18c4?sharedUserId=patil-parag-oss"><strong>Part 4 — What Does </strong></a><a href="https://medium.com/@patil-parag-oss/what-does-torch-compile-actually-do-to-your-llm-4e3766cd18c4?sharedUserId=patil-parag-oss"><strong>torch.compile() Actually Do to Your LLM?</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bcb121aeb2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BF16 vs FP16: Why Smaller Numbers Make Local LLMs Faster]]></title>
            <link>https://patil-parag-oss.medium.com/bf16-vs-fp16-why-smaller-numbers-make-local-llms-faster-5110971e0a69?source=rss-966c27f82db4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5110971e0a69</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpu-optimization]]></category>
            <dc:creator><![CDATA[Parag Patil]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 09:45:58 GMT</pubDate>
            <atom:updated>2026-09-15T08:56:26.296Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2 of the series: </em><strong><em>Stop Wasting Your GPU — A Developer’s Guide to Local LLM Optimization</em></strong></p><p>In <a href="https://medium.com/@patil-parag-oss/your-llm-is-running-on-a-gpu-but-is-it-running-efficiently-2382a10eae9f">Part 1</a>, I introduced the mental model I use when thinking about GPU optimization for local LLMs:</p><blockquote><strong>BF16 / FP16 </strong>→ Make the numbers smaller<br><strong>FlashAttention</strong>→ Move less data<br><strong>torch.compile</strong>→ Execute operations smarter<br><strong>KV Cache</strong>→ Don’t calculate the past again<br><strong>Batching / Bucketing</strong>→ Keep the GPU busy</blockquote><p>In this article, I want to start with the simplest one:</p><blockquote><strong>BF16 / FP16 → </strong>Make the numbers smaller.</blockquote><p>At first, reduced precision sounded like one of those topics I needed to understand at the floating-point-bit level before I could use it.</p><p>Fortunately, from an LLM developer’s perspective, the core idea is much simpler.</p><p>My model is full of numbers.</p><p>Those numbers consume GPU memory.</p><p>If I can represent many of those numbers using 16 bits instead of 32 bits, I can reduce memory consumption and let the GPU process them more efficiently.</p><p>But that immediately raises a few questions:</p><ul><li>What exactly are FP32, FP16, and BF16?</li><li>Why are both FP16 and BF16 16-bit but behave differently?</li><li>Which one should I use for a local LLM?</li><li>Does moving to 16-bit precision reduce model quality?</li><li>Does a 20 GB FP32 model really become a 10 GB model?</li><li>What should I actually benchmark?</li></ul><p>Let’s break it down.</p><h3>First, What Is Precision?</h3><p>Consider a number inside the model: <strong><em>0.137842371</em></strong></p><p>A computer needs a binary representation to store that value.</p><p>The number of bits available affects:</p><ul><li>how large or small a number can be</li><li>how precisely it can be represented</li><li>how much memory it consumes</li><li>and how efficiently certain GPU hardware can process it</li></ul><p>A simplified comparison is:</p><p><strong>FP32 -&gt; </strong>32 bits per value<br><strong>FP16 -&gt; </strong>16 bits per value<br><strong>BF16 -&gt; 1</strong>6 bits per value</p><p>So, at the highest level:</p><pre>FP32<br>████████████████████████████████<br>FP16 / BF16<br>████████████████</pre><p>Half the number of bits.</p><p>And that leads to my first mental model:</p><blockquote><strong>If I can safely use 16-bit values instead of 32-bit values, I can move and store less data.</strong></blockquote><h3>Why Does This Matter So Much for LLMs?</h3><p>Because an LLM doesn’t contain a few thousand numbers.</p><p>It contains billions.</p><p>Take a simplified 7-billion-parameter model.</p><p>If every parameter were stored in FP32:</p><blockquote><strong>7 billion parameters × 4 bytes = 28 GB</strong></blockquote><p>If those same parameters were stored in BF16 or FP16:</p><blockquote><strong>7 billion parameters × 2bytes = 14 GB</strong></blockquote><p>That is only the weight-storage calculation, but it immediately shows why precision matters.</p><p>From a developer perspective:</p><blockquote><strong>FP32 weights<br> ↓<br>More VRAM</strong></blockquote><blockquote><strong>BF16 / FP16 weights<br> ↓<br>Less VRAM</strong></blockquote><p>This can be the difference between:</p><blockquote><strong>“The model does not fit on this GPU.”</strong></blockquote><p>and:</p><blockquote><strong>“The model fits, and I still have room for context and KV cache.”</strong></blockquote><h3>But Model Weights Are Not the Whole Story</h3><p>This is an important point.</p><p>If my FP32 weights consume 28 GB, switching to BF16 does <strong>not</strong> mean my entire application will automatically use exactly 14 GB.</p><p>GPU memory is also used by:</p><p><strong>Model weights + Input tensors + Intermediate activations + Attention workspace + KV Cache + CUDA/runtime allocations + Framework overhead</strong></p><p>Think of VRAM as two broad categories:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTTLuZ5eDoWrb4swJTIYyA.png" /></figure><p><strong>Disclosure:</strong> I used AI assistance to draft &amp; create the image</p><p>FP32 → BF16 primarily shrinks the <strong>first category</strong>.</p><p>So I think about the optimization as:</p><blockquote><strong>Weight memory<br>↓ significantly</strong></blockquote><blockquote><strong>Many floating-point tensors<br>↓ often substantially</strong></blockquote><blockquote><strong>Total application VRAM<br>↓ significantly</strong></blockquote><p>rather than:</p><blockquote><strong><em>Everything becomes exactly 50% smaller</em></strong></blockquote><p>That distinction becomes important when benchmarking a real system.</p><h3>A Conversational AI Example</h3><p>Let’s go back to the local conversational AI workload from Part 1.</p><p>A user asks:</p><blockquote><strong>“Based on our previous discussions and the lending policy, why was my application rejected?”</strong></blockquote><p>The application builds:</p><pre>System Prompt              500 tokens<br>Conversation History     2,500 tokens<br>RAG Context              4,000 tokens<br>Customer Context           800 tokens<br>Question                    100 tokens<br>-------------------------------------<br>Total                    7,900 tokens</pre><p>Those tokens are transformed into tensors and passed through the LLM.</p><p>During inference, the GPU must keep track of:</p><p><strong><em>Model weights + Input representations + Intermediate tensors + Attention states + KV Cache</em></strong></p><p>Now imagine 20 simultaneous conversations.</p><p>The model weights are shared.</p><p>But each active conversation introduces additional runtime memory.</p><p>That means VRAM isn’t only deciding whether my model fits.</p><p>It also helps determine:</p><blockquote><strong>How many users can I serve at the same time?</strong></blockquote><h3>So Why Not Just Use FP16 Everywhere?</h3><p>This is where BF16 enters the picture.</p><p>FP16 and BF16 both use 16 bits.</p><p>But they allocate those bits differently.</p><p>A simplified representation is:</p><p><strong>FP32</strong><br>1 sign bit<br>8 exponent bits<br>23 fraction bits</p><p><strong>FP16</strong><br>1 sign bit<br>5 exponent bits<br>10 fraction bits</p><p><strong>BF16</strong><br>1 sign bit<br>8 exponent bits<br>7 fraction bits</p><p>This is the key difference.</p><p>FP16 provides more fraction precision.</p><p>BF16 provides a much larger numeric range because it keeps the same exponent width as FP32.</p><h3>The Developer-Friendly Version</h3><p>The way I remember it is:</p><p><strong>FP16 </strong>→ More precision within a smaller numeric range<br><strong>BF16</strong> → Less precision but much wider numeric range</p><p>For neural networks, that wider range is often very useful.</p><p>Intermediate values can sometimes become very large or very small.</p><p>FP16 has a greater risk of numerical overflow or underflow.</p><p>BF16 tends to be more tolerant because its numeric range is much closer to FP32.</p><p>So my mental model becomes:</p><blockquote><strong>BF16 sacrifices some precision to retain range.</strong></blockquote><p>And for many modern neural-network workloads, that trade-off works very well.</p><h3>Why BF16 Is Often My First Choice</h3><p>If the GPU supports BF16 efficiently and the model supports it, I generally start my evaluation with BF16.</p><p>Not because BF16 is universally faster.</p><p>But because it often gives me a practical combination of:</p><blockquote><strong>Lower memory than FP32 <br>Good numerical range <br>Tensor Core support on modern GPUs <br>Less numerical sensitivity than FP16</strong></blockquote><p>That makes it attractive for LLM inference.</p><p>But I don’t treat: <strong>BF16 &gt; FP16</strong></p><p>as a universal rule.</p><p>The actual choice depends on:</p><ul><li>GPU architecture</li><li>model implementation</li><li>inference framework</li><li>supported kernels</li><li>and model behaviour</li></ul><p>Which is why I benchmark rather than assume.</p><h3>A Simplified Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNpfpdHUDWkAUpZuJHZjYA.png" /></figure><p>The important point is that both FP16 and BF16 reduce memory compared with FP32.</p><p>But they make different trade-offs.</p><h3>What Changes in the Code?</h3><p>Suppose I originally load my model using FP32:</p><pre>import torch<br>model = load_model()<br>model = model.to(<br>    device=&quot;cuda&quot;,<br>    dtype=torch.float32<br>)</pre><p>A BF16 configuration could look conceptually like:</p><pre>model = model.to(<br>    device=&quot;cuda&quot;,<br>    dtype=torch.bfloat16<br>)</pre><p>Or, when loading a Hugging Face model:</p><pre>from transformers import AutoModelForCausalLM<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_path,<br>    torch_dtype=torch.bfloat16,<br>    device_map=&quot;cuda&quot;<br>)</pre><p>For FP16:</p><pre>model = AutoModelForCausalLM.from_pretrained(<br>    model_path,<br>    torch_dtype=torch.float16,<br>    device_map=&quot;cuda&quot;<br>)</pre><p>The code change can look deceptively small.</p><p>But underneath it, we have changed the datatype used by billions of model parameters and many runtime operations.</p><h3>What Does the GPU Gain?</h3><p>I think about the benefits in three buckets.</p><h3>1. Less Memory</h3><p>This is the most obvious one.</p><blockquote><strong>32-bit tensor<br> ↓<br>16-bit tensor<br> ↓<br>Approximately half the storage per element</strong></blockquote><p>Less VRAM consumption means more room for:</p><blockquote><strong>Longer context<br>Larger batches<br>Larger KV Cache<br>More concurrent requests</strong></blockquote><h3>2. Less Memory Bandwidth</h3><p>The GPU also needs to read the model weights and tensors.</p><p>If each value is smaller, less data needs to travel through GPU memory.</p><p>Conceptually:</p><pre>FP32<br>████████████████████████████████<br>        ↓<br>GPU<br><br>BF16<br>████████████████<br>        ↓<br>GPU</pre><p>This can matter because LLM inference is often not limited purely by arithmetic.</p><p>Memory bandwidth can become a major factor.</p><h3>3. Better Use of Specialized GPU Hardware</h3><p>Modern NVIDIA GPUs contain Tensor Cores designed to accelerate lower-precision matrix operations.</p><p>Transformer inference is dominated by matrix multiplication.</p><p>So using a datatype supported efficiently by the GPU can result in better computational throughput.</p><p>This is another reason I don’t think about BF16 only as:</p><blockquote><strong>“Saving memory.”</strong></blockquote><p>It can also change how efficiently the GPU performs the work.</p><h3>What Does BF16 Not Solve?</h3><p>This is where it is important not to mix up the five optimizations.</p><p>BF16 can make tensors smaller.</p><p>But it does not automatically solve:</p><blockquote>Large attention memory traffic<strong> → FlashAttention problem<br></strong>PyTorch execution overhead <strong>→ torch.compile problem<br></strong>Repeated decoder calculations <strong>→ KV Cache problem<br></strong>Idle GPU capacity<strong> → Batching problem</strong></blockquote><p>So if I enable BF16 and still see poor GPU utilization, it doesn’t mean BF16 failed.</p><p>It may simply mean my actual bottleneck is somewhere else.</p><h3>Think About It as Creating GPU Headroom</h3><p>This is how I prefer to visualize BF16.</p><p>Suppose my GPU has: <strong><em>24 GB VRAM</em></strong></p><p>Before optimization:</p><pre>Model weights        16 GB<br>KV Cache              4 GB<br>Runtime tensors       2 GB<br>Other allocations     1 GB<br>---------------------------<br>Used                  23 GB<br>Free                   1 GB</pre><p>There is almost no room to increase:</p><blockquote><strong>Context<br>Batch size<br>Concurrency</strong></blockquote><p>Now imagine reduced precision brings model/runtime memory down enough to produce:</p><pre>Model weights         9 GB<br>KV Cache              4 GB<br>Runtime tensors       2 GB<br>Other allocations     1 GB<br>---------------------------<br>Used                  16 GB<br>Free                   8 GB</pre><p>These numbers are purely illustrative.</p><p>But this is exactly how I think about the objective.</p><p>The optimization did not simply:</p><blockquote><strong>Reduce a number on </strong><strong><em>nvidia-smi</em>.</strong></blockquote><p>It created <strong>headroom</strong>.</p><p>That headroom can potentially be converted into:</p><blockquote>More concurrent conversations<br><strong>OR</strong><br>Longer context<br><strong>OR</strong><br>Larger batch size<br><strong>OR</strong><br>A larger model</blockquote><p>And that is much more useful.</p><h3>Precision Is Also a Quality Decision</h3><p>There is another side to reduced precision.</p><p>We are changing how numbers are represented.</p><p>So I don’t consider the optimization complete until I validate model behaviour.</p><p>For a conversational AI workload, I would test representative prompts such as:</p><blockquote><strong>Simple Q&amp;A<br>RAG-based answers<br>Long conversation history<br>Structured JSON responses<br>Numerical questions<br>Policy interpretation<br>Tool-calling output</strong></blockquote><p>And compare:</p><blockquote>FP32 response<br><strong>vs</strong><br>BF16 response<br><strong>vs</strong><br>FP16 response</blockquote><p>Not necessarily expecting identical token-for-token answers.</p><p>What matters is whether:</p><blockquote><strong>Accuracy<br>Instruction following<br>Response format<br>Reasoning quality<br>Business outcome</strong></blockquote><p>remain within an acceptable range.</p><h3>Do I Need FP32 for Everything?</h3><p>Not necessarily.</p><p>Modern neural-network inference often uses mixed precision.</p><p>That means different operations can use different datatypes where appropriate.</p><p>Conceptually:</p><p>Most matrix operations → <strong>BF16 / FP16</strong><br>Some numerically sensitive work → <strong>Higher precision when required</strong></p><p>Frameworks and optimized kernels can handle many of these decisions.</p><p>This is why I prefer not to think of the model as:</p><blockquote><strong>Everything FP32</strong><br>or:<br><strong>Everything BF16</strong></blockquote><p>The broader idea is:</p><blockquote><strong>Use high precision where it is necessary and lower precision where it is sufficient.</strong></blockquote><h3>What About INT8 and 4-Bit Quantization?</h3><p>At this point, someone usually asks:</p><blockquote><strong>If 16-bit is good, why stop there?</strong></blockquote><p>Good question.</p><p>We can go further:</p><blockquote>FP32 → <strong>32 bits</strong><br>BF16 / FP16 →<strong> 16 bits</strong><br>INT8 →<strong> 8 bits</strong><br>INT4 / 4-bit → <strong>~4 bits</strong></blockquote><p>Quantization can reduce model memory much further.</p><p>But I consider it a separate optimization topic because it introduces additional concerns:</p><ul><li>quantization methods</li><li>calibration</li><li>kernel support</li><li>accuracy degradation</li><li>dequantization overhead</li><li>weight-only vs activation quantization</li></ul><p>For this series, I am deliberately keeping the mental model focused on the five optimizations introduced in Part 1.</p><p>But the same principle still applies:</p><blockquote><strong>Smaller representations reduce memory and bandwidth requirements.</strong></blockquote><h3>How I Would Benchmark BF16 / FP16</h3><p>I would start with an FP32 or current-production baseline.</p><p>For each precision mode, I would record:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VbAmTGqWuXGzQ1i08e7llg.png" /></figure><p>I would not benchmark only with: <strong>“Hello”</strong></p><p>That tells me very little about my actual workload.</p><p>I would use realistic prompts.</p><p>For example:</p><blockquote><strong>Short Prompt</strong><br>~500 tokens<br><strong>Medium Prompt</strong><br>~4K tokens<br><strong>Long Prompt</strong><br>~8K tokens<br><strong>Very Long Prompt</strong><br>~16K tokens</blockquote><p>Then test concurrency:</p><blockquote><strong>1 user<br>5 users<br>10 users<br>20 users</strong></blockquote><p>This shows whether the memory savings actually translate into production capacity.</p><h3>A Simple Benchmark Matrix</h3><p>For example:</p><pre>                FP32       FP16       BF16<br>Peak VRAM         ?<br>TTFT              ?<br>TPOT              ?<br>Tokens/sec        ?<br>Max Context       ?<br>Max Users         ?<br>maQuality         ?</pre><p>The values don’t need to look impressive.</p><p>They need to tell me:</p><blockquote><strong>Which precision is best for this model on this GPU for this workload?</strong></blockquote><p>That is the engineering question.</p><h3>One Common Mistake: Looking Only at Model Size</h3><p>Suppose I see:</p><p>FP32 model = <strong>28 GB</strong><br>BF16 model = <strong>14 GB</strong></p><p>It is tempting to conclude:</p><blockquote><strong>Great — concurrency will double.</strong></blockquote><p>Not necessarily.</p><p>Concurrency may also be constrained by:</p><ul><li>KV Cache size</li><li>context length</li><li>temporary memory</li><li>batching strategy</li><li>attention implementation</li><li>request mix</li></ul><p>So reduced precision gives me more capacity.</p><p>What I do with that capacity depends on the rest of the inference architecture.</p><p>This is why the five optimizations need to eventually work together.</p><h3>Where BF16 Fits Into the Bigger Picture</h3><p>At this point our overall mental model looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAJHAzODf7TOpFuscGkk-Q.png" /></figure><p>And before the model:</p><blockquote><strong>Batching / Bucketing<br> ↓<br>Keep GPU busy</strong></blockquote><p>BF16 is therefore the <strong>memory and datatype foundation</strong> of the optimization stack.</p><h3>My Developer Mental Model</h3><p>When I hear:</p><p><strong><em>BF16<br>FP16<br>Mixed precision</em></strong></p><p>I don’t start by thinking about mantissa bits.</p><p>I first translate the discussion into:</p><blockquote><strong>Can I represent this workload using smaller numbers without materially hurting the model?</strong></blockquote><p>If yes:</p><blockquote><strong>Smaller numbers<br> ↓<br>Less memory<br> ↓<br>Less data movement<br> ↓<br>Better hardware utilization<br> ↓<br>More GPU headroom</strong></blockquote><p>And that headroom can become:</p><p><strong><em>Longer context + More KV Cache + Bigger batches + More concurrent users</em></strong></p><p>That is the part that actually matters to my application.</p><h3>The One Thing to Remember</h3><p>If you remember only one line from this article:</p><blockquote><strong><em>BF16 / FP16 = Make the numbers smaller.</em></strong></blockquote><p>But the complete developer mental model is slightly richer:</p><p>Don’t use more numerical precision than your inference workload actually needs.<br> ↓<br>Smaller tensors<br> ↓<br>Less VRAM + less memory bandwidth<br> ↓<br>More useful work from the same GPU</p><p>And most importantly:</p><blockquote><strong>Measure the improvement on your own model, GPU, prompts, and concurrency pattern.</strong></blockquote><p>There is no universal benchmark that can tell me exactly what BF16 will do for my production conversational AI system.</p><h3>What Comes Next?</h3><p>So far, we have addressed our first kind of GPU waste:</p><p><strong><em>Too much tensor memory<br> ↓<br>BF16 / FP16</em></strong></p><p>But even after making the tensors smaller, the Transformer can still spend a surprising amount of time moving attention data between GPU compute units and high-bandwidth memory.</p><p>And that problem becomes much more visible as context grows.</p><p>A 500-token prompt might be fine.</p><p>An 8K, 16K, or 32K conversational context is a very different workload.</p><p>That brings us to the next optimization.</p><h3>Part 3 — FlashAttention Explained Simply: Stop Moving So Much GPU Data</h3><p>In Part 3, I’ll explore:</p><ul><li>what actually happens during Transformer attention,</li><li>why attention can become a GPU memory-traffic problem,</li><li>why FlashAttention does not simply “remove the O(N²) calculation,”</li><li>what GPU tiling means without diving into CUDA internals,</li><li>why FlashAttention matters more for long-context conversational AI,</li><li>and what I would benchmark before and after enabling it.</li></ul><p>The mental model will be:</p><blockquote><strong><em>FlashAttention → Move less data.</em></strong></blockquote><p><em>This is Part 2 of </em><strong><em>Stop Wasting Your GPU: A Developer’s Guide to Local LLM Optimization</em></strong><em>.</em></p><p><a href="https://medium.com/@patil-parag-oss/your-llm-is-running-on-a-gpu-but-is-it-running-efficiently-2382a10eae9f"><strong>← Previous: Part 1 — Your LLM Is Running on a GPU. But Is It Running Efficiently?</strong></a></p><p><strong>Next → </strong><a href="https://medium.com/@patil-parag-oss/flashattention-explained-simply-stop-moving-so-much-gpu-data-9bcb121aeb2d?sharedUserId=patil-parag-oss"><strong>Part 3 — FlashAttention Explained Simply: Stop Moving So Much GPU Data</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5110971e0a69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your LLM Is Running on a GPU. But Is It Running Efficiently?]]></title>
            <link>https://patil-parag-oss.medium.com/your-llm-is-running-on-a-gpu-but-is-it-running-efficiently-2382a10eae9f?source=rss-966c27f82db4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2382a10eae9f</guid>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <dc:creator><![CDATA[Parag Patil]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 09:27:05 GMT</pubDate>
            <atom:updated>2026-08-27T07:54:27.911Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 1 of the series: </em><strong><em>Stop Wasting Your GPU — A Developer’s Guide to Local LLM Optimization</em></strong></p><p>When I first started running local LLMs on GPUs, I thought getting the model onto CUDA was the hard part.</p><p>The code worked.</p><pre>model = model.to(&quot;cuda&quot;)<br>output = model.generate(inputs)</pre><p>The GPU was visible in nvidia-smi.</p><p>The model was generating responses.</p><p>Latency looked reasonable during testing.</p><p>So naturally, I thought:</p><blockquote><strong>The model is running on the GPU. Performance should already be good.</strong></blockquote><p>Then the application moved closer to production.</p><p>One user became ten.</p><p>Ten users became twenty.</p><p>Prompts became longer because we started adding conversation history, RAG context, system instructions, user context, and tool results.</p><p>Suddenly, the same GPU that looked perfectly comfortable during development started behaving very differently.</p><p>I began seeing:</p><ul><li>GPU memory filling much faster than expected</li><li>Slow time to first token</li><li>Inconsistent token streaming</li><li>Requests building up in queues</li><li>Low GPU utilization at some times and saturation at others</li><li>Reduced concurrency</li><li>Out-of-memory failures under load</li></ul><p>That was when I realized something important:</p><blockquote><strong>Running an LLM on a GPU is not the same as running an LLM efficiently on a GPU.</strong></blockquote><p>That distinction is what this series is about.</p><h3>The Problem Usually Starts After the Demo</h3><p>A simple conversational AI request may look harmless.</p><p>A user asks:</p><blockquote><strong>“Why was my loan application rejected?”</strong></blockquote><p>From the user’s perspective, that is a single sentence.</p><p>But by the time my application constructs the actual LLM input, it may look more like this:</p><pre>System prompt             500 tokens<br>Conversation history    2,500 tokens<br>RAG context             4,000 tokens<br>Customer context          800 tokens<br>Current question          100 tokens<br>------------------------------------<br>Total                   7,900 tokens</pre><p>The user sent one question.</p><p>The GPU received nearly 8,000 tokens to process before it could generate the first response token.</p><p>And this is only one request.</p><p>Now imagine 20 users doing the same thing at roughly the same time.</p><p>That changes the engineering question completely.</p><p>The question is no longer:</p><blockquote><strong>Can the model generate the right answer?</strong></blockquote><p>It becomes:</p><blockquote><strong>How many conversations can I serve on the same GPU while maintaining acceptable latency, memory usage, and response quality?</strong></blockquote><p>That is the real production problem.</p><h3>My GPU Optimization Mental Model</h3><p>GPU optimization can quickly become intimidating.</p><p>You start hearing terms such as:</p><ul><li>BF16</li><li>FP16</li><li>Tensor Cores</li><li>FlashAttention</li><li>Triton</li><li>torch.compile</li><li>KV Cache</li><li>continuous batching</li><li>CUDA Graphs</li><li>paged attention</li></ul><p>All of them sound important.</p><p>But as a developer, I needed a simpler way to reason about the problem.</p><p>Eventually I reduced it to five questions.</p><blockquote><strong>Am I using more memory than necessary?<br>Am I moving too much data?<br>Am I executing the model inefficiently?<br>Am I recalculating work I already completed?<br>Is my GPU sitting idle?</strong></blockquote><p>And these questions map surprisingly well to five common optimizations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g911EFreqQYTcPreHtbZRQ.png" /></figure><p>This became the mental model I now use:</p><blockquote><strong>BF16 / FP16 </strong>→ Make the numbers smaller<br><strong>FlashAttention</strong> → Move less data<br><strong>torch.compile </strong>→ Execute operations smarter<br><strong>KV Cache</strong> → Don’t calculate the past again<br><strong>Batching / Bucketing</strong> → Keep the GPU busy</blockquote><p>If I understand those five sentences, I can understand most of the GPU optimization decisions around a local LLM.</p><h3>1. BF16 / FP16 — Make the Numbers Smaller</h3><p>An LLM is ultimately a massive collection of numbers.</p><p>Those numbers represent:</p><ul><li>model weights</li><li>activations</li><li>intermediate tensors</li><li>attention values</li><li>and cached states</li></ul><p>If I use FP32, each floating-point value typically consumes 32 bits.</p><p>If I can safely use BF16 or FP16, each value uses 16 bits.</p><p>The simplified mental model is:</p><pre>FP32<br>████████████████<br><br>BF16 / FP16<br>████████</pre><p>Smaller values mean less data to store and move.</p><p>That can translate into:</p><blockquote><strong>Less VRAM<br> ↓<br>More room for context<br> ↓<br>More room for KV Cache<br> ↓<br>Larger batches<br> ↓<br>More concurrent users</strong></blockquote><p>On modern GPUs, lower-precision formats can also make better use of Tensor Core hardware.</p><p>So I don’t think about BF16 as:</p><blockquote><strong>“A reduced-precision numerical format.”</strong></blockquote><p>I think:</p><blockquote><strong>Why am I paying for precision my inference workload may not need?</strong></blockquote><p>I’ll cover this in detail in Part 2.</p><h3>2. FlashAttention — Move Less Data</h3><p>When I first heard about FlashAttention, I assumed it simply reduced the amount of attention computation.</p><p>That is not the most useful way to think about it.</p><p>The real issue is often <strong>memory movement</strong>.</p><p>A Transformer attention operation conceptually looks like:</p><blockquote><strong><em>Q × Kᵀ<br> ↓<br>Attention scores<br> ↓<br>Softmax<br> ↓<br>× V</em></strong></blockquote><p>With long sequences, large intermediate attention data can be repeatedly written to and read from GPU memory.</p><p>And GPUs have an important characteristic:</p><blockquote><strong>They are incredibly fast at doing math, but moving data can still become expensive.</strong></blockquote><p>FlashAttention reorganizes the attention calculation so that more work is performed in smaller tiles using faster on-chip GPU memory.</p><p>My mental model is simply:</p><blockquote><strong>FlashAttention = move less data.</strong></blockquote><p>This becomes especially relevant for conversational AI applications containing:</p><blockquote><strong>Long chat history + Large RAG context + System instructions + Agent context + Tool responses</strong></blockquote><p>I’ll break this down visually in Part 3.</p><h3>3. torch.compile — Execute Operations Smarter</h3><p>Attention is only one part of a Transformer.</p><p>A typical block also performs:</p><p><strong><em>LayerNorm<br>Linear<br>Attention<br>Residual<br>LayerNorm<br>Linear<br>Activation<br>Linear<br>Residual</em></strong></p><p>Then it repeats this across many layers.</p><p>PyTorch eager execution is excellent for development, but the model may involve a very large number of individual operations and GPU kernel launches.</p><p>With:</p><pre>model = torch.compile(model)</pre><p>I am essentially asking PyTorch:</p><blockquote><strong>Can you look at the larger execution graph and find a more efficient way to run it?</strong></blockquote><p>That may include:</p><ul><li>reducing framework overhead</li><li>combining eligible operations</li><li>reducing intermediate work</li><li>and generating optimized GPU execution.</li></ul><p>So I remember:</p><blockquote><strong>torch.compile = execute operations smarter.</strong></blockquote><p>Not necessarily less mathematics.</p><p>Better execution of the mathematics.</p><p>That’s Part 4.</p><h3>4. KV Cache — Don’t Calculate the Past Again</h3><p>This one is particularly easy to understand in conversational AI.</p><p>LLMs generate responses token by token.</p><p>For example:</p><blockquote><strong>Your<br>Your application<br>Your application has<br>Your application has been<br>Your application has been approved</strong></blockquote><p>Every new token depends on the previous tokens.</p><p>Without caching, the model could repeatedly recalculate attention information it has already computed.</p><p>KV Cache stores the Key and Value representations of previous tokens.</p><p>Instead of:</p><blockquote><strong><em>Generate token<br>↓<br>Recalculate previous information</em></strong></blockquote><blockquote><strong><em>Generate next token<br>↓<br>Recalculate it again</em></strong></blockquote><p>we get:</p><blockquote><strong>Process previous tokens<br>↓<br>Store K/V<br>↓<br>Generate next token<br>↓<br>Reuse stored K/V</strong></blockquote><p>The analogy I use is:</p><blockquote><strong>If I have already solved steps 1 through 10, why would I solve them again just to calculate step 11?</strong></blockquote><p>So:</p><blockquote><strong>KV Cache = don’t calculate the past again.</strong></blockquote><p>I’ll explore what this means for token generation and GPU memory in Part 5.</p><h3>5. Batching and Bucketing — Keep the GPU Busy</h3><p>This is where model optimization turns into serving optimization.</p><p>Imagine I have optimized everything inside the model, but I process requests like this:</p><blockquote><strong>User A → GPU → response<br>User B → GPU → response<br>User C → GPU → response</strong></blockquote><p>The GPU may still be underutilized.</p><p>GPUs are designed for parallel workloads.</p><p>The analogy I use is a bus.</p><blockquote><strong>If I have a 50-seat bus and send it out with one passenger at a time, the bus is technically working.</strong></blockquote><p>It is just being used badly.</p><p>Batching lets me do:</p><blockquote><strong><em>User A ─┐<br>User B ─┤<br>User C ─┼── Batch → GPU<br>User D ─┘</em></strong></blockquote><p>Now the GPU has more work available in parallel.</p><p>But there is another problem.</p><p>Suppose the requests are:</p><blockquote><strong>100 tokens<br>120 tokens<br>150 tokens<br>8,000 tokens</strong></blockquote><p>Naively batching all of them together can waste significant compute on padding.</p><p>Bucketing groups similar workloads before batching.</p><p>So my shorthand is:</p><blockquote><strong>Batching fills the GPU. Bucketing fills it with compatible work.</strong></blockquote><p>Or even more simply:</p><blockquote><strong>Keep the GPU busy.</strong></blockquote><p>That’s Part 6.</p><h3>What Are We Actually Optimizing?</h3><p>At this point, it is easy to start thinking that success means enabling all five optimizations.</p><p>It doesn’t.</p><p>This:</p><blockquote><strong>BF16 ✔<br>FlashAttention ✔<br>torch.compile ✔<br>KV Cache ✔<br>Batching ✔</strong></blockquote><p>does not automatically mean:</p><blockquote><strong>GPU optimized ✔</strong></blockquote><p>The real objective is measurable application performance.</p><p>For a conversational AI system, I care about six metrics.</p><h3>TTFT — Time to First Token</h3><p>A user asks a question.</p><p>How long before they see the first word?</p><blockquote><strong><em>User asks question<br> ↓<br>……..<br> ↓<br>“Based…”</em></strong></blockquote><p>That delay is <strong>Time to First Token</strong>.</p><p>For conversational systems, TTFT has a major impact on perceived responsiveness.</p><h3>TPOT — Time Per Output Token</h3><p>After the first token appears, how quickly do subsequent tokens arrive?</p><blockquote><strong>Based<br>Based on<br>Based on your<br>Based on your application</strong></blockquote><p>This determines whether streaming feels smooth or painfully slow.</p><h3>Throughput</h3><p>How much useful work does the GPU perform?</p><p>Common measures include:</p><blockquote><strong>Tokens / second<br>Requests / second</strong></blockquote><p>A model may be fast for one user but terrible at overall throughput.</p><h3>Concurrency</h3><p>How many conversations can I serve simultaneously?</p><blockquote><strong>5?<br>20?<br>50?<br>100?</strong></blockquote><p>And more importantly:</p><blockquote><strong>At what point does latency become unacceptable?</strong></blockquote><h3>VRAM Consumption</h3><p>GPU memory determines:</p><blockquote><strong>Model size + Context size + KV Cache + Batch size + Concurrency</strong></blockquote><p>A model that fits comfortably during development may not fit once real users and long conversations arrive.</p><h3>GPU Utilization</h3><p>Finally, I want to know how effectively the GPU is being used.</p><p>But there is an important warning here.</p><h3>100% GPU Utilization Is Not the Goal</h3><p>Suppose I aggressively batch requests and achieve: <strong>GPU utilization = 99%</strong></p><p>That sounds excellent.</p><p>But what if every user waits 12 seconds before receiving the first token?</p><p>That is not a successful conversational AI system.</p><p>Similarly, suppose GPU utilization is only: <strong>70%</strong></p><p>but I achieve:</p><blockquote><strong>Low TTFT<br>Smooth token streaming<br>Required throughput<br>Required concurrency</strong></blockquote><p>That may be a perfectly good production configuration.</p><p>So my goal is not: <strong>MAX(GPU Utilization)</strong></p><p>My goal is closer to:</p><blockquote><strong>Required User Experience + Required Throughput + Required Concurrency<br> ↓<br>Minimum Practical GPU Cost</strong></blockquote><p>That is an important distinction.</p><h3>Optimize Waste, Not Technology</h3><p>This is the part of the mental model that I find most useful.</p><p>Whenever someone proposes a GPU optimization, I now ask:</p><blockquote><strong>What waste are we actually removing?</strong></blockquote><p>If the problem is:</p><h3>Too much tensor memory</h3><p>I look at:</p><blockquote><strong>BF16 / FP16</strong></blockquote><h3>Too much attention memory movement</h3><p>I look at:</p><blockquote><strong>FlashAttention</strong></blockquote><h3>Too much execution overhead</h3><p>I evaluate:</p><blockquote><strong>torch.compile</strong></blockquote><h3>Repeated computation</h3><p>I verify:</p><blockquote><strong>KV Cache</strong></blockquote><h3>Idle GPU capacity</h3><p>I investigate:</p><blockquote><strong>Batching / Bucketing</strong></blockquote><p>That makes the optimization discussion much more concrete.</p><p>Instead of saying:</p><blockquote><strong>“We should enable FlashAttention because it is faster.”</strong></blockquote><p>I can say:</p><blockquote><strong>“Our long-context workload is generating significant attention-related memory traffic, so we want to reduce unnecessary HBM movement.”</strong></blockquote><p>Now I know what problem I am solving.</p><h3>The Series Roadmap</h3><p>This article is only the starting point.</p><p>Over the next six parts, I’ll take each optimization separately and explain it from the same developer perspective.</p><h3>Part 1 — You are here</h3><p><strong>Your LLM Is Running on a GPU. But Is It Running Efficiently?</strong></p><p>The mental model and the five types of GPU waste.</p><h3>Part 2</h3><p><strong>BF16 vs FP16: Why Smaller Numbers Make Local LLMs Faster</strong></p><p>Mental model:</p><blockquote><strong>Make the numbers smaller.</strong></blockquote><h3>Part 3</h3><p><strong>FlashAttention Explained Simply: Stop Moving So Much GPU Data</strong></p><p>Mental model:</p><blockquote><strong>Move less data.</strong></blockquote><h3>Part 4</h3><p><strong>What Does </strong><strong>torch.compile() Actually Do to Your LLM?</strong></p><p>Mental model:</p><blockquote><strong>Execute operations smarter.</strong></blockquote><h3>Part 5</h3><p><strong>KV Cache Explained: Stop Making Your LLM Recalculate the Past</strong></p><p>Mental model:</p><blockquote><strong>Don’t calculate the past again.</strong></blockquote><h3>Part 6</h3><p><strong>Your GPU Is Powerful. So Why Is It Sitting Idle?</strong></p><p>Mental model:</p><blockquote><strong>Keep the GPU busy.</strong></blockquote><h3>Part 7</h3><p><strong>Putting It All Together: Optimize the Conversation, Not the Benchmark</strong></p><p>Where I will connect all five optimizations to:</p><ul><li>TTFT</li><li>TPOT</li><li>throughput</li><li>concurrency</li><li>VRAM</li><li>GPU utilization</li><li>and ultimately cost per conversation</li></ul><h3>The One Mental Model I Want You to Keep</h3><p>If you remember only one thing from this first article, remember this:</p><blockquote><strong>BF16 / FP16 </strong>→ Make the numbers smaller.<br><strong>FlashAttention</strong> → Move less data.<br><strong>torch.compile </strong>→ Execute operations smarter.<br><strong>KV Cache </strong>→ Don’t calculate the past again.<br><strong>Batching / Bucketing </strong>→ Keep the GPU busy.</blockquote><p>Put differently:</p><blockquote><strong>Smaller data + Less data movement + Smarter execution + Less recalculation + Better parallelism<br> ↓<br>More useful work from the same GPU</strong></blockquote><p>And ultimately, that is what I am trying to achieve.</p><p>Not a more impressive nvidia-smi screenshot.</p><p>Not more optimization flags in my code.</p><p>Not 100% GPU utilization for the sake of it.</p><p>The real objective is:</p><blockquote><strong>Serve more conversations with better response times using the GPU capacity I already have, without materially compromising model quality.</strong></blockquote><p>In Part 2, I’ll start with the simplest of the five optimizations:</p><h3>BF16 vs FP16 — Make the Numbers Smaller</h3><p>We’ll look at what precision actually means, why reducing it can dramatically change GPU memory usage, when BF16 makes more sense than FP16, and what I would measure before and after enabling it.</p><p><em>This is Part 1 of </em><strong><em>Stop Wasting Your GPU: A Developer’s Guide to Local LLM Optimization</em></strong><em>.</em></p><p><strong>Next → </strong><a href="https://medium.com/@patil-parag-oss/bf16-vs-fp16-why-smaller-numbers-make-local-llms-faster-5110971e0a69"><strong>Part 2: BF16 vs FP16 — Why Smaller Numbers Make Local LLMs Faster</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2382a10eae9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Assignment]]></title>
            <link>https://patil-parag-oss.medium.com/sql-assignment-c09d23cac523?source=rss-966c27f82db4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c09d23cac523</guid>
            <dc:creator><![CDATA[Parag Patil]]></dc:creator>
            <pubDate>Tue, 14 Oct 2025 21:57:06 GMT</pubDate>
            <atom:updated>2025-10-14T21:57:06.900Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>Get the total number of orders placed by each customer</li></ol><pre>SELECT Customers.CompanyName, COUNT(Orders.OrderID) AS NumberOfOrders<br>FROM Customers <br>LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID <br>GROUP BY Customers.CompanyName;</pre><p>Explanation: This query joins the Customers and Orders tables on the CustomerID field, counts the number of orders per customer, and returns a list of customer names and their order counts.</p><p>2. Find all suppliers who provide products in the ‘Seafood’ category</p><pre>SELECT Suppliers.CompanyName<br>FROM Suppliers <br>JOIN Products ON Suppliers.SupplierID = Products.SupplierID <br>JOIN Categories ON Products.CategoryID = Categories.CategoryID <br>WHERE Categories.CategoryName = &#39;Seafood&#39;;</pre><p>Explanation: This query first joins the Suppliers, Products, and Categories tables, then returns the names of suppliers who supply products in the ‘Seafood’ category.</p><p>3. Get the total quantity of each product sold</p><pre>SELECT Products.ProductName, SUM(Order_Details.Quantity) AS TotalSold<br>FROM Products<br>JOIN Order_Details ON Products.ProductID = Order_Details.ProductID<br>GROUP BY Products.ProductName;</pre><p>Explanation: This query joins the Products and Order_Details tables, and then sums the quantity of each product sold.</p><p>4. Find the total sales (Quantity*UnitPrice) for each category of products</p><pre>SELECT Categories.CategoryName, SUM(Order_Details.Quantity * Order_Details.UnitPrice) AS TotalSales<br>FROM Categories<br>JOIN Products ON Categories.CategoryID = Products.CategoryID<br>JOIN Order_Details ON Products.ProductID = Order_Details.ProductID<br>GROUP BY Categories.CategoryName;</pre><p>Explanation: This query first joins the Categories, Products, and Order_Details tables, and then calculates the total sales for each category of products.</p><p>5. List the employees and the number of orders each employee has taken</p><pre>SELECT Employees.FirstName, Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders<br>FROM Employees<br>JOIN Orders ON Employees.EmployeeID = Orders.EmployeeID<br>GROUP BY Employees.FirstName, Employees.LastName;</pre><p>Explanation: This query joins the Employees and Orders tables and counts the number of orders each employee has processed.</p><p>6. Get the customers who have placed more than 10 orders</p><pre>SELECT Customers.CompanyName, COUNT(Orders.OrderID) AS NumberOfOrders<br>FROM Customers<br>JOIN Orders ON Customers.CustomerID = Orders.CustomerID<br>GROUP BY Customers.CompanyName<br>HAVING COUNT(Orders.OrderID) &gt; 10;</pre><p>Explanation: This query joins the Customers and Orders tables, counts the number of orders each customer has placed, and returns only those customers who have placed more than 10 orders.</p><p>7. Get the top 5 most sold products</p><pre>SELECT Products.ProductName, SUM(Order_Details.Quantity) AS TotalSold<br>FROM Products<br>JOIN Order_Details ON Products.ProductID = Order_Details.ProductID<br>GROUP BY Products.ProductName<br>ORDER BY TotalSold DESC<br>LIMIT 5;</pre><p>Explanation: This query joins the Products and Order_Details tables, calculates the total quantity sold for each product, and returns the top 5 most sold products.</p><p>8. Find the products that have never been ordered</p><pre>SELECT Products.ProductName<br>FROM Products<br>LEFT JOIN Order_Details ON Products.ProductID = Order_Details.ProductID<br>WHERE Order_Details.ProductID IS NULL;</pre><p>Explanation: This query joins the Products and Order_Details tables and returns the products that have never been ordered.</p><p>9. Find the customers who have not placed any orders</p><pre>SELECT Customers.CompanyName<br>FROM Customers<br>LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID<br>WHERE Orders.CustomerID IS NULL;</pre><p>Explanation: This query joins the Customers and Orders tables and returns the customers who have not placed any orders.</p><p>10. List all ‘Orders’ with ‘Customer’ details and ‘Employee’ who processed it</p><pre>SELECT Orders.OrderID, Customers.CompanyName, Employees.FirstName, Employees.LastName<br>FROM Orders<br>JOIN Customers ON Orders.CustomerID = Customers.CustomerID<br>JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID;</pre><p>Explanation: This query first joins the Orders, Customers, and Employees tables, and then returns a list of orders, with the customer details and the name of the employee who processed each order.</p><p>11. Calculate the average product price by category</p><pre>SELECT Categories.CategoryName, AVG(Products.UnitPrice) AS AveragePrice<br>FROM Categories<br>JOIN Products ON Categories.CategoryID = Products.CategoryID<br>GROUP BY Categories.CategoryName;</pre><p>Explanation: This query first joins the Categories and Products tables, and then calculates the average price of products in each category.</p><p>12. Find the total revenue generated by each employee</p><pre>SELECT Employees.FirstName, Employees.LastName, SUM(Order_Details.UnitPrice * Order_Details.Quantity) AS TotalRevenue<br>FROM Employees<br>JOIN Orders ON Employees.EmployeeID = Orders.EmployeeID<br>JOIN Order_Details ON Orders.OrderID = Order_Details.OrderID<br>GROUP BY Employees.FirstName, Employees.LastName;</pre><p>Explanation: This query first joins the Employees, Orders, and Order_Details tables, and then calculates the total revenue generated by each employee.</p><p>13. List all orders shipped to ‘Germany’</p><pre>SELECT Orders.OrderID<br>FROM Orders<br>JOIN Customers ON Orders.CustomerID = Customers.CustomerID<br>WHERE Customers.Country = &#39;Germany&#39;;</pre><p>Explanation: This query joins the Orders and Customers tables and returns a list of orders that were shipped to Germany.</p><p>14. Find the most expensive product in each category</p><pre>SELECT Categories.CategoryName, Products.ProductName, MAX(Products.UnitPrice) AS MaxPrice<br>FROM Categories<br>JOIN Products ON Categories.CategoryID = Products.CategoryID<br>GROUP BY Categories.CategoryName;</pre><p>Explanation: This query first joins the Categories and Products tables, and then returns the most expensive product in each category.</p><p>15. Find the total revenue for the year 1997</p><pre>SELECT SUM(Order_Details.UnitPrice * Order_Details.Quantity) AS TotalRevenue<br>FROM Order_Details<br>JOIN Orders ON Order_Details.OrderID = Orders.OrderID<br>WHERE YEAR(Orders.OrderDate) = 1997;</pre><p>Explanation: This query joins the Orders and Order_Details tables and calculates the total revenue for the year 1997.</p><p>16. List all products that are discontinued</p><pre>SELECT Products.ProductName<br>FROM Products<br>WHERE Products.Discontinued = 1;</pre><p>Explanation: This query returns all products that are discontinued.</p><p>17. List all the distinct countries to which orders have been shipped</p><pre>SELECT DISTINCT Customers.Country<br>FROM Orders<br>JOIN Customers ON Orders.CustomerID = Customers.CustomerID;</pre><p>Explanation: This query first joins the Orders and Customers tables, and then returns a list of all distinct countries to which orders have been shipped.</p><p>18. Find all employees who report to ‘Andrew Fuller’</p><pre>SELECT e1.FirstName, e1.LastName<br>FROM Employees e1<br>JOIN Employees e2 ON e1.ReportsTo = e2.EmployeeID<br>WHERE e2.FirstName = &#39;Andrew&#39; AND e2.LastName = &#39;Fuller&#39;;</pre><p>Explanation: This query uses a self-join on the Employees table to find all employees who report to ‘Andrew Fuller’.</p><p>19. Find the customers who have spent more than $5000 in total</p><pre>SELECT Customers.CompanyName, SUM(Order_Details.UnitPrice * Order_Details.Quantity) AS TotalSpent<br>FROM Customers<br>JOIN Orders ON Customers.CustomerID = Orders.CustomerID<br>JOIN Order_Details ON Orders.OrderID = Order_Details.OrderID<br>GROUP BY Customers.CompanyName<br>HAVING TotalSpent &gt; 5000;</pre><p>Explanation: This query first joins the Customers, Orders, and Order_Details tables, then calculates the total amount spent by each customer, and returns only those customers who have spent more than $5000.</p><p>20. List the top 5 employees who have processed the most orders</p><pre>SELECT Employees.FirstName, Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders<br>FROM Employees<br>JOIN Orders ON Employees.EmployeeID = Orders.EmployeeID<br>GROUP BY Employees.FirstName, Employees.LastName<br>ORDER BY NumberOfOrders DESC<br>LIMIT 5;</pre><p>Explanation: This query first joins the Employees and Orders tables, then counts the number of orders each employee has processed, and returns the top 5 employees who have processed the most orders.</p><p>21. Get the list of customers who have ordered ‘Chai’ product</p><pre>SELECT Customers.Company_Name<br>FROM Customers<br>JOIN Orders ON Customers.Customer_ID = Orders.Customer_ID<br>JOIN Order_Details ON Orders.Order_ID = Order_Details.Order_ID<br>JOIN Products ON Order_Details.Product_ID = Products.Product_ID<br>WHERE Products.Product_Name = &#39;Chai&#39;;</pre><p>22. Get the employees who have processed orders for ‘Chai’ product</p><pre>SELECT Employees.First_Name, Employees.Last_Name<br>FROM Employees<br>JOIN Orders ON Employees.Employee_ID = Orders.Employee_ID<br>JOIN Order_Details ON Orders.Order_ID = Order_Details.Order_ID<br>JOIN Products ON Order_Details.Product_ID = Products.Product_ID<br>WHERE Products.Product_Name = &#39;Chai&#39;;</pre><p>23. Find the most common shipping country</p><pre>SELECT Customers.Country, COUNT(Orders.Order_ID) AS NumberOfOrders<br>FROM Customers<br>JOIN Orders ON Customers.Customer_ID = Orders.Customer_ID<br>GROUP BY Customers.Country<br>ORDER BY NumberOfOrders DESC<br>LIMIT 1;</pre><p>24. Find the order with the highest total cost</p><pre>SELECT Orders.Order_ID, SUM(Order_Details.Quantity * Order_Details.Unit_Price) as TotalCost<br>FROM Orders<br>JOIN Order_Details ON Orders.Order_ID = Order_Details.Order_ID<br>GROUP BY Orders.Order_ID<br>ORDER BY TotalCost DESC<br>LIMIT 1;</pre><p>25. Find the employees who have processed more than 100 orders</p><pre>SELECT Employees.First_Name, Employees.Last_Name, COUNT(Orders.Order_ID) AS NumberOfOrders<br>FROM Employees<br>JOIN Orders ON Employees.Employee_ID = Orders.Employee_ID<br>GROUP BY Employees.First_Name, Employees.Last_Name<br>HAVING NumberOfOrders &gt; 100;</pre><p>26. Find the customer who has ordered the most ‘Chai’ product</p><pre>SELECT Customers.Company_Name, SUM(Order_Details.Quantity) AS TotalQuantity<br>FROM Customers<br>JOIN Orders ON Customers.Customer_ID = Orders.Customer_ID<br>JOIN Order_Details ON Orders.Order_ID = Order_Details.Order_ID<br>JOIN Products ON Order_Details.Product_ID = Products.Product_ID<br>WHERE Products.Product_Name = &#39;Chai&#39;<br>GROUP BY Customers.Company_Name<br>ORDER BY TotalQuantity DESC<br>LIMIT 1;</pre><p>27. Find the average quantity of products ordered in each order</p><pre>SELECT Orders.Order_ID, AVG(Order_Details.Quantity) as AverageQuantity<br>FROM Orders<br>JOIN Order_Details ON Orders.Order_ID = Order_Details.Order_ID<br>GROUP BY Orders.Order_ID;</pre><p>28. Find the top 3 most popular categories of products ordered</p><pre>SELECT Categories.Category_Name, COUNT(Order_Details.Order_ID) AS NumberOfOrders<br>FROM Categories<br>JOIN Products ON Categories.Category_ID = Products.Category_ID<br>JOIN Order_Details ON Products.Product_ID = Order_Details.Product_ID<br>GROUP BY Categories.Category_Name<br>ORDER BY NumberOfOrders DESC<br>LIMIT 3;</pre><p>29. Find the month in the year 2016 with the highest total sales</p><pre>SELECT MONTH(Orders.Order_Date) AS Month, SUM(Order_Details.Quantity * Order_Details.Unit_Price) as TotalSales<br>FROM Orders<br>JOIN Order_Details ON Orders.Order_ID = Order_Details.Order_ID<br>WHERE YEAR(Orders.Order_Date) = 2016<br>GROUP BY MONTH(Orders.Order_Date)<br>ORDER BY TotalSales DESC<br>LIMIT 1;</pre><p>30. Find the employee who processed the most orders in August 2016</p><pre>SELECT Employees.First_Name, Employees.Last_Name, COUNT(Orders.Order_ID) AS NumberOfOrders<br>FROM Employees<br>JOIN Orders ON Employees.Employee_ID = Orders.Employee_ID<br>WHERE YEAR(Orders.Order_Date) = 2016 AND MONTH(Orders.Order_Date) = 8<br>GROUP BY Employees.First_Name, Employees.Last_Name<br>ORDER BY NumberOfOrders DESC<br>LIMIT 1;</pre><p>31. Find the top 3 customers who have ordered the most products</p><pre>SELECT Customers.Company_Name, SUM(Order_Details.Quantity) AS TotalQuantity<br>FROM Customers<br>JOIN Orders ON Customers.Customer_ID = Orders.Customer_ID<br>JOIN Order_Details ON Orders.Order_ID = Order_Details.Order_ID<br>GROUP BY Customers.Company_Name<br>ORDER BY TotalQuantity DESC<br>LIMIT 3;</pre><p>Explanation: This query first joins the Customers, Orders, and Order_Details tables. It then groups by the company name, sums the quantities of the products ordered, orders them in descending order, and finally limits the output to the top 3.</p><p>32. Find the employees who have not processed any orders</p><pre>SELECT Employees.First_Name, Employees.Last_Name<br>FROM Employees<br>WHERE Employees.Employee_ID NOT IN (<br>    SELECT Orders.Employee_ID FROM Orders<br>);</pre><p>Explanation: This query uses a subquery to get the list of Employee IDs from the Orders table, then it selects the employees whose IDs are not in this list, meaning they have not processed any orders.</p><p>33. Find the suppliers who supply the top 5 most sold products</p><pre>SELECT DISTINCT Suppliers.Company_Name<br>FROM Suppliers<br>JOIN Products ON Suppliers.Supplier_ID = Products.Supplier_ID<br>WHERE Products.Product_ID IN (<br>    SELECT Order_Details.Product_ID<br>    FROM Order_Details<br>    GROUP BY Order_Details.Product_ID<br>    ORDER BY SUM(Order_Details.Quantity) DESC<br>    LIMIT 5<br>);</pre><p>Explanation: This query uses a subquery to find the top 5 most sold products, then joins the Suppliers and Products tables to get the suppliers of these products.</p><p>34. Find the customers who have ordered products from all categories</p><pre>SELECT Customers.Company_Name<br>FROM Customers<br>WHERE NOT EXISTS (<br>    SELECT * FROM Categories<br>    WHERE NOT EXISTS (<br>        SELECT * FROM Orders<br>        JOIN Order_Details ON Orders.Order_ID = Order_Details.Order_ID<br>        JOIN Products ON Order_Details.Product_ID = Products.Product_ID<br>        WHERE Orders.Customer_ID = Customers.Customer_ID AND Products.Category_ID = Categories.Category_ID<br>    )<br>);</pre><p>Explanation: This query uses two nested subqueries to find the customers who have ordered products from all categories. It selects customers for whom there doesn’t exist a category for which there doesn’t exist an order containing a product from that category.</p><p>35. Find the total sales for each year</p><pre>SELECT YEAR(Orders.Order_Date) AS Year, SUM(Order_Details.Quantity * Order_Details.Unit_Price) as TotalSales<br>FROM Orders<br>JOIN Order_Details ON Orders.Order_ID = Order_Details.Order_ID<br>GROUP BY YEAR(Orders.Order_Date);</pre><p>Explanation: This query first joins the Orders and Order_Details tables. It then groups the data by year, and for each year, calculates the total sales by summing the product of quantity and unit price for all orders.</p><p>36. Classify customers based on their total order amounts such that total order amounts &gt; 5000 should be classified as ‘High Value’, if &gt; 1000 then as ‘Medium Value’ and otherwise as ‘Low Value’</p><p>Here is the sample output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*M132uU_YUlbAuOe2WxPjMQ.png" /></figure><pre>SELECT Customers.Company_Name,<br>       SUM(Order_Details.Quantity * Order_Details.Unit_Price) as TotalOrderAmount,<br>       CASE<br>           WHEN SUM(Order_Details.Quantity * Order_Details.Unit_Price) &gt; 5000 THEN &#39;High Value&#39;<br>           WHEN SUM(Order_Details.Quantity * Order_Details.Unit_Price) &gt; 1000 THEN &#39;Medium Value&#39;<br>           ELSE &#39;Low Value&#39;<br>       END as CustomerClass<br>FROM Customers<br>JOIN Orders ON Customers.Customer_ID = Orders.Customer_ID<br>JOIN Order_Details ON Orders.Order_ID = Order_Details.Order_ID<br>GROUP BY Customers.Company_Name;</pre><p>Explanation: This query first joins the Customers, Orders, and Order_Details tables, and then groups by the company name. It sums the quantities of the products ordered multiplied by their unit prices to calculate the total order amount for each customer. It then classifies customers as ‘High Value’, ‘Medium Value’, or ‘Low Value’ based on their total order amount.</p><p>37. Classify products based on their sales volume such that TotalQuantity &gt; 1000 Then SalesCategory as ‘High Sales’. If TotalQuantity&gt;500 Then ‘Medium Sales’ and else ‘Lower Sales’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*ANLP87Wok6lGmUpQyRizHw.png" /></figure><pre>SELECT Products.Product_Name,<br>       SUM(Order_Details.Quantity) as TotalQuantity,<br>       CASE<br>           WHEN SUM(Order_Details.Quantity) &gt; 1000 THEN &#39;High Sales&#39;<br>           WHEN SUM(Order_Details.Quantity) &gt; 500 THEN &#39;Medium Sales&#39;<br>           ELSE &#39;Low Sales&#39;<br>       END as SalesCategory<br>FROM Products<br>JOIN Order_Details ON Products.Product_ID = Order_Details.Product_ID<br>GROUP BY Products.Product_Name;</pre><p>Explanation: This query first joins the Products and Order_Details tables, then groups by the product name. It sums the quantities of the products sold to calculate the total sales volume for each product. It then classifies products as ‘High Sales’, ‘Medium Sales’, or ‘Low Sales’ based on their sales volume.</p><p>38. Classify employees based on the number of orders they have processed such that NumberOfOrders &gt; 100 Then PerformanceCategory as ‘High Performing’. If NumberOfOrders&gt;50 Then ‘Medium Performing’ and else ‘Lower Performing’</p><p>Here is the sample output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*1LE7hDYoxqxMN-CmNW9rpg.png" /></figure><pre>SELECT Employees.First_Name, Employees.Last_Name,<br>       COUNT(Orders.Order_ID) as NumberOfOrders,<br>       CASE<br>           WHEN COUNT(Orders.Order_ID) &gt; 100 THEN &#39;High Performing&#39;<br>           WHEN COUNT(Orders.Order_ID) &gt; 50 THEN &#39;Medium Performing&#39;<br>           ELSE &#39;Low Performing&#39;<br>       END as PerformanceCategory<br>FROM Employees<br>JOIN Orders ON Employees.Employee_ID = Orders.Employee_ID<br>GROUP BY Employees.First_Name, Employees.Last_Name;</pre><p>Explanation: This query first joins the Employees and Orders tables, then groups by the first and last names. It counts the number of orders each employee has processed. It then classifies employees as ‘High Performing’, ‘Medium Performing’, or ‘Low Performing’ based on the number of orders they have processed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c09d23cac523" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redefining Work-Life Balance: A Modern Perspective from the Knowledge Industry]]></title>
            <link>https://patil-parag-oss.medium.com/redefining-work-life-balance-a-modern-perspective-from-the-knowledge-industry-93855c7f49a4?source=rss-966c27f82db4------2</link>
            <guid isPermaLink="false">https://medium.com/p/93855c7f49a4</guid>
            <category><![CDATA[work-life-balance]]></category>
            <dc:creator><![CDATA[Parag Patil]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 11:22:56 GMT</pubDate>
            <atom:updated>2023-10-06T11:22:56.135Z</atom:updated>
            <content:encoded><![CDATA[<p>The conventional notion of work-life balance conjures images of a scale, evenly poised between professional obligations and personal enjoyment. However, a growing school of thought suggests that for a truly satisfying existence, particularly in the knowledge industry, perhaps we should first focus on excelling in our careers, subsequently paving the way for a fulfilling personal life. Let’s dive into an alternative perspective on the oft-debated concept of work-life balance.</p><h4>Traditional and Emerging Views on Work-Life Balance</h4><p>Traditionally, work-life balance has been envisioned as a strict separation between professional and personal life, each occupying an equal, but distinct, space. The modern perspective, especially relevant to the knowledge industry, argues that a symbiotic relationship between work and life not only exists but thrives when passion and excellence in work seamlessly integrate with personal satisfaction and relaxation.</p><h4>The Path to Excellence and Satisfaction Through Work</h4><p>Intrinsically, passion fuels excellence. When individuals are passionate about their work, it naturally translates to superior outcomes and high job satisfaction. Consider the stories of industry leaders like Elon Musk and Indra Nooyi, who, through dedication to their careers, have not only achieved professional excellence but have also crafted lives that are rich and personally satisfying.</p><h4>Unpacking the Knowledge Industry</h4><p>The knowledge industry, characterized by flexible schedules, continuous learning, and often, remote or hybrid work models, inherently defies the traditional 9–5 structure. The blurred lines between personal and professional spheres necessitate a fresh look at how work-life balance is perceived and achieved within this domain.</p><h4>Advocating for Work-Life Integration</h4><p>Work-life integration proposes a model where work and life are intertwined, where the demarcation between the two is fluid rather than rigid. This model prioritizes quality over quantity, suggesting that enriching experiences in both work and personal life are more valuable than the mere allocation of equal time to each. Thus, crafting a personalized balance that respects both career ambitions and life goals emerges as a viable approach.</p><h4>Addressing the Criticisms</h4><p>While the above model has its merits, it is crucial to address potential pitfalls such as burnout, neglect of personal relationships, and potential health concerns. Striking a balance that safeguards mental, emotional, and physical well-being is paramount to ensuring that the pursuit of work excellence does not inadvertently compromise life’s joys and relationships.</p><h4>Crafting a Personalized Work-Life Harmony</h4><p>Achieving a satisfying work-life integration involves identifying priorities, establishing boundaries, and retaining the flexibility to recalibrate as career and life evolve. This bespoke balance ensures alignment with individual aspirations, capacities, and responsibilities across the work-life spectrum.</p><h4>Conclusion</h4><p>In redefining work-life balance, especially within the ever-evolving knowledge industry, it is pivotal to recognize that a one-size-fits-all model is increasingly obsolete. The essence of a fulfilling existence lies in crafting a personalized approach that harmoniously integrates professional excellence and personal satisfaction. It is an invitation for individuals to reflect, redefine, and reimagine their own version of work-life balance, ensuring a future where work enriches life and vice versa.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93855c7f49a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>