<?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 Allam Satyanarayana on Medium]]></title>
        <description><![CDATA[Stories by Allam Satyanarayana on Medium]]></description>
        <link>https://medium.com/@allam.satyanarayana?source=rss-6f161f7e9dbe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_7s_rojgkX2TjFK6.jpg</url>
            <title>Stories by Allam Satyanarayana on Medium</title>
            <link>https://medium.com/@allam.satyanarayana?source=rss-6f161f7e9dbe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:48:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@allam.satyanarayana/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[Designing an LLM Inference Platform for 10,000 Requests per Second (and Testing the Ideas on a Free…]]></title>
            <link>https://medium.com/@allam.satyanarayana/designing-an-llm-inference-platform-for-10-000-requests-per-second-and-testing-the-ideas-on-a-free-6cee87ee62ca?source=rss-6f161f7e9dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cee87ee62ca</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[inference-engineering]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[kv-cache]]></category>
            <dc:creator><![CDATA[Allam Satyanarayana]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 00:17:21 GMT</pubDate>
            <atom:updated>2026-11-14T00:32:40.055Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing an LLM Inference Platform for 10,000 Requests per Second (and Testing the Ideas on a Free GPU)</h3><p><em>One system-design interview question, a full architecture, a cost estimate on AWS, and a set of real measurements from a Kaggle notebook.</em></p><h3>The question</h3><blockquote><strong><em>Design an LLM inference platform that has to serve 10,000 requests per second with p99 latency under 2 seconds. How would you handle batching, KV cache, autoscaling, and cost? What breaks first as traffic grows?</em></strong></blockquote><p>It reads like a wall of buzzwords. The model answer I started from was one dense paragraph: continuous batching, chunked prefill, PagedAttention, prefix caching, autoscale on queue depth and TTFT, right-size the model, and “prefill queueing breaks first, then KV-cache memory.”</p><p>That answer is directionally right, but it is compressed, and it asserts the failure order with more confidence than the evidence supports. So I did three things: I unpacked every term, drew the whole architecture, and then ran the ideas on a real GPU to see which parts of the answer held up.</p><h3>Step 1: Ask before you design</h3><p>A strong candidate does not start drawing boxes. The constraints are ambiguous in ways that change the design completely:</p><ul><li>Is the 2 seconds <strong>time to first token (TTFT)</strong>, or the <strong>whole response</strong>?</li><li>How long are prompts and outputs? A 200-token chat reply and a 4,000-token summary are different systems.</li><li>Is the response <strong>streamed</strong>? Which <strong>model size</strong>? Is traffic <strong>bursty</strong> or steady?</li></ul><p>Throughout this post I use one concrete scenario: an 8B-class model, about 500 input tokens and 200 output tokens per request, streamed responses, 2 seconds end to end at p99.</p><h3>Step 2: Do the arithmetic first</h3><p>“Start from the arithmetic” is the most important sentence in the model answer, and it never actually does any. Here it is.</p><p><strong>Concurrency (Little’s law).</strong> Requests in flight equals arrival rate times time in the system: 10,000 RPS x about 1.5 s is roughly <strong>15,000 requests in flight at once</strong>. That number drives KV cache memory and GPU count.</p><p><strong>Token rates.</strong></p><ul><li>Prefill: 10,000 x 500 = <strong>5 million input tokens per second</strong></li><li>Decode: 10,000 x 200 = <strong>2 million output tokens per second</strong></li></ul><p><strong>The latency budget.</strong> Total latency is TTFT plus output tokens times time per token. If TTFT takes 0.3 s, the remaining 1.7 s over 200 tokens leaves about <strong>8.5 ms per token</strong>. Output length is the hidden lever in any “2 second” target.</p><p><strong>KV cache per token</strong> = 2 x layers x KV heads x head dimension x bytes. For a Llama-3–8B-style model in FP16 that is 2 x 32 x 8 x 128 x 2 = <strong>128 KB per token</strong>. A 1,000-token context needs about 128 MB, so 15,000 requests in flight need roughly <strong>2 TB of KV cache</strong> across the fleet, before counting model weights. For a 70B-class model (80 layers, same KV heads) it is about 320 KB per token. Memory becomes a first-class constraint very quickly.</p><h3>Step 3: The architecture</h3><p>Full architecture of the LLM inference platform</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I52oog4tUZxiez9lGrwNFA.png" /></figure><p>Read the diagram as three layers.</p><p><strong>The request path (gray).</strong></p><ul><li><strong>API gateway.</strong> Authentication, rate limits, token streaming (SSE), and <em>admission control</em>: the ability to reject or queue requests gracefully instead of letting p99 collapse for everyone.</li><li><strong>Cache-aware router.</strong> A plain round-robin load balancer is not enough for LLMs. The router should send requests that share a prompt prefix to the replica that already holds that prefix in cache, while also looking at queue depth so it does not overload one replica.</li></ul><p><strong>The GPU data plane (teal).</strong></p><ul><li><strong>Replica pool.</strong> Each replica is an inference engine such as vLLM or SGLang on one GPU or a tensor-parallel group of GPUs. At large scale you can split the pool into separate <strong>prefill</strong> and <strong>decode</strong> pools, because the two phases stress the hardware differently (more on that below).</li><li><strong>Weight store.</strong> Model weights are tens of gigabytes. They live in object storage and a local NVMe cache so that new replicas can start quickly.</li></ul><p><strong>The control plane (purple).</strong></p><ul><li><strong>Metrics and tracing</strong> collect TTFT, queue depth, KV cache utilization and per-token latency from every replica.</li><li><strong>Autoscaler</strong> adds or removes replicas based on those signals, <strong>not CPU</strong>. GPU services do not show stress as CPU load.</li><li><strong>Warm pool</strong> holds pre-loaded spare replicas, because a cold replica can take minutes to download and load weights. Reactive autoscaling alone is too slow for bursts.</li><li>The metrics also feed back into the gateway so it can <strong>shed load</strong> when queues grow.</li></ul><h3>Step 4: Inside one replica</h3><p>Most of the interesting ideas in the model answer live inside a single replica.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bbIuzr5pN_BbZ-9hiHhW0w.png" /></figure><p>Inside one replica</p><p><strong>Prefill and decode are different workloads.</strong> <em>Prefill</em> processes the whole prompt in large matrix multiplies, so it is <strong>compute-bound</strong>. <em>Decode</em> generates one token at a time and must read all the model weights for every step, so it is <strong>memory-bandwidth-bound</strong>. If you have read about the roofline model, this is exactly that distinction: prefill sits to the right of the ridge point and decode sits far to the left.</p><p><strong>Continuous batching.</strong> Static batching waits for the slowest request in a batch to finish. Continuous batching adds and removes requests at <em>every decode step</em>. Because each step reads the weights once regardless of batch size, batching many requests amortizes that read across many tokens. This is the single biggest throughput lever, and I measure it below.</p><p><strong>Chunked prefill.</strong> A 10,000-token prompt can monopolize the GPU and stall everyone else’s token generation. Splitting prefill into chunks interleaved with decode steps keeps other users’ streaming smooth.</p><p><strong>PagedAttention.</strong> Older systems reserved one contiguous slab of KV memory per request, sized for the maximum length, wasting a lot of it. PagedAttention stores the cache in small fixed-size blocks, like virtual-memory pages, so more requests fit per GPU.</p><p><strong>Prefix caching.</strong> If many requests share a system prompt, compute its KV once and reuse it. That cuts prefill work and TTFT. It only helps if requests land on the replica that holds the cache, which is why the router has to be cache-aware.</p><h3>Step 5: Autoscaling</h3><p>Scale on <strong>leading indicators</strong>: queue depth and TTFT. By the time p99 moves, users are already unhappy.</p><p>Three details separate a good answer from a basic one:</p><ul><li><strong>Cold start is slow.</strong> A new replica must pull and load tens of gigabytes. Keep a warm pool, or scale predictively when traffic patterns are known.</li><li><strong>Idle GPUs cost the same as busy ones.</strong> The warm pool is insurance with a price tag, so size it deliberately.</li><li><strong>Scale on a capacity number you measured</strong>, not one you guessed. That is what the experiment below produces.</li></ul><h3>Step 6: What does it cost on AWS?</h3><p>I used public AWS price trackers (October 2026, US East, on-demand) and sized the 8B-class scenario. These are <strong>planning estimates, not quotes</strong>, and AWS GPU prices have moved several times over the past two years, so check the AWS Pricing Calculator before relying on any figure.</p><p><strong>The GPU prices I used.</strong></p><ul><li>A p5.48xlarge (8 x H100) is about <strong>$55.04 per hour</strong>, roughly $6.88 per GPU-hour.</li><li>A g6e.xlarge (1 x L40S, 48 GB) is about $1.86 per hour, and a g4dn.xlarge (1 x T4) is about $0.53 per hour.</li></ul><p><strong>Sizing arithmetic (my estimates).</strong></p><ul><li>Prefill: an 8B model costs about 16 GFLOP per token, so 5 million tokens per second is about 80 PFLOPS. At roughly 40% utilization on an H100 (about 400 TFLOPS), that needs about <strong>200 GPUs</strong>.</li><li>Decode: at roughly 12,000 tokens per second per H100 at large batch sizes, 2 million tokens per second needs about <strong>170 GPUs</strong>.</li><li>Total: about 370 H100s, or about 46 nodes. With 30% headroom, <strong>about 60 </strong><strong>p5.48xlarge nodes</strong>, which is about $3,300 per hour or <strong>$2.4 million per month</strong> on-demand.</li></ul><p>Cost levers</p><p>Three levers cut that bill roughly 3.5x:</p><ul><li><strong>Prefix caching.</strong> If 80% of each prompt is a shared system prompt, prefill work drops by about 80%.</li><li><strong>FP8 quantization.</strong> It roughly halves the bytes read per decode step and raises compute throughput.</li><li><strong>A smaller model</strong> that still meets your quality bar beats a large model you have to over-provision.</li></ul><p>A 1-year commitment would take roughly 30 to 50% off on top of that. And watch the hardware choice: an L40S reads 16 GB of FP16 weights in about 18 ms per decode step, which is <strong>over the 8.5 ms per-token budget</strong> from Step 2. Cheaper GPUs only work if the model is quantized or split across several of them.</p><p>Everything else in the diagram (gateway and router CPU pods, load balancers, data transfer, observability) is small next to the GPUs. My rough guess is well under 10% of the bill, but I did not price it line by line.</p><h3>Step 7: What breaks first?</h3><p>The model answer says prefill queueing, then KV-cache memory. My honest answer is <strong>it depends on prompt length, output length and model size</strong>, so I tested it.</p><h3>The experiment: one replica on a free Kaggle GPU</h3><p>I cannot reproduce 10,000 RPS on a free notebook. What I <em>can</em> do is measure one replica carefully, because capacity planning starts there:</p><pre>replicas = target RPS / (RPS one replica sustains within the SLO) x headroom</pre><p><strong>Setup.</strong> A Kaggle notebook with a Tesla T4, vLLM serving Qwen/Qwen2.5-0.5B-Instruct (small and ungated), prompts of roughly 200 tokens, 128 output tokens, --max-num-seqs 64. A small asyncio load generator streams responses and records TTFT and end-to-end latency at rising concurrency, while a second task samples vLLM&#39;s /metrics endpoint for queue depth and KV cache usage.</p><p>The server launch:</p><p>python</p><pre>import subprocess<br>server = subprocess.Popen([<br>    &quot;python&quot;, &quot;-m&quot;, &quot;vllm.entrypoints.openai.api_server&quot;,<br>    &quot;--model&quot;, &quot;Qwen/Qwen2.5-0.5B-Instruct&quot;,<br>    &quot;--dtype&quot;, &quot;half&quot;,<br>    &quot;--max-model-len&quot;, &quot;2048&quot;,<br>    &quot;--gpu-memory-utilization&quot;, &quot;0.85&quot;,<br>    &quot;--max-num-seqs&quot;, &quot;64&quot;,<br>    &quot;--enable-prefix-caching&quot;,<br>    &quot;--port&quot;, &quot;8000&quot;,<br>])</pre><p>The core of the load generator (streaming, so TTFT is measurable):</p><p>python</p><pre>async def one(session):<br>    t0 = time.perf_counter(); ttft = None; n = 0<br>    content = f&quot;Request {uuid.uuid4()}. &quot; + PROMPT      # unique prompt per request<br>    body = {&quot;model&quot;: MODEL, &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: content}],<br>            &quot;max_tokens&quot;: 128, &quot;stream&quot;: True}<br>    async with session.post(URL, json=body) as r:<br>        async for line in r.content:<br>            if line.startswith(b&quot;data:&quot;) and b&quot;[DONE]&quot; not in line:<br>                if ttft is None: ttft = time.perf_counter() - t0<br>                n += 1<br>    return ttft, time.perf_counter() - t0, n</pre><h3>Finding 1: Batching is a 20x throughput lever</h3><p>With one stream, the server produced about 168 tokens per second. With 64 concurrent streams it produced about 3,500. Each decode step reads the weights once whatever the batch size, so batching spreads that cost across users.</p><p>The price is per-user speed. Time per token grew from about 6 ms at batch size 1 to about 19 ms at batch size 64. <strong>Throughput and per-user latency trade against each other</strong>, which is the heart of LLM serving.</p><h3>Finding 2: My first numbers were too optimistic</h3><p>In the first sweep every request used an identical prompt, so the prefix cache made prefill nearly free. Once I made every prompt unique, throughput dropped by 19 to 28% and p99 TTFT rose roughly five-fold at the same concurrency. If you benchmark with repeated prompts, you are benchmarking your cache, not your system.</p><h3>Finding 3: Capacity curves for one and two replicas</h3><p>Capacity curves</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JoBcdV9tKFal-uD-F3U-Q.png" /></figure><p>What the curves show:</p><ul><li><strong>One replica.</strong> p99 latency passed the 2 s target between 24 and 32 concurrent requests. At 16 concurrent requests it served about 11 RPS with p99 at about 1.5 s, and I treat that as the safe operating point.</li><li><strong>The queue forms before the cap.</strong> With unique prompts, requests started waiting at about 40 concurrent requests, below the scheduler cap of 64. The wait was for <em>prefill</em>, not for a free slot.</li><li><strong>Two replicas scaled almost perfectly.</strong> Splitting traffic across two T4s gave 98 to 105% of double the single-replica throughput at the same load per replica. At 16 concurrent requests per replica, the pair served about 22 RPS with p99 near 1.6 s.</li><li><strong>Then a hard ceiling.</strong> Throughput flattened near 40 RPS, and p99 TTFT jumped from about 1 s to about 3.5 s once concurrency passed what the servers could run at once.</li></ul><h3>Finding 4: The failure order</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6IKzOJqKyuekyPTTWzu4Q.png" /></figure><p>What breaks first</p><p>In my measurements, the SLO broke in stages: first <strong>per-token slowdown</strong> as batches grew, then <strong>prefill queueing</strong> that lengthened TTFT, then a <strong>scheduler cap</strong> where running requests were pinned and everyone else waited. <strong>KV cache never mattered</strong>: it stayed under 3% for this small model with short prompts. For long contexts or larger models I would expect it to come into play, which is why the model answer’s “then KV memory” is plausible but not universal.</p><h3>Finding 5: The GPU was busy but inefficient</h3><p>I first suspected the CPU was starving the GPU (the “launch-bound” case from the profiling lesson). Measuring disproved that. During the load, GPU utilization read 100%, power sat near 66 W against a 70 W limit, the clock ran around 1.1 GHz, and the busiest vLLM process used only 43 to 61% of one CPU core.</p><p>So the card was busy and power-capped, yet my back-of-envelope math says it delivered only a few TFLOPS of useful math and tens of GB/s of memory traffic, far below its peaks. For a 0.5B model that points to small kernels and a large vocabulary layer, not to a host bottleneck. That is a hypothesis; confirming it would need a kernel-level profiler.</p><h3>Three measurement traps I hit</h3><ul><li><strong>A cold replica.</strong> The first run against the second server showed an absurd TTFT because it had not been warmed up. Always send warm-up requests to every replica.</li><li><strong>A client-side connection limit.</strong> My aiohttp session capped simultaneous connections at 100, so requests above that waited <em>inside my own load generator</em>, inflating TTFT. Setting TCPConnector(limit=0) fixed it. I caught this because the server reported 64 running + 36 waiting = 100, not the 128 I thought I was sending.</li><li><strong>Two GPUs in one </strong><strong>nvidia-smi query.</strong> Kaggle&#39;s &quot;T4 x2&quot; setting exposes two cards, and my first utilization sampler mixed their rows, producing a meaningless 0% median. Query one GPU at a time with nvidia-smi -i 0.</li></ul><p>The lesson: check client-side numbers against server-side counters before believing either.</p><h3>From one replica to a fleet</h3><p>Using the conservative 11 RPS per replica:</p><pre>replicas = 10,000 / 11 x 1.3 headroom = about 1,180 T4 replicas</pre><p>At about $0.53 per hour per T4 that is roughly $625 per hour, or $0.45 million per month. That is a demonstration of the <em>method</em>. It is a 0.5B toy model with short prompts, so do not compare it with the 8B estimate above.</p><h3>The 2-minute interview answer</h3><blockquote><em>I’d first clarify whether the 2 seconds is TTFT or the full response, and the prompt and output lengths. Then I’d do the arithmetic: 10,000 RPS at about 1.5 seconds is around 15,000 requests in flight, and at 500 input and 200 output tokens that’s 5 million prefill tokens and 2 million decode tokens per second, with a budget of roughly 8 milliseconds per output token.</em></blockquote><blockquote><em>The architecture is a gateway with auth, rate limiting and admission control, a cache-aware router, and a pool of GPU replicas running continuous batching with chunked prefill, PagedAttention and prefix caching. A control plane watches queue depth, TTFT and KV utilization, and autoscales on those, not CPU, with a warm pool because replica cold starts take minutes.</em></blockquote><blockquote><em>For cost, I’d measure how many RPS one replica sustains within the SLO, divide, add headroom, and then reduce the bill with prefix caching, quantization and the smallest model that meets the quality bar.</em></blockquote><blockquote><em>What breaks first depends on the workload. In my single-replica tests, per-token latency degraded first as batches grew, then prefill queueing pushed TTFT up before the scheduler’s concurrency cap was even reached. KV cache never mattered for that small model, but with long contexts or a large model I’d expect it to be next. So I’d watch queue wait, TTFT, per-token latency and KV utilization together, and size replicas at a point with real margin under the SLO.</em></blockquote><h3>What this does not prove</h3><p>Being honest about limits is part of a good answer:</p><ul><li>It is a <strong>0.5B model</strong> on small T4 GPUs. An 8B model on H100s has a different bottleneck mix.</li><li>All requests had <strong>similar lengths</strong>. Real traffic is messier, and I did not test whether a load-aware router beats round-robin under mixed lengths.</li><li>I tested <strong>one and two replicas</strong>, not a router, an autoscaler or a warm pool. Those parts of the architecture rest on reasoning and published practice, not on my measurements.</li><li>The AWS cost figures are <strong>estimates from public price trackers</strong> and my own throughput assumptions.</li></ul><h3>Key takeaways</h3><ol><li><strong>Do the arithmetic first.</strong> Little’s law, token rates, a per-token latency budget and KV size per token turn vague requirements into numbers.</li><li><strong>Prefill is compute-bound and decode is memory-bound.</strong> That one fact explains continuous batching, chunked prefill, quantization and disaggregated pools.</li><li><strong>Batching trades per-user speed for throughput.</strong> A replica’s safe operating point sits well below its throughput peak.</li><li><strong>Autoscale on queue depth and TTFT, and keep a warm pool.</strong> Cold starts are slow and idle GPUs still cost money.</li><li><strong>“What breaks first” depends on the workload.</strong> Say so, name the signals you would watch, and back it with a measurement.</li><li><strong>Capacity planning is </strong><strong>target RPS / measured RPS per replica x headroom.</strong> Measure with realistic, unique prompts and warm replicas.</li><li><strong>Cross-check client numbers against server counters.</strong> Two of my three traps were measurement bugs, not system behavior.</li></ol><h3>Further reading</h3><ul><li>vLLM documentation: continuous batching, PagedAttention, prefix caching and chunked prefill</li><li>The PagedAttention paper (Kwon et al., “Efficient Memory Management for Large Language Model Serving with PagedAttention”)</li><li>AWS GPU pricing guide (OpsLyft, October 2026) and the AWS Pricing Calculator</li><li>Reporting on AWS GPU price changes: The Register, “AWS raises GPU prices 15% on a Saturday” (January 2026).</li><li><a href="https://github.com/satyanarayanaallam/llm-inference-platform-10k-rps.git">https://github.com/satyanarayanaallam/llm-inference-platform-10k-rps.git</a></li></ul><p><em>If this helped, share it with someone preparing for an AI infrastructure or performance engineering interview.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cee87ee62ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Is My GPU Model So Slow? A Hands-On Guide to Profiling with the Roofline Model]]></title>
            <link>https://medium.com/@allam.satyanarayana/why-is-my-gpu-model-so-slow-a-hands-on-guide-to-profiling-with-the-roofline-model-966d2498ff54?source=rss-6f161f7e9dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/966d2498ff54</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[gpu-profiling]]></category>
            <category><![CDATA[gpu-acceleration]]></category>
            <category><![CDATA[matrix]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Allam Satyanarayana]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 14:45:42 GMT</pubDate>
            <atom:updated>2026-11-12T14:45:42.875Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I had never run a GPU profiler before. Here is how I went from one interview question to a working mental model, using nothing but a free Kaggle notebook and a Tesla T4.</em></p><h3>The interview question</h3><blockquote><strong><em>You profile a model with Nsight Systems, Nsight Compute, and PyTorch Profiler, and it’s running well below its expected FLOPS. Walk me through your profiling workflow: how do you use a roofline model to decide if you’re compute-bound, memory-bandwidth-bound, or launch-bound, and what do you look at next in each case?</em></strong></blockquote><p>On first read, this sounds like a wall of jargon. So instead of memorizing an answer, I broke it down piece by piece, ran a few experiments, and then wrote the answer in my own words. This post follows that same path.</p><h3>Part 1: Decoding the question</h3><p>The interviewer is not asking for a list of tools. They want a <strong>workflow</strong>: an order of operations with decision points.</p><p>The setup has three profilers, all running on NVIDIA GPUs:</p><ul><li><strong>Nsight Systems</strong> is the <em>timeline</em> view. It shows kernel launches, gaps between kernels, CPU/GPU overlap, memory copies and sync points.</li><li><strong>Nsight Compute</strong> is the <em>per-kernel microscope</em>. It shows achieved FLOPS, memory throughput, occupancy, stall reasons and where a kernel sits on the roofline.</li><li><strong>PyTorch Profiler</strong> is the <em>framework view</em>. It maps GPU time back to PyTorch ops and shows CPU-side overhead.</li></ul><p>And the symptom is <strong>“well below expected FLOPS”</strong>. That phrase hides two ideas worth unpacking.</p><h3>FLOPs vs FLOPS</h3><ul><li><strong>FLOPs</strong> (lowercase s) is a <em>count</em>: how many floating-point operations the work needs.</li><li><strong>FLOPS</strong> (uppercase S) is a <em>rate</em>: operations per second.</li></ul><pre>Achieved FLOPS = total FLOPs ÷ time taken</pre><p>If a GPU can theoretically do 1000 TFLOPS and your model reaches 200, you are at 20% of peak.</p><h3>What does “expected” mean?</h3><ul><li>The <strong>theoretical peak</strong> from the spec sheet (you almost never hit 100%).</li><li>A <strong>realistic target</strong>, such as 50–70% of peak for well-tuned matrix-multiply workloads.</li><li>A <strong>previous baseline</strong>, such as an older version of the model.</li></ul><p>Peak also depends on <strong>precision</strong> (FP32 vs FP16/BF16/FP8) and on whether <strong>tensor cores</strong> are used. Compare against the wrong peak and you may think the model is slow when the expectation was the problem. A strong answer starts by checking the expectation.</p><h3>Part 2: What is a “kernel”?</h3><p>This word tripped me up, so it deserves its own section.</p><p>A <strong>GPU kernel is not the operating system kernel.</strong> Same word, unrelated meaning. In GPU programming, a kernel is simply <strong>a function that runs on the GPU</strong>, executed by thousands of threads at once, each working on a different piece of the data.</p><p>The flow looks like this:</p><ol><li>Your program runs on the <strong>CPU</strong> (the <em>host</em>).</li><li>The CPU <strong>launches</strong> a kernel on the GPU (the <em>device</em>).</li><li>The GPU runs it in parallel while the CPU moves on to launch the next one.</li></ol><p>When PyTorch runs torch.matmul(a, b), it launches a matrix-multiply kernel. relu launches another. A layer norm launches another. <strong>One forward pass can be hundreds or thousands of kernels.</strong></p><h3>Part 3: The roofline model</h3><p>The roofline model answers one question:</p><blockquote>Given a kernel’s characteristics, what is the maximum speed the hardware can possibly give it?</blockquote><p>A kernel can be limited by one of two things: how fast the GPU can <strong>compute</strong>, or how fast it can <strong>move data</strong>.</p><h3>Arithmetic intensity</h3><pre>Arithmetic Intensity (AI) = FLOPs performed ÷ bytes moved from memory</pre><ul><li><strong>Low AI:</strong> little math per byte, so the kernel mostly waits for data.</li><li><strong>High AI:</strong> lots of math per byte, so the kernel keeps the math units busy.</li></ul><h3>The formula</h3><pre>Attainable FLOPS = min( Peak FLOPS , AI × Peak Memory Bandwidth )</pre><p>Plot it on log-log axes (x = arithmetic intensity, y = performance) and you get a roof shape:</p><ul><li><strong>The sloped line on the left</strong> is the <strong>memory roof</strong>. Performance rises with intensity.</li><li><strong>The flat line on the right</strong> is the <strong>compute roof</strong> (peak FLOPS).</li><li><strong>The ridge point</strong> is where they meet. Left of it, kernels are memory-bound. Right of it, compute-bound.</li></ul><p>Every kernel is a single <strong>dot</strong> on this chart.</p><h3>Two worked examples</h3><p>Take a GPU with roughly 1000 TFLOPS peak and 3 TB/s of bandwidth. The ridge point is about 330 FLOPs/byte.</p><p><strong>Elementwise add of two FP16 vectors</strong></p><ul><li>1 FLOP per element, 6 bytes moved per element (two reads, one write)</li><li>AI ≈ 0.17 FLOPs/byte, far left of the ridge</li><li>Attainable ≈ 0.5 TFLOPS, about 0.05% of peak</li></ul><p>No amount of tuning will push this kernel toward peak FLOPS. <strong>Low FLOPS is simply what the hardware allows at that intensity.</strong></p><p><strong>Large matrix multiply (4096 × 4096, FP16)</strong></p><ul><li>2N³ FLOPs over roughly 6N² bytes, so AI ≈ N/3 ≈ 1365</li><li>Far right of the ridge, so it <em>can</em> approach the compute roof</li><li>Low FLOPS here would signal a real inefficiency</li></ul><h3>The limit of the roofline</h3><p>The roofline only describes kernels that are <strong>running</strong>. If the GPU sits idle between kernels, the dots look fine but the run is still slow. That is the <strong>launch-bound</strong> case, and it never shows up on a roofline. This is why the workflow starts with a timeline.</p><h3>Part 4: Three reasons for low FLOPS</h3><p>The same symptom, low FLOPS, comes from at least three different causes:</p><ol><li><strong>Memory-bandwidth-bound.</strong> The kernel waits on data from memory. Low FLOPS is <em>expected</em>, because the memory roof sits below the compute peak.</li><li><strong>Launch-bound.</strong> The GPU idles between many tiny kernels because the CPU or framework cannot feed it fast enough.</li><li><strong>Compute-bound but inefficient.</strong> Intensity is high, but the kernel sits below the compute roof because tensor cores are not used, precision is too high, or tiling and occupancy are poor.</li></ol><p>My first instinct was <em>“it’s probably memory-bound.”</em> That is a reasonable hypothesis, but without measurement it is a guess, not a diagnosis. The point of the question is to measure, then decide.</p><h3>Part 5: The experiment (free, on Kaggle)</h3><p>I ran everything on a <strong>Tesla T4</strong> in a Kaggle notebook. PyTorch Profiler works there out of the box. Nsight Systems and Nsight Compute generally need a machine where you have root access and GPU counter permissions, so I used simple hand measurements to learn the same ideas.</p><p>As far as I know, the T4 has about <strong>65 TFLOPS</strong> of FP16 tensor-core peak and <strong>320 GB/s</strong> of memory bandwidth. That puts its ridge point near <strong>200 FLOPs/byte</strong>. (Check NVIDIA’s spec sheet for exact numbers.)</p><h3>The benchmark</h3><p>python</p><pre>import torch<br>def bench(fn, iters=50, warmup=10):<br>    for _ in range(warmup): fn()<br>    torch.cuda.synchronize()<br>    s, e = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)<br>    s.record()<br>    for _ in range(iters): fn()<br>    e.record(); torch.cuda.synchronize()<br>    return s.elapsed_time(e) / iters / 1000   # seconds per call<br># 1) Big matmul: high arithmetic intensity (compute-bound)<br>N = 4096<br>a = torch.randn(N, N, device=&quot;cuda&quot;, dtype=torch.float16)<br>b = torch.randn(N, N, device=&quot;cuda&quot;, dtype=torch.float16)<br>t = bench(lambda: a @ b)<br>print(f&quot;Matmul     : {2*N**3 / t / 1e12:.1f} TFLOPS&quot;)<br># 2) Big elementwise add: very low arithmetic intensity (memory-bound)<br>n = 100_000_000<br>x = torch.randn(n, device=&quot;cuda&quot;, dtype=torch.float16)<br>y = torch.randn(n, device=&quot;cuda&quot;, dtype=torch.float16)<br>t = bench(lambda: x + y)<br>print(f&quot;Vector add : {3*n*2 / t / 1e9:.0f} GB/s moved, {n / t / 1e12:.3f} TFLOPS&quot;)<br># 3) Many tiny ops: launch overhead dominates<br>small = torch.randn(1000, device=&quot;cuda&quot;)<br>def many_small():<br>    for _ in range(1000):<br>        small.add_(1)<br>t = bench(many_small, iters=5, warmup=2)<br>print(f&quot;1000 tiny ops: {t*1000:.1f} ms total, {t/1000*1e6:.1f} microseconds per op&quot;)</pre><h3>Why divide?</h3><p>Each metric is just <strong>work ÷ time = rate</strong>:</p><ul><li>2*N**3 is the FLOP count of a matmul (N² outputs, each needing N multiplies and N adds). Divide by seconds to get FLOPS, and by 1e12 to read it in TFLOPS.</li><li>3*n*2 is the bytes moved by the add: read x, read y, write the result, at 2 bytes per FP16 element. Divide by seconds and 1e9 to get GB/s.</li><li>n is the FLOP count of the add (one operation per element).</li></ul><p>And a neat connection: <strong>work ÷ bytes = arithmetic intensity</strong> (the x-axis), while <strong>work ÷ time = achieved rate</strong> (the y-axis).</p><h3>My results</h3><pre>Matmul     : 21.6 TFLOPS<br>Vector add : 252 GB/s moved, 0.042 TFLOPS<br>1000 tiny ops: 7.8 ms total, 7.8 microseconds per op</pre><h3>What they mean</h3><p><strong>Matmul: 21.6 TFLOPS (about 33% of peak). Compute-bound.</strong> Arithmetic intensity is about 1365, far right of the ridge. 33% looks low, but the T4 is a 70 W card that throttles clocks under sustained tensor-core load, and 25–40 TFLOPS is common in practice. Not much headroom.</p><p><strong>Vector add: 252 GB/s (about 79% of peak bandwidth). Memory-bound.</strong> Arithmetic intensity is about 0.17. The memory roof at that intensity is roughly 0.053 TFLOPS, and I measured 0.042, so about 79% of the roof. Real kernels typically top out at 80–90% of spec bandwidth, so this is close to the best the hardware can do. Its FLOPS is a tiny fraction of the compute peak, and that is perfectly normal.</p><p><strong>Tiny ops: 7.8 µs each. Launch-bound.</strong> Each op touches only 1000 elements, so the GPU work takes a few microseconds, yet each op costs about 7.8 µs end to end. The rest is CPU-side overhead: Python, PyTorch dispatch and the CUDA launch call. The GPU spends much of that time waiting.</p><p><strong>One GPU, three different bottlenecks, depending on the operation.</strong></p><h3>Part 6: Reading the PyTorch Profiler</h3><p>python</p><pre>from torch.profiler import profile, ProfilerActivity<br>with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:<br>    a @ b<br>    x + y<br>    many_small()<br>    torch.cuda.synchronize()<br>print(prof.key_averages().table(sort_by=&quot;device_time_total&quot;, row_limit=10))<br>prof.export_chrome_trace(&quot;trace.json&quot;)</pre><p>The trimmed output showed:</p><ul><li><strong>Matmul kernel</strong> (turing_fp16_s1688gemm_...): 1 call, <strong>6.543 ms</strong> of GPU time.</li><li><strong>Big add kernel</strong> (vectorized_elementwise_kernel): 1 call, <strong>2.377 ms</strong>.</li><li><strong>Tiny </strong><strong>add_ kernel</strong>: <strong>1000 calls</strong>, <strong>3.55 µs</strong> of GPU time each.</li><li><strong>cudaLaunchKernel</strong>: called <strong>1002 times</strong>, about 6.7 µs each on the CPU.</li></ul><h3>Tips for reading the table</h3><ul><li><strong>Self</strong> columns count only that row. <strong>Total</strong> columns include everything the row calls, so parents double-count children.</li><li>The real GPU time is at the bottom: <strong>Self CUDA time total</strong>.</li><li>Ignore “Activity Buffer Request”. It is the profiler’s own bookkeeping.</li></ul><h3>Cross-checking the hand measurements</h3><ul><li>Matmul: 137.4 GFLOP ÷ 6.543 ms ≈ <strong>21 TFLOPS</strong>. It matches.</li><li>Vector add: 600 MB ÷ 2.377 ms ≈ <strong>252 GB/s</strong>. It matches.</li><li>The matmul kernel name tells us <strong>tensor cores are in use</strong>, so the 33% of peak is not caused by missing tensor cores.</li></ul><h3>The launch-bound signature</h3><p>For the tiny kernel, the GPU works about <strong>3.5 µs</strong> per op while the CPU spends roughly <strong>3x longer</strong> issuing it (the profiler inflates CPU time a bit, so the unprofiled 7.8 µs is the more honest number). The GPU is idle a large share of the time. Compare that with the matmul and the big add, which run for milliseconds, where launch cost is invisible.</p><p>You can also open trace.json at <a href="https://ui.perfetto.dev/">ui.perfetto.dev</a> and zoom into the 1000 small kernels. You will see thin blocks with <strong>empty gaps</strong> between them, while the matmul and big add look like solid bars.</p><h3>Part 7: The answer</h3><p>Here is the answer I would give in an interview.</p><h3>Step 0: Check the expectation</h3><p>Confirm “expected FLOPS” is realistic. Use the right peak for the precision, and check whether tensor cores can apply. A model made of small or memory-heavy ops will never hit the headline number.</p><h3>Step 1: Whole-program view (Nsight Systems, PyTorch Profiler trace)</h3><p>Ask first: <strong>is the GPU busy?</strong> Look for gaps between kernels, CPU-side stalls, syncs and memcpys.</p><p>If you see many tiny kernels with empty gaps, it is <strong>launch-bound</strong>. Stop here, because the roofline cannot help with kernels that are not running.</p><h3>Step 2: Rank the kernels (PyTorch Profiler)</h3><p>If the GPU is busy, find where the time goes. Sort by GPU time, take the top few kernels, and map them back to modules or ops. The biggest ones decide the end-to-end number.</p><h3>Step 3: Roofline per kernel (Nsight Compute)</h3><p>For each hot kernel, get its FLOPs and bytes moved, compute its <strong>arithmetic intensity</strong>, and compare it to the ridge point. Then compare achieved FLOPS and achieved bandwidth against the two roofs.</p><h3>Step 4: What to do next in each case</h3><p><strong>Memory-bandwidth-bound</strong> (left of the ridge). Low FLOPS is expected, so reduce bytes or raise intensity:</p><ul><li>Fuse ops so intermediates are not written to and read from HBM again (torch.compile, fused attention).</li><li>Use lower precision or quantization.</li><li>Raise the batch size to increase weight reuse.</li><li>If it is far below the bandwidth roof, check coalescing, L2 hit rate and cache reuse.</li></ul><p><strong>Compute-bound</strong> (right of the ridge). Check how close it is to the compute roof:</p><ul><li>Near the roof: little left to gain, so reduce FLOPs (smaller model, sparsity, better algorithm).</li><li>Well below the roof: confirm tensor cores are used, switch to FP16/BF16/FP8, make shapes tile-friendly (multiples of 8 or 16), and inspect occupancy, pipe utilization, warp stalls and clock throttling.</li></ul><p><strong>Below both roofs.</strong> This points to latency, occupancy or small-problem inefficiency. Nsight Compute’s stall reasons and occupancy sections are the next stop.</p><p><strong>Launch-bound.</strong> The kernels are fine and the problem is feeding them:</p><ul><li>Use <strong>CUDA Graphs</strong>, or torch.compile with mode=&quot;reduce-overhead&quot;.</li><li>Fuse small ops into fewer kernels.</li><li>Batch more work per launch.</li><li>Remove syncs such as .item() and .cpu(), and cut Python overhead.</li></ul><h3>Step 5: Re-measure</h3><p>After each fix, re-profile and compare <strong>end-to-end</strong> time, not just one kernel. Fixing one bottleneck often exposes the next.</p><h3>The whole experiment in one view</h3><ul><li><strong>Matmul, 21.6 TFLOPS:</strong> compute-bound, AI ≈ 1365, tensor-core kernel. Little headroom, so look at clocks and tile choices.</li><li><strong>Vector add, 252 GB/s:</strong> memory-bound, AI ≈ 0.17, about 79% of bandwidth. Fuse it with neighbors or cut bytes.</li><li><strong>1000 tiny ops:</strong> launch-bound, 3.5 µs of GPU work inside about 7.8 µs per op. Use CUDA Graphs or fusion.</li></ul><h3>Key takeaways</h3><ol><li><strong>Low FLOPS is a symptom, not a diagnosis.</strong> It has at least three different causes.</li><li><strong>FLOPs is a count, FLOPS is a rate.</strong> Achieved FLOPS is work divided by time.</li><li><strong>A kernel is a function that runs on the GPU</strong>, not the OS kernel.</li><li><strong>Arithmetic intensity (FLOPs per byte) decides which roof applies.</strong> Memory-bound kernels will never reach peak FLOPS, and that is fine.</li><li><strong>The roofline cannot see idle time.</strong> Use a timeline first to rule out launch-bound behavior.</li><li><strong>Measure, then fix, then re-measure.</strong> Each bottleneck has a different remedy, so guessing wastes time.</li></ol><h3>Try it yourself</h3><ol><li>Open a Kaggle notebook and enable a GPU accelerator.</li><li>Paste the benchmark above and compare your numbers with your GPU’s spec sheet.</li><li>Run the profiler cell and find the three kernels in the table.</li><li>Open trace.json in Perfetto and look at the gaps.</li></ol><p>Once you have seen all three bottlenecks with your own eyes, the interview question stops being jargon and becomes a checklist.</p><p><em>If this helped, share it with a friend who is preparing for AI infrastructure or performance engineering interviews.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=966d2498ff54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serving LLMs on Two Free Tesla T4s: A Measurement Study of Batching, KV Cache, Quantization and…]]></title>
            <link>https://medium.com/@allam.satyanarayana/serving-llms-on-two-free-tesla-t4s-a-measurement-study-of-batching-kv-cache-quantization-and-6528581f392c?source=rss-6f161f7e9dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/6528581f392c</guid>
            <category><![CDATA[torch]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[kv-cache]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[kaggle]]></category>
            <dc:creator><![CDATA[Allam Satyanarayana]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 02:11:49 GMT</pubDate>
            <atom:updated>2026-10-20T02:11:49.534Z</atom:updated>
            <content:encoded><![CDATA[<h3>Serving LLMs on Two Free Tesla T4s: A Measurement Study of Batching, KV Cache, Quantization and Tensor Parallelism</h3><h3>What a 1.5B and a 7B model taught me about GPU inference, using only a free Kaggle notebook and vLLM</h3><h3>Abstract</h3><p>I wanted to understand how LLM inference servers behave, not by reading about prefill, decode, KV cache and batching, but by measuring them. So I built a small, fully instrumented lab on a free Kaggle notebook with two NVIDIA Tesla T4 GPUs, served models with <strong>vLLM 0.32.0</strong>, and drove them with my own streaming load generator that records time to first token (TTFT), inter-token latency (ITL), per-user speed and aggregate throughput.</p><p>Five experiments, four server configurations, and one very instructive dependency crash later, these are the findings:</p><ol><li><strong>Decode speed follows bytes, not parameters.</strong> A 1.5B model in fp16 (≈3 GB of weights) decoded at 53 tokens/s for a single user. A 7B model in 4-bit AWQ (≈4.2 GB, my estimate) decoded at 35 tokens/s. That is 5× the parameters for only 1.5× the slowdown. Both landed at roughly half of the theoretical memory-bandwidth ceiling.</li><li><strong>Batching is almost free throughput.</strong> Going from 1 to 32 concurrent users raised aggregate throughput <strong>11.7×</strong> (51.6 → 605.9 tokens/s) while the per-step latency grew only <strong>2.3×</strong> (18.7 → 43.5 ms).</li><li><strong>A too-small batch limit creates a queue, not a slowdown.</strong> Capping the server at 4 concurrent sequences flattened throughput at ~200 tokens/s and pushed median TTFT at 32 users to <strong>17.7 s</strong> (vs 1.2 s with 64 slots). The queueing delay was predictable from first principles to within roughly 6–16%.</li><li><strong>Prefill is a separate cost, and it hurts everyone.</strong> TTFT grew from 0.08 s to 0.41 s to 1.7 s as prompts grew from 50 to 400 to 1,500 words. At the longest prompt, the median ITL jumped from ~16 ms to 84 ms.</li><li><strong>Tensor parallelism makes a model fit; it does not make it free.</strong> A 7B fp16 model (≈15 GB, too big for one T4 in practice) ran across both GPUs at ~22–26 tokens/s per user, somewhat below the 4-bit single-GPU run (28–32 tokens/s at the same loads), but one data point (single user) was strongly anomalous and I could not explain it.</li><li><strong>My own measurements were noisier than I expected.</strong> Identical load levels on identically configured servers differed by up to 6–8× in p95 TTFT between runs. I report this openly because it changes how some results should be read.</li></ol><p>Everything here comes from one notebook run, and I have tried to mark clearly what was measured, what was derived, and what is a hypothesis I did not test.</p><h3>1. Introduction</h3><h3>1.1 Why this study</h3><p>Most explanations of LLM serving stop at slogans: “decode is memory-bound”, “batching improves throughput”, “quantization helps”. They are true, but slogans do not tell you how much. How many tokens per second should you expect on a given GPU? At how many users does latency start to hurt? What happens when you set one flag wrong?</p><p>I wanted numbers I produced myself, on hardware anyone can access for free.</p><h3>1.2 Why Kaggle and the T4</h3><p>Kaggle notebooks offer a free GPU option with <strong>two Tesla T4s</strong> (about 15 GB of usable memory each). Kaggle advertises a weekly GPU quota (commonly cited as about 30 hours, though the exact number is not in Kaggle’s documentation, so check your own account).</p><p>The T4 is an old data-center GPU (Turing architecture, compute capability 7.5). That is a feature for a learning project: it is slow enough that bottlenecks are easy to see, and memory-constrained enough that quantization and tensor parallelism are not academic.</p><p>The trade-off is that a notebook gives you no root access, no Docker and no Kubernetes. This study therefore covers the <strong>inference engine</strong> side of the problem. The production-infrastructure side (autoscaling, ingress, gateways) needs a different environment and is future work.</p><h3>1.3 Research questions</h3><p>I wrote a hypothesis down before each experiment (they are in the notebook itself):</p><p>#QuestionHypothesisRQ1How do throughput and latency change as concurrent users increase?Per-user speed drops, total throughput climbs a lotRQ2How does prompt length affect latency?Long prompts stress compute (prefill) and hurt TTFT; long outputs stress memory bandwidth (decode)RQ3What happens when the server’s concurrent-sequence limit is too low?Extra users queue; TTFT explodes while throughput plateaus earlyRQ4What does 4-bit quantization buy?Fewer bytes cross the memory bus, so decode is faster per parameterRQ5What does tensor parallelism across two T4s cost?A model that does not fit on one GPU runs, but communication over PCIe prevents a 2× gain</p><h3>2. Background and definitions</h3><p><strong>Two phases of generation.</strong> An LLM request has a <em>prefill</em> phase, where the whole prompt is processed in parallel (compute-bound), followed by a <em>decode</em> phase, where tokens are produced one at a time and each step must read all model weights from memory (memory-bound).</p><p><strong>The napkin ceiling.</strong> Because each decode step reads every weight once, a single stream cannot go faster than:</p><blockquote><em>max tokens/s ≈ memory bandwidth ÷ bytes of weights</em></blockquote><p>The T4’s memory bandwidth is about 320 GB/s (the vendor spec, taken as an assumption here, not measured).</p><p><strong>KV cache.</strong> To avoid recomputing attention for earlier tokens, the server stores a key and a value vector per layer for every token of every active sequence. Its size per token is:</p><blockquote><em>2 (K and V) × layers × KV heads × head dimension × bytes per value</em></blockquote><p><strong>Continuous batching.</strong> vLLM schedules many sequences together at every step. Since decode is memory-bound, reading the weights once to produce tokens for 32 sequences is much cheaper than reading them 32 times.</p><p><strong>Metrics used in this study</strong> (all measured client-side, per streamed request):</p><p>MetricMeaning<strong>TTFT</strong>Time from sending the request to receiving the first content token<strong>ITL</strong>Mean time between subsequent tokens: (end-to-end time − TTFT) ÷ (tokens − 1)<strong>Per-user tokens/s</strong>1 ÷ mean ITL, i.e. the speed one user sees<strong>Aggregate throughput</strong>Total tokens generated ÷ wall-clock time of the whole level<strong>p50 / p95</strong>Median and 95th percentile across requests at a level</p><h3>3. Experimental setup</h3><h3>3.1 Hardware and software</h3><p>ItemValuePlatformKaggle notebook, accelerator “GPU T4 x2”, internet onGPUs2 × Tesla T4, 15,360 MiB each as reported by nvidia-smi; PCIe, no NVLinkGPU architectureTuring, compute capability (7, 5)NVIDIA driver580.178.04 (supports up to CUDA 13.0)Python3.13.15Inference enginevLLM 0.32.0PyTorch2.13.0+cu130Host RAM available at model load3.74 GiB (reported by vLLM)Assumed T4 memory bandwidth320 GB/s (vendor spec)</p><h3>3.2 Models</h3><p>ModelPrecisionApprox. weightsRoleQwen/Qwen2.5–1.5B-Instructfp16≈3.0 GB (checkpoint 2.88 GiB)Baseline, batching and slot experimentsQwen/Qwen2.5–7B-Instruct-AWQ4-bit AWQ≈4.2 GB (my estimate at 0.55 bytes/param)Quantization experimentQwen/Qwen2.5–7B-Instructfp16≈15.2 GB (7.6B × 2 bytes)Tensor-parallel experiment</p><p>The T4 has no native bfloat16 support, so every server was launched with --dtype half (fp16).</p><h3>3.3 Server configurations</h3><p>ExperimentModel--max-num-seqs--max-model-len--gpu-memory-utilizationGPUs1, 21.5B fp166440960.85131.5B fp16<strong>4</strong>40960.85147B AWQ3240960.90157B fp1616<strong>2048</strong>0.90<strong>2 (TP=2)</strong></p><p>Note that several settings differ between experiments, so cross-experiment comparisons are indicative, not controlled.</p><h3>3.4 Workload</h3><ul><li>Prompts: a fixed filler sentence repeated up to the requested number of words, preceded by a random 8-letter tag (explained in Section 4.9).</li><li>Default prompt: 300 words. Output: max_tokens = 128, forced to full length with ignore_eos.</li><li>Concurrency levels: 1, 2, 4, 8, 16, 32 (fewer for the larger models).</li><li>Requests per level: 3 × concurrency, with a minimum of 6.</li><li>One warm-up call (2 requests, 16 tokens each, concurrency 1) before each sweep.</li></ul><h3>4. Methodology: the notebook, cell by cell</h3><p>The notebook has 17 executed code cells. I walk through each one: what it does, why, and what it printed.</p><h3>Cell 1: Environment check</h3><pre>import subprocess, sys<br>print(sys.version)<br>print(subprocess.run([&quot;nvidia-smi&quot;], capture_output=True, text=True).stdout)</pre><p><strong>Purpose.</strong> Confirm which Python is running and that both GPUs are visible before installing anything.</p><p><strong>Output.</strong> Python 3.13.15, and an nvidia-smi table with two Tesla T4s:</p><p>FieldValueMeaningDriver / CUDA580.178.04 / 13.0The CUDA figure is the <em>highest version the driver supports</em>, not what is installedMemory0 MiB / 15,360 MiB (both)Nothing loaded yet, about 15 GB of VRAM per GPUPerf stateP8Idle power state (P0 is maximum performance)Power10 W and 9 W of 70 WIdle drawTemperature39 °C and 41 °CIdleBus IDs00:04.0 and 00:05.0Two separate PCIe devices, which matters for tensor parallelism laterProcessesnoneGPUs free</p><p>nvidia-smi (NVIDIA System Management Interface) is the GPU equivalent of top: it reports memory, utilization, temperature, power and per-process usage.</p><h3>Cell 2: Installing vLLM</h3><pre>!pip install -q vllm</pre><p><strong>Purpose.</strong> Install the inference engine from PyPI.</p><p><strong>What happened.</strong> The install succeeded but ended with a long list of pip dependency-resolver warnings. They looked alarming, so here is what they mean.</p><p>Kaggle’s image ships hundreds of preinstalled packages (RAPIDS, Google Cloud client libraries, gRPC tooling). vLLM needed newer versions of several shared libraries, so pip upgraded them: protobuf to 7.36.2, numba to 0.65.0, cuda-python to 13.4.4, cuda-core to 1.2.2, cuda-toolkit to 13.0.3.0, and opentelemetry-api and opentelemetry-sdk to 1.45.1.</p><p>Each warning line has the same shape: <em>&lt;preinstalled package&gt; requires &lt;older range&gt;, but you have &lt;new version&gt;</em>. The package at the start of the line (for example google-adk or cuml) was a <strong>bystander</strong> that was already installed. It was not being installed by vLLM, it simply had its version requirement broken by the upgrade. None of those packages are used in this study, so the warnings were safe to ignore.</p><h3>Cell 3: Verifying the install</h3><pre>import vllm, torch<br>print(&quot;vllm&quot;, vllm.__version__, &quot;| torch&quot;, torch.__version__)<br>print([torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())])<br>print(&quot;compute capability:&quot;, torch.cuda.get_device_capability(0))</pre><p><strong>Output.</strong></p><pre>vllm 0.32.0 | torch 2.13.0+cu130<br>[&#39;Tesla T4&#39;, &#39;Tesla T4&#39;]<br>compute capability: (7, 5)</pre><p><strong>Observation.</strong> The install upgraded PyTorch to a CUDA 13 build (+cu130). That raised a legitimate worry: newer CUDA builds sometimes drop support for old GPU architectures. This output shows both T4s visible with capability 7.5, but it does not prove kernels run on them. The definitive proof came later, when the server generated tokens.</p><h3>Cell 4: The TorchAudio crash and its fix</h3><pre>!pip uninstall -y torchaudio</pre><p><strong>Output.</strong> Found existing installation: torchaudio 2.11.0+cu128 ... Successfully uninstalled.</p><p><strong>The problem.</strong> My first attempt to launch the server died during imports with:</p><blockquote><em>RuntimeError: Detected that PyTorch and TorchAudio were compiled with different CUDA versions. PyTorch has CUDA version 13.0 whereas TorchAudio has CUDA version 12.8.</em></blockquote><p><strong>Root cause.</strong> Kaggle’s image provided PyTorch, TorchVision and TorchAudio as a matched set built for CUDA 12.8. pip install vllm upgraded only PyTorch (to the CUDA 13 build). TorchAudio checks at import time that its CUDA version matches PyTorch&#39;s and refuses to load otherwise. The transformers library, which vLLM uses to read model configs, imports TorchAudio, so the whole server crashed on the way in. The traceback shows the chain: api_server → vllm.config → transformers → audio_utils → torchaudio → error.</p><p><strong>Fix.</strong> These models are text-only, so removing TorchAudio is enough: transformers tolerates its absence, and the server launched normally afterwards.</p><p><strong>Lesson.</strong> torch, torchvision and torchaudio are built as a matched set. Upgrading one alone is a classic way to break an environment, and it is exactly why production deployments pin a whole container image instead of patching a shared one.</p><h3>Cell 5: Server helper functions</h3><pre>import subprocess, time, os, signal, shlex, sys, requests</pre><pre>PORT = 8000<br>BASE = f&quot;http://127.0.0.1:{PORT}&quot;<br>LOG = &quot;/kaggle/working/server.log&quot;<br>SERVER = {&quot;proc&quot;: None}</pre><pre>def tail_log(n=40):<br>    with open(LOG) as f:<br>        return &quot;&quot;.join(f.readlines()[-n:])</pre><pre>def stop_server():<br>    p = SERVER[&quot;proc&quot;]<br>    if p and p.poll() is None:<br>        os.killpg(os.getpgid(p.pid), signal.SIGTERM)<br>        try:<br>            p.wait(timeout=30)<br>        except subprocess.TimeoutExpired:<br>            os.killpg(os.getpgid(p.pid), signal.SIGKILL)<br>    SERVER[&quot;proc&quot;] = None<br>    time.sleep(3)</pre><pre>def start_server(model, extra_args=&quot;&quot;, timeout=900):<br>    stop_server()<br>    cmd = (f&quot;{sys.executable} -m vllm.entrypoints.openai.api_server &quot;<br>           f&quot;--model {model} --port {PORT} --dtype half {extra_args}&quot;)<br>    print(&quot;$&quot;, cmd)<br>    logf = open(LOG, &quot;w&quot;)<br>    SERVER[&quot;proc&quot;] = subprocess.Popen(shlex.split(cmd), stdout=logf,<br>                                      stderr=subprocess.STDOUT, preexec_fn=os.setsid)<br>    t0 = time.time()<br>    while time.time() - t0 &lt; timeout:<br>        if SERVER[&quot;proc&quot;].poll() is not None:<br>            print(&quot;Server exited. Last log lines:\n&quot;, tail_log(40))<br>            return False<br>        try:<br>            if requests.get(f&quot;{BASE}/health&quot;, timeout=2).status_code == 200:<br>                print(f&quot;Ready in {time.time() - t0:.0f}s  &lt;- this is your cold-start time&quot;)<br>                return True<br>        except requests.RequestException:<br>            pass<br>        time.sleep(5)<br>    print(&quot;Timed out. Last log lines:\n&quot;, tail_log(40))<br>    return False</pre><p><strong>Purpose.</strong> Run the inference server as a background process so the notebook stays usable and so the server can be restarted with different settings for each experiment.</p><p><strong>Design decisions, line by line:</strong></p><ul><li><strong>LOG file.</strong> Server output goes to a file instead of the notebook, which keeps cell output clean and lets tail_log show the last lines when something fails. This is what made the TorchAudio crash diagnosable.</li><li><strong>preexec_fn=os.setsid</strong> puts the server and its worker processes in their own process group. stop_server can then kill the whole group with os.killpg. Without this, the tensor-parallel run (which spawns worker processes) could leave orphaned processes holding GPU memory.</li><li><strong>SIGTERM first, SIGKILL after 30 s</strong> gives the server a chance to shut down cleanly.</li><li><strong>start_server polls </strong><strong>/health</strong> every 5 seconds and checks the process is still alive on each loop, so a crash is reported immediately instead of waiting for the full timeout.</li><li><strong>--dtype half</strong> is hard-coded because the T4 lacks native bfloat16 (the default for Qwen2.5).</li><li><strong>Timing.</strong> The “Ready in N s” message measures the <strong>cold-start time</strong>, the number that matters later when thinking about autoscaling.</li></ul><h3>Cell 6: First server launch</h3><pre>MODEL = &quot;Qwen/Qwen2.5-1.5B-Instruct&quot;<br>ok = start_server(MODEL, &quot;--max-model-len 4096 --gpu-memory-utilization 0.85 --max-num-seqs 64 --tensor-parallel-size 1&quot;)</pre><p><strong>Output.</strong> Ready in 160s.</p><p><strong>Flag meanings.</strong></p><p>FlagEffect--max-model-len 4096Longest context (prompt + output) any request may use--gpu-memory-utilization 0.85Fraction of GPU memory vLLM may claim; leftover after weights becomes KV cache--max-num-seqs 64Maximum sequences scheduled together in one step (the &quot;batch slots&quot;)--tensor-parallel-size 1Use one GPU only, so the second T4 sat idle in this configuration</p><h3>Cell 7: Smoke test</h3><pre>r = requests.post(f&quot;{BASE}/v1/chat/completions&quot;, json={<br>    &quot;model&quot;: MODEL,<br>    &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Explain what a GPU is in two sentences.&quot;}],<br>    &quot;max_tokens&quot;: 80})<br>print(r.json()[&quot;choices&quot;][0][&quot;message&quot;][&quot;content&quot;])<br>print(r.json()[&quot;usage&quot;])</pre><p><strong>Output.</strong> The model returned a coherent explanation of a GPU, with usage of <strong>39 prompt tokens and 72 completion tokens</strong>. The server speaks the OpenAI-compatible chat API, so the same client code works against vLLM, llama.cpp or a hosted API. Completion stopped at 72 tokens, below the 80-token cap, meaning the model ended naturally.</p><h3>Cell 8: How did the engine spend GPU memory?</h3><pre>print(&quot;&quot;.join(l for l in open(LOG) if &quot;KV cache&quot; in l or &quot;GiB&quot; in l)[:3000])</pre><p><strong>Purpose.</strong> Filter the server log for memory-related lines. This is the most informative single cell in the notebook.</p><p><strong>What the log said:</strong></p><p>Log line (abridged)MeaningCheckpoint size: 2.88 GiB. Available RAM: 3.74 GiBWeights on disk; small host RAMModel loading took 2.98 GiB memory and 27.84 secondsWeights resident on the GPUGraph capturing finished in 7 secs, took 0.13 GiBCUDA graphs (pre-recorded GPU work) were capturedAvailable KV cache memory: 8.67 GiBEverything left after weights, activations and graphs<strong>GPU KV cache size: 324,640 tokens</strong>Cache capacity, in tokens<strong>Maximum concurrency for 4,096 tokens per request: 79.26x</strong>The cache holds ~79 full-length conversationsFree memory 14.46/14.56 GiB; desired 12.38 GiB (0.85)The budget the flag created3.13 GiB weights+non-torch, 0.58 GiB peak activation, 0.08 GiB CUDA graphThe non-cache costs</p><p><strong>Key insight.</strong> The engine does not choose the KV cache size directly. It computes a budget (0.85 × 14.56 GiB = 12.38 GiB), subtracts weights, activation scratch space and graph memory, and gives <strong>all the remainder to the KV cache</strong>. That is why --gpu-memory-utilization is really a &quot;how much cache&quot; knob.</p><p><strong>Cross-check.</strong> 8.67 GiB ÷ 324,640 tokens = about <strong>28.7 KB per token</strong>, matching the napkin formula in Cell 9 (28,672 bytes). And 324,640 ÷ 4,096 = 79.26, matching the log’s concurrency figure exactly.</p><p><strong>A note on a timeline.</strong> After the weights were resident (log time 00:04:25), another ~62 seconds passed before the engine’s last startup line (00:05:27). Graph capture itself was reported as only 7 s and 3 s, so most of the remaining time went into other startup work that the log does not break down.</p><p><strong>Idle-window log lines.</strong> The last two lines show Avg generation throughput: 7.2 tokens/s and then 0.0. These are averages over a 10-second window. My single short smoke-test request fell inside one window, so 7.2 tokens/s is <strong>not</strong> the server&#39;s speed, it is one request&#39;s tokens divided by ten seconds. This is a reminder to measure speed with a proper benchmark, not log lines.</p><h3>Cell 9: Napkin math, predicting before measuring</h3><pre>from transformers import AutoConfig</pre><pre>def napkin(model, params_b, bytes_per_param=2, bw_gbs=320):<br>    cfg = AutoConfig.from_pretrained(model)<br>    head_dim = cfg.hidden_size // cfg.num_attention_heads<br>    kv_per_token = 2 * cfg.num_hidden_layers * cfg.num_key_value_heads * head_dim * 2<br>    weights_gb = params_b * bytes_per_param<br>    print(f&quot;weights                ~ {weights_gb:.1f} GB&quot;)<br>    print(f&quot;KV cache per token     ~ {kv_per_token/1024:.0f} KB&quot;)<br>    print(f&quot;KV for one 4096 ctx    ~ {kv_per_token*4096/1e9:.2f} GB per sequence&quot;)<br>    print(f&quot;decode ceiling (1 user)~ {bw_gbs/weights_gb:.0f} tok/s  (real number will be lower)&quot;)</pre><pre>napkin(MODEL, 1.5)</pre><p><strong>How it works.</strong> It reads the model’s architecture from its config (layers, KV heads, hidden size, attention heads), computes the KV bytes per token with the formula from Section 2, and divides bandwidth by weight bytes to get the ceiling.</p><p><strong>Output for the 1.5B model:</strong></p><pre>weights                ~ 3.0 GB<br>KV cache per token     ~ 28 KB<br>KV for one 4096 ctx    ~ 0.12 GB per sequence<br>decode ceiling (1 user)~ 107 tok/s  (real number will be lower)</pre><p>The 28 KB figure matches what the engine measured in Cell 8. This is the part I find most satisfying: <strong>a formula on paper predicted what the engine allocated</strong>, which means the same arithmetic can size a deployment before renting any hardware.</p><p>(A harmless stderr warning appeared about unauthenticated Hugging Face Hub requests, since no HF_TOKEN was set.)</p><h3>Cell 10: The benchmark client</h3><pre>import asyncio, aiohttp, json, random, string<br>import numpy as np, pandas as pd<br>import matplotlib.pyplot as plt</pre><pre>FILLER = (&quot;The quick brown fox jumps over the lazy dog. &quot; * 200).split()</pre><pre>def make_prompt(n_words):<br>    tag = &quot;&quot;.join(random.choices(string.ascii_lowercase, k=8))<br>    return f&quot;[{tag}] Summarize the following text in detail:\n&quot; + &quot; &quot;.join(FILLER[:n_words])</pre><pre>async def one_request(session, model, prompt, max_tokens):<br>    payload = {&quot;model&quot;: model, &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>               &quot;max_tokens&quot;: max_tokens, &quot;temperature&quot;: 0.7, &quot;stream&quot;: True,<br>               &quot;ignore_eos&quot;: True}<br>    t0 = time.perf_counter(); ttft = None; n = 0<br>    async with session.post(f&quot;{BASE}/v1/chat/completions&quot;, json=payload) as resp:<br>        resp.raise_for_status()<br>        async for raw in resp.content:<br>            line = raw.decode().strip()<br>            if not line.startswith(&quot;data:&quot;):<br>                continue<br>            data = line[5:].strip()<br>            if data == &quot;[DONE]&quot;:<br>                break<br>            chunk = json.loads(data)<br>            if chunk.get(&quot;choices&quot;) and chunk[&quot;choices&quot;][0][&quot;delta&quot;].get(&quot;content&quot;):<br>                if ttft is None:<br>                    ttft = time.perf_counter() - t0<br>                n += 1<br>    return {&quot;ttft&quot;: ttft, &quot;e2e&quot;: time.perf_counter() - t0, &quot;tokens&quot;: n}</pre><pre>async def run_level(model, concurrency, n_requests, prompt_words, max_tokens):<br>    sem = asyncio.Semaphore(concurrency)<br>    timeout = aiohttp.ClientTimeout(total=1800)<br>    async with aiohttp.ClientSession(timeout=timeout, connector=aiohttp.TCPConnector(limit=0)) as s:<br>        async def task():<br>            async with sem:<br>                return await one_request(s, model, make_prompt(prompt_words), max_tokens)<br>        t0 = time.perf_counter()<br>        results = await asyncio.gather(*[task() for _ in range(n_requests)])<br>        wall = time.perf_counter() - t0<br>    ok = [r for r in results if r[&quot;ttft&quot;] is not None and r[&quot;tokens&quot;] &gt; 1]<br>    ttft = np.array([r[&quot;ttft&quot;] for r in ok])<br>    itl = np.array([(r[&quot;e2e&quot;] - r[&quot;ttft&quot;]) / (r[&quot;tokens&quot;] - 1) for r in ok])<br>    return {&quot;concurrency&quot;: concurrency, &quot;requests&quot;: len(ok),<br>            &quot;throughput_tok_s&quot;: sum(r[&quot;tokens&quot;] for r in ok) / wall,<br>            &quot;ttft_p50&quot;: np.percentile(ttft, 50), &quot;ttft_p95&quot;: np.percentile(ttft, 95),<br>            &quot;itl_ms_p50&quot;: np.percentile(itl, 50) * 1000,<br>            &quot;per_user_tok_s&quot;: 1 / itl.mean()}</pre><pre>async def sweep(model, levels=(1, 2, 4, 8, 16, 32), prompt_words=300, max_tokens=128, reqs_per_level=3):<br>    await run_level(model, 1, 2, prompt_words, 16)  # warm-up<br>    rows = []<br>    for c in levels:<br>        row = await run_level(model, c, max(c * reqs_per_level, 6), prompt_words, max_tokens)<br>        rows.append(row)<br>        print({k: (round(v, 2) if isinstance(v, float) else v) for k, v in row.items()})<br>    return pd.DataFrame(rows)</pre><p>(A plot() helper that draws the three-panel figures used below is also defined in this cell.)</p><p><strong>Design decisions, explained:</strong></p><ul><li><strong>Streaming (</strong><strong>&quot;stream&quot;: True).</strong> TTFT and ITL can only be measured if tokens arrive incrementally. A non-streaming client sees only the total time.</li><li><strong>Server-sent events parsing.</strong> Each line beginning with data: carries a JSON chunk; [DONE] ends the stream. TTFT is the time to the first chunk with non-empty content. Each content chunk is counted as one token.</li><li><strong>Random tag at the start of every prompt.</strong> vLLM can reuse the KV cache for prompts that share a prefix (the engine logs a prefix-cache hit rate, which suggests this feature is active by default in this version). A random tag in the first tokens makes every prompt unique from its first block, so the benchmark measures real prefill work instead of cache hits.</li><li><strong>ignore_eos.</strong> A vLLM extension that forces every request to generate exactly max_tokens. Without it, requests would stop at random lengths, which makes throughput numbers incomparable.</li><li><strong>Closed-loop concurrency with a semaphore.</strong> At most concurrency requests are in flight; as soon as one finishes, the next starts. Total requests per level is max(3 × concurrency, 6), so levels 1, 2, 4, 8, 16, 32 send 6, 6, 12, 24, 48 and 96 requests.</li><li><strong>Warm-up.</strong> One tiny run (2 requests, 16 tokens, concurrency 1) before measuring. As the results will show, this turned out to be too small.</li><li><strong>Metrics.</strong> Throughput is total tokens over the level’s wall time. Per-user speed is 1 / mean(ITL). The reported itl_ms_p50 is the <em>median</em>, so the two can differ slightly when the distribution is skewed.</li></ul><h3>Cell 11: Experiment 1 call</h3><pre>results = {}<br>results[&quot;1.5B fp16&quot;] = await sweep(MODEL)<br>plot(results)<br>results[&quot;1.5B fp16&quot;]</pre><p>Results are in Section 5.1.</p><h3>Cell 12: Reading the engine’s own metrics</h3><pre>txt = requests.get(f&quot;{BASE}/metrics&quot;).text<br>keys = (&quot;num_requests_running&quot;, &quot;num_requests_waiting&quot;, &quot;kv_cache_usage&quot;, &quot;gpu_cache_usage&quot;,<br>        &quot;preemption&quot;, &quot;time_to_first_token_seconds_sum&quot;, &quot;time_to_first_token_seconds_count&quot;)<br>for l in txt.splitlines():<br>    if not l.startswith(&quot;#&quot;) and any(k in l for k in keys):<br>        print(l)</pre><p><strong>Purpose.</strong> vLLM exposes Prometheus-format metrics at /metrics. This is what a production monitoring stack would scrape. Results in Section 5.2.</p><h3>Cells 13 to 16: Experiments 2 to 5</h3><p>Each restarts or reuses the server with different flags and reruns the sweep. The exact code and commands are shown next to each experiment in Section 5.</p><h3>Cell 17: Cleanup</h3><pre>stop_server()</pre><p>Releases the GPUs. On Kaggle the weekly GPU quota keeps counting while the session is open, so shutting down the server and the session matters.</p><h3>5. Results and observations</h3><h3>5.1 Experiment 1: the batching curve (RQ1)</h3><p><strong>Setup.</strong> Qwen2.5–1.5B, fp16, 1 GPU, 64 slots, 300-word prompts, 128 output tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jTGjRBhmd3A-Xa4SgIYtjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5HNgUJOdP6648pSsRF4FPQ.png" /><figcaption>Baseline sweep of Qwen2.5–1.5B fp16. Left: total throughput. Middle: p95 TTFT. Right: per-user speed.</figcaption></figure><p><strong>Observations.</strong></p><ol><li><strong>Hypothesis supported.</strong> Aggregate throughput rose from 51.6 to 605.9 tokens/s (<strong>11.7×</strong>) while per-user speed fell from 53.3 to 22.9 tokens/s (down 57%).</li><li><strong>Batching is nearly free at the engine level.</strong> Median ITL, the time of one decode step as seen by each stream, grew only from 18.7 ms to 43.5 ms (<strong>2.3×</strong>) while the number of sequences per step grew 32×. Reading the weights once per step is the shared cost, so adding sequences is cheap until compute starts to matter. (Figure 6 shows ITL for all configurations.)</li><li><strong>Scaling efficiency fell steadily.</strong> Relative to one user, scaling efficiency (throughput gain ÷ users) was 95% at 2 users, 74% at 4, 63% at 8, 48% at 16 and 37% at 32. Efficiency drops because the step time itself grows with batch size.</li><li><strong>A step-time sanity check.</strong> If every step yields one token per active sequence, throughput should be about users ÷ ITL. That predicts 53.5 tok/s at 1 user and 735 tok/s at 32 users, versus measured 51.6 (96%) and 605.9 (82%). The gap at higher concurrency (down to about 68% at 4 to 16 users) is time not spent on decode steps, for example prefilling newly arrived requests, plus client overhead. I did not isolate which.</li><li><strong>The knee was not reached.</strong> Throughput was still rising at 32 users, and the server had 64 slots. A real capacity plan would extend the sweep (64, 128 users) until throughput flattens or p95 TTFT crosses an SLO.</li><li><strong>Measured single-user speed versus the ceiling.</strong> The napkin ceiling was 107 tok/s; measured per-user speed at one user was <strong>53.3 tok/s, about 50%</strong>. Multiplying weights by speed (3.0 GB × 53.3) implies an effective bandwidth of roughly <strong>160 GB/s, about half the 320 GB/s spec</strong>. The gap is typical: kernels do not reach peak bandwidth, and each step also reads the KV cache, runs attention and sampling, and launches many small kernels.</li></ol><p><strong>Caveats I noticed (important):</strong></p><ul><li><strong>Per-user speed at 2 users (59.5) was higher than at 1 user (53.3).</strong> Adding load cannot make each stream faster in steady state. Levels 1 and 2 each had only 6 requests, so this is likely noise or warm-up, but see the cross-experiment comparison in Section 5.4 for evidence that it is systematic.</li><li><strong>p95 TTFT is not monotonic</strong>: it peaked at 16 users (3.53 s) and fell at 32 (2.21 s), while p50 plateaued near 1.17 s. I did not investigate; with 3 waves of requests per level and one run per point, burst structure and small samples are plausible contributors.</li><li><strong>p95 over 6 requests is essentially the maximum.</strong> At 1 and 2 users the “p95” is one slow request away from changing.</li></ul><h3>5.2 The engine’s own view (metrics cell)</h3><p>Taken after Experiment 1 finished, with the server idle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XHTJTlkEqpplpGi6fLsQA.png" /></figure><p><strong>Observations.</strong></p><ul><li><strong>The request count reconciles exactly.</strong> My client sent 6 + 6 + 12 + 24 + 48 + 96 = 192 measured requests, plus 2 warm-up requests and 1 smoke-test request = <strong>195</strong>. The server-side count matches.</li><li><strong>Mean server-side TTFT</strong> over the whole run was 230.17 ÷ 195 = <strong>1.18 s</strong>.</li><li><strong>Zero preemptions confirms the KV-cache analysis.</strong> The cache held 324,640 tokens; at 32 users and roughly 500 tokens per request (my estimate; I did not measure prompt token counts), only on the order of 5% of the cache was needed. For this model at these concurrencies, KV cache was <strong>not</strong> the bottleneck.</li><li><strong>A gotcha for dashboards.</strong> Series ending in _created (for example vllm:num_preemptions_created = 1.79e9) are Unix timestamps of when the metric object was created, not counts. Alerting on them would be a mistake.</li></ul><h3>5.3 Experiment 2: prefill versus decode (RQ2)</h3><p><strong>Setup.</strong> Back on the 64-slot server (Experiment 2 ran before Experiment 3 in the notebook), 4 concurrent users, 12 requests, only 16 output tokens, with prompt length varied.</p><pre>rows = []<br>for words in (50, 400, 1500):<br>    r = await run_level(MODEL, 4, 12, words, 16)<br>    r[&quot;prompt_words&quot;] = words<br>    rows.append(r)<br>pd.DataFrame(rows)[[&quot;prompt_words&quot;, &quot;ttft_p50&quot;, &quot;ttft_p95&quot;, &quot;itl_ms_p50&quot;]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0M8INj28GQ-NQ8KeusEMsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y3FKWZHF7huyDWwEMO6I9g.png" /><figcaption>TTFT and median ITL as prompt length grows.</figcaption></figure><p><strong>Observations.</strong></p><ol><li><strong>TTFT scales with prompt length, as expected for compute-bound prefill.</strong> Going from 50 to 400 words (8×) raised median TTFT 4.9×; going from 400 to 1,500 words (3.75×) raised it 4.2×. The first step is sub-linear because a fixed overhead (HTTP, scheduling, a first decode step) dominates short prompts.</li><li><strong>Overall, a 30× longer prompt cost 20.7× more TTFT.</strong> Prompt length is the main driver of time-to-first-token in this setup. I did not measure token counts, so “words” is only a proxy.</li><li><strong>Prefill interferes with decoding.</strong> Median ITL was flat at ~16–17 ms for the 50- and 400-word prompts, then jumped to <strong>84 ms at 1,500 words</strong>, a 5× slowdown in the <em>decode</em> phase. A plausible reading: four requests arrive together, their long prefills occupy the GPU, and any request already decoding has its steps stretched while others prefill. This is consistent with the motivation for chunked prefill and prefill/decode disaggregation in production systems, but I did not test it. The test is short too (only 15 inter-token intervals per request), so this number is noisy.</li><li><strong>Hypothesis supported in direction.</strong> I tested the prefill half (long prompts, short output). I did not run the mirror case (short prompt, long output) as a separate experiment; the baseline sweep with 128 output tokens already behaves as the decode-dominated case.</li></ol><h3>5.4 Experiment 3: too few batch slots (RQ3)</h3><p><strong>Setup.</strong> Same model and workload, but the server restarted with --max-num-seqs 4.</p><pre>ok = start_server(MODEL, &quot;--max-model-len 4096 --gpu-memory-utilization 0.85 --max-num-seqs 4&quot;)<br>results[&quot;1.5B, 4 slots&quot;] = await sweep(MODEL)<br>plot(results)</pre><p>The restart took <strong>115 s</strong> (versus 160 s for the first launch).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N49hNSBvLOkrEPcjzQNApQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKoNXretzS6H_63nc7yT_w.png" /><figcaption>4 slots (orange) versus 64 slots (blue). Throughput plateaus at about 200 tok/s and p95 TTFT climbs to about 18 s.</figcaption></figure><p><strong>Observations.</strong></p><ol><li><strong>Hypothesis strongly supported.</strong> Throughput plateaus at ~200 tokens/s from 4 users onward (193 → 194 → 200 → 200). The plateau is exactly four streams times about 50 tokens/s each.</li><li><strong>Per-user speed stays flat at ~54–55 tokens/s</strong> regardless of how many users arrive, because at most four sequences are ever decoding. Compare this with 64 slots at 32 users, where each user got 22.9 tokens/s.</li><li><strong>The cost moves into the queue.</strong> Median TTFT rose from 0.32 s (4 users) to 2.86, 7.74 and <strong>17.72 s</strong> (8, 16, 32 users). The total work is the same, but users wait instead of sharing.</li><li><strong>The queueing delay can be predicted.</strong> A request’s service time is roughly 128 tokens × 17.84 ms + 0.1 s prefill ≈ 2.4 s. With 4 slots, a request that arrives with c − 4 others ahead of it should wait about (c − 4) ÷ 4 service times:</li></ol><p>UsersPredicted TTFT (s)Measured p50 (s)82.42.86167.17.743216.717.72</p><p>The prediction is within about 6–16% (the larger deviation is at the shortest queue, where a small absolute difference dominates). This is a closed-queue behavior, not mysterious overload. 5. <strong>Head-to-head at 32 users:</strong> 200 versus 606 tokens/s (3.0× less throughput), TTFT p50 17.7 s versus 1.2 s (15× worse), but per-user speed 55 versus 23 tokens/s (2.4× better for users who got a slot). Which of these matters is a product decision, not an engineering fact.</p><p><strong>An inconsistency worth reporting.</strong> For 1, 2 and 4 users the two servers should behave identically, because the slot limit is not binding. Yet at 4 users the 64-slot server measured <strong>152 tok/s with p95 TTFT 2.52 s</strong>, while the 4-slot server measured <strong>193 tok/s with p95 TTFT 0.33 s</strong>. At 2 users, p95 TTFT was 1.13 s versus 0.18 s. Same model, same flags that matter, same load: a 6–8× difference in tail latency. The most plausible explanation is that Experiment 1 ran right after a fresh server start with a minimal warm-up (one concurrency-1 call), so its low-concurrency levels paid for first-use effects such as batch shapes not yet exercised. I did not confirm this. The practical consequence is that <strong>the low-concurrency points in Experiment 1 are probably pessimistic</strong>, and that the scaling-efficiency numbers in Observation 3 of Section 5.1 would look better with a proper warm-up.</p><h3>5.5 Experiment 4: quantization (RQ4)</h3><p><strong>Setup.</strong> Qwen2.5–7B-Instruct-AWQ on one T4, 32 slots.</p><pre>MODEL_7B_AWQ = &quot;Qwen/Qwen2.5-7B-Instruct-AWQ&quot;<br>ok = start_server(MODEL_7B_AWQ, &quot;--quantization awq --max-model-len 4096 --gpu-memory-utilization 0.90 --max-num-seqs 32&quot;)<br>napkin(&quot;Qwen/Qwen2.5-7B-Instruct&quot;, 7.6, bytes_per_param=0.55)<br>results[&quot;7B AWQ 4-bit&quot;] = await sweep(MODEL_7B_AWQ, levels=(1, 2, 4, 8, 16))</pre><p>Cold start: <strong>155 s</strong>. Napkin output:</p><pre>weights                ~ 4.2 GB<br>KV cache per token     ~ 56 KB<br>KV for one 4096 ctx    ~ 0.23 GB per sequence<br>decode ceiling (1 user)~ 77 tok/s  (real number will be lower)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrBuCDq-MQFQC9QfEhd7VA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZnY5bnf19A911k7PyW-MhA.png" /><figcaption>The 7B AWQ model (green) added to the earlier curves.</figcaption></figure><p><strong>Observations.</strong></p><ol><li><strong>A 7B model ran on one T4.</strong> In fp16 its weights (about 15.2 GB) would nearly fill the card’s usable 14.56 GiB, leaving no practical room for KV cache or activations. In 4-bit it needed about 4.2 GB. (This fit argument is arithmetic; I did not try fp16 on a single GPU.)</li><li><strong>Speed tracked bytes, not parameters.</strong> The 7B model has 5× the parameters of the 1.5B model but its weights are only about 1.4× larger in bytes. Measured single-user speed was 35.4 versus 53.3 tokens/s, a ratio of <strong>1.50×</strong>; the napkin ceilings (77 versus 107) predict <strong>1.39×</strong>. Parameter count alone would have predicted a 5× gap.</li><li><strong>Same efficiency fraction.</strong> The 7B AWQ model reached 35.4 of a 77 tokens/s ceiling (<strong>46%</strong>), compared with 50% for the 1.5B model. The implied effective bandwidth is about 149 GB/s versus 160 GB/s. Both models used roughly half of the theoretical bandwidth, which is a useful rule of thumb for this GPU and engine. (The 4.2 GB estimate for AWQ weights is mine, so the 46% carries that uncertainty.)</li><li><strong>Prefill is the cost of a bigger model.</strong> Single-user TTFT was 0.31 s versus 0.095 s for the 1.5B model (<strong>3.3×</strong> slower), because prefill is compute-bound and the 7B model does about five times more arithmetic per token, plus dequantization overhead.</li><li><strong>The sweep did not reach saturation.</strong> It stopped at 16 users with throughput still rising (190.6 tok/s, a 5.8× gain over one user) while ITL grew 1.8× (28.0 → 51.1 ms).</li><li><strong>Hypothesis supported.</strong> Fewer bytes per token meant the larger model stayed usable. I did not measure output quality, so the quality side of the trade-off remains unexamined.</li></ol><h3>5.6 Experiment 5: tensor parallelism (RQ5)</h3><p><strong>Setup.</strong> Qwen2.5–7B-Instruct in fp16, split across both T4s (--tensor-parallel-size 2), context limited to 2,048 and 16 slots.</p><pre>MODEL_7B = &quot;Qwen/Qwen2.5-7B-Instruct&quot;<br>ok = start_server(MODEL_7B, &quot;--tensor-parallel-size 2 --max-model-len 2048 --gpu-memory-utilization 0.90 --max-num-seqs 16&quot;, timeout=1500)<br>results[&quot;7B fp16, TP=2&quot;] = await sweep(MODEL_7B, levels=(1, 2, 4, 8))</pre><p>Cold start: <strong>260 s</strong>, the slowest of the four launches (likely reflecting a larger checkpoint and two worker processes; the log excerpt does not break it down).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYmoSQaFUMav6pdEvKO3WA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Gf438KHMBlD8DGKo1yEEA.png" /><figcaption>All four configurations. Red is the 7B fp16 model split across two GPUs.</figcaption></figure><p><strong>Observations.</strong></p><ol><li><strong>The model that does not fit one GPU ran.</strong> Each GPU held about half of the ≈15.2 GB of weights (≈7.6 GB each), which is the whole point of tensor parallelism.</li><li><strong>Steady-state speed was somewhat below the 4-bit single-GPU run.</strong> At 2 to 8 users the TP=2 fp16 server delivered 25.6 to 22.4 tokens/s per user, versus 32.1 to 27.8 for 7B AWQ on one GPU. Aggregate throughput at 8 users was 138 versus 143 tokens/s. So spending two GPUs on fp16 bought roughly what one GPU bought with 4-bit weights, at lower per-user speed and double the hardware.</li><li><strong>Relative to its own napkin ideal, TP=2 held up well.</strong> With weights split across two GPUs, the ideal step time is 7.6 GB ÷ 320 GB/s ≈ 24 ms. The measured 37 ms at 2 users is about 64% of ideal, versus 50% and 47% for the single-GPU runs. Interconnect cost is visible but not catastrophic at these batch sizes; Figure 7 compares ideal and measured step times.</li><li><strong>The single-user result is anomalous and I cannot explain it.</strong> At one user, median ITL was <strong>110 ms</strong> (10 tok/s). At two users it was <strong>37 ms</strong>. A stream getting 3× faster when another user joins is not plausible as a steady-state property. The mean ITL implied by per-user speed (≈98 ms) is below the median (110 ms), so the six requests were not uniformly slow: some decoded noticeably faster than others. That fits a warm-up or clock-ramp effect (GPU power state, first-use initialization of multi-GPU communication), but I did not measure it. I therefore <strong>do not treat the 10 tok/s single-user figure as representative</strong>, and no conclusion about TP latency at batch size 1 should be drawn from it.</li><li><strong>Hypothesis partly tested.</strong> The prediction was that TP “will not be 2× faster than one GPU would be”. Because the 7B fp16 model cannot run on one GPU, the direct comparison is impossible. I also did not run the proposed TP=2-on-the-1.5B-model comparison, where communication overhead is expected to dominate.</li><li><strong>Different settings.</strong> This run used --max-model-len 2048 and 16 slots, unlike the others, so cross-experiment comparisons are indicative only.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ux7u9NTDIHijQbhUrvlSqA.png" /></figure><h3>6. Synthesis</h3><h3>6.1 One table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7-VD8VaMroyxdkXrrngnQ.png" /></figure><p>The 4-slot row’s 47.2 tok/s at one user is likely affected by the same first-level effect discussed in Section 5.4 (its two-user figure was 57.3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c986pnJwe1epjodN5J8haA.png" /></figure><h3>6.2 What the experiments say together</h3><ul><li><strong>Memory bandwidth explains the single-user speed.</strong> The effective bandwidth was roughly 150–160 GB/s for both single-GPU runs, about half of the spec. A rough rule for this stack: expect about half of bandwidth ÷ weight bytes.</li><li><strong>Batching converts spare compute into throughput.</strong> One decode step costs almost the same whether it serves 1 sequence or 32, so aggregate throughput scales far faster than step time.</li><li><strong>The scheduler limit sets the shape of the queue.</strong> --max-num-seqs decides whether overload shows up as slower streams (many slots) or as waiting (few slots). Neither is free.</li><li><strong>Prompt length is a first-class capacity input.</strong> Prefill cost and its interference with decoding mean that a workload with long prompts needs a different configuration than one with short prompts, even at the same request rate.</li><li><strong>Quantization is the cheapest way to fit and speed up.</strong> Tensor parallelism is the way to fit when quantization is not enough, at the price of hardware and cold-start time.</li></ul><h3>7. Threats to validity</h3><p>I would rather list these than have a reader discover them.</p><ol><li><strong>One run per data point.</strong> No repeats, no confidence intervals. The evidence that this matters is in my own data: identical loads differed 6–8× in p95 TTFT between Experiments 1 and 3.</li><li><strong>Warm-up was too small.</strong> Two requests of 16 tokens at concurrency 1 cannot warm every batch shape, and likely contributed to the anomalous low-concurrency points (Experiment 1 at 2 and 4 users; Experiment 5 at 1 user).</li><li><strong>Small samples.</strong> Several levels have only 6 to 12 requests, so p95 is close to the maximum.</li><li><strong>Token counting by chunk.</strong> The client counts streamed content chunks as tokens and does not verify against the server’s usage report. With ignore_eos and a 128-token cap, 128 per request is expected, but I did not check it.</li><li><strong>Synthetic prompts.</strong> The repeated filler sentence is not realistic text, and “words” is only a proxy for tokens.</li><li><strong>Closed-loop load.</strong> Concurrency is held fixed, rather than driving requests at a fixed arrival rate, and all requests at each level start as a simultaneous burst, which affects TTFT tails.</li><li><strong>Uncontrolled settings.</strong> Slots, context length and memory utilization differ between experiments (Section 3.3).</li><li><strong>Assumed bandwidth.</strong> The 320 GB/s figure is the published spec, not a measurement, and the AWQ weight size (≈4.2 GB) is my own estimate.</li><li><strong>No quality evaluation.</strong> I measured speed, not whether 4-bit outputs are as good.</li><li><strong>One machine, one day.</strong> Kaggle’s shared infrastructure may behave differently at other times.</li></ol><h3>8. Practical takeaways for production</h3><ol><li><strong>Size from bytes.</strong> Weights, KV cache per token × context × concurrent users, and a margin. This notebook showed the formula matches what the engine allocates.</li><li><strong>Find the knee with a real sweep.</strong> Extend the concurrency range until throughput flattens or p95 TTFT crosses your target, and set slot limits and replica counts from that, not defaults.</li><li><strong>Do not run with a tiny </strong><strong>--max-num-seqs.</strong> It silently converts load into queueing delay (17.7 s median at 32 users in my run).</li><li><strong>Watch the right signals.</strong> vllm:num_requests_waiting, vllm:kv_cache_usage_perc, vllm:num_preemptions_total and TTFT. Remember that _created series are timestamps.</li><li><strong>Plan for slow starts.</strong> Cold starts here ranged from 115 s to 260 s. Autoscaling must act on queue depth early and scale down slowly.</li><li><strong>Quantize before parallelizing.</strong> Reach for tensor parallelism when the model genuinely does not fit.</li><li><strong>Protect decoders from long prompts.</strong> Look at chunked prefill or separate prefill and decode capacity if your traffic mixes long and short prompts.</li><li><strong>Benchmark properly.</strong> Warm up, repeat, report distributions, and keep configurations comparable.</li></ol><h3>9. Reproducing and extending this work</h3><p><strong>Environment:</strong> Kaggle notebook, GPU T4 x2, internet on, phone-verified account. Install with pip install vllm, then pip uninstall -y torchaudio if the CUDA mismatch error appears.</p><p><strong>Notebook:</strong> <a href="https://github.com/satyanarayanaallam/serving-vllms-on-kaggle/blob/main/serving-vllm-experiment.ipynb">https://github.com/satyanarayanaallam/serving-vllms-on-kaggle/blob/main/serving-vllm-experiment.ipynb</a></p><p><strong>Next steps I plan:</strong></p><ul><li>Repeat every sweep three or more times with a longer warm-up and report confidence intervals.</li><li>Extend concurrency to 64 and 128 to find the actual knee.</li><li>Use the server’s usage report to count tokens exactly.</li><li>Run TP=2 on the 1.5B model to test the claim that communication overhead dominates for small models.</li><li>Test chunked prefill and prefix caching explicitly.</li><li>Move to the infrastructure layer: the same engine behind a gateway on Kubernetes with Prometheus and autoscaling on queue depth, then one short run on a rented modern GPU.</li></ul><h3>Closing thoughts</h3><p>The most valuable outcome was not any single number. It was seeing the textbook relationships appear in my own data: bytes predicting speed, batching amortizing weight reads, a slot limit turning into a predictable queue, and prefill competing with decode. The second most valuable outcome was seeing how easily my own measurements wobbled. If a 1.5B model on a free GPU can produce a 6× difference in tail latency from one run to the next, treat every inference benchmark you read, including this one, with appropriate care.</p><p>If you run the notebook yourself, I would love to hear what you measure, especially if it contradicts something here.</p><h3>Appendix A: Server log excerpt (first launch, memory-related lines)</h3><pre>Checkpoint size: 2.88 GiB. Available RAM: 3.74 GiB.<br>Model loading took 2.98 GiB memory and 27.841852 seconds<br>Graph capturing finished in 7 secs, took 0.13 GiB<br>Available KV cache memory: 8.67 GiB<br>GPU KV cache size: 324,640 tokens, Maximum concurrency for 4,096 tokens per request: 79.26x<br>Graph capturing finished in 3 secs, took 0.08 GiB<br>Free memory on device (14.46/14.56 GiB) on startup. Desired GPU memory utilization is (0.85, 12.38 GiB).<br>Actual usage is 3.13 GiB for consumed memory (weights + non-torch), 0.58 GiB for peak activation,<br>and 0.08 GiB for CUDAGraph memory.</pre><h3>Appendix B: Derived quantities and how they were computed</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4I2pWjd5mHzjM7wWqg70uQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6528581f392c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Rate Limiter Is Lying to You: Designing a Distributed Rate Limiter That Actually Works]]></title>
            <link>https://medium.com/@allam.satyanarayana/your-rate-limiter-is-lying-to-you-designing-a-distributed-rate-limiter-that-actually-works-26946d67e1fc?source=rss-6f161f7e9dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/26946d67e1fc</guid>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Allam Satyanarayana]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 03:19:37 GMT</pubDate>
            <atom:updated>2026-08-05T03:19:37.330Z</atom:updated>
            <content:encoded><![CDATA[<p>Picture this: your API gateway enforces a hard 100 requests/minute limit per tenant. Legal signed a contract with a partner bank guaranteeing it. Your dashboards say it’s working. Then an audit shows one tenant pushed through 1,200 requests in a minute — twelve times over. Nobody touched the rate limiter code. Nothing crashed. So what happened?</p><p>The bug wasn’t in the logic. It was in the topology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_3Zm6NadrTI_L7RGZk9Og.png" /><figcaption>Architecture Diagram</figcaption></figure><h3>The setup nobody designed on purpose</h3><p>Most rate limiters don’t start as a single, carefully-designed system. They accrete. You had one API gateway, you added a counter, it worked. Then traffic grew, you scaled to 12 gateway instances behind a load balancer — and every one of those instances kept counting independently, in its own memory, with no idea the other 11 exist.</p><pre>Clients → Load Balancer → [ GW1  GW2  GW3 … GW12 ]  → Backend<br>                              count=100 each, independently</pre><p>A tenant capped at “100/min” isn’t really capped at 100. They’re capped at 100 <em>per gateway instance they happen to land on</em>. With round-robin routing across 12 instances, the effective ceiling is closer to 1,200/min. The limiter isn’t broken — it’s just answering a question (“how many requests has <em>this instance</em> seen?”) that nobody actually asked.</p><p>The fix isn’t removing instances or the load balancer. It’s moving the counter out of each instance and into one place all of them share.</p><h3>First instinct: Redis counter, and why it’s still wrong</h3><p>The obvious move is to point all 12 gateways at a shared Redis instance and run INCR + EXPIRE on a per-tenant key. This solves the visibility problem — now everyone&#39;s incrementing the same number. But it introduces a subtler bug: the <strong>fixed window boundary</strong> problem.</p><p>Say the window resets every 60 seconds, aligned to the clock. A tenant sends 100 requests at 0:59, and 100 more at 1:00. Each individual window “only” saw 100 requests — technically within limit. But in the two-second span from 0:59 to 1:01, 200 requests actually got through. The fixed window doesn’t see the burst because it resets the counter to zero right in the middle of it.</p><h3>The real fix: sliding window counter</h3><p>Instead of a hard reset, weight the previous window by how far you are into the current one:</p><pre>estimate = current_window_count + previous_window_count × (1 − elapsed / window_size)</pre><p>If you’re 20 seconds into a 60-second window, you count all of the current window’s requests plus 40/60 (≈67%) of the previous window’s requests. This smooths the boundary — a burst spanning two windows gets penalized proportionally instead of slipping through the crack between them.</p><p>This isn’t a novel idea — it’s the same approach <a href="https://blog.cloudflare.com/counting-things-a-lot-of-different-things/">Cloudflare uses in production</a> at the edge, across millions of domains. Their own measurements found about 0.003% of requests wrongly allowed or denied across 400 million requests from 270,000 sources — an approximation, but an accurate enough one that it’s the industry’s default answer for this exact problem. It’s also O(1) memory per tenant, unlike a sliding window <em>log</em> (which stores a timestamp per request and gets expensive fast at high volume).</p><h3>The part everyone skips: atomicity</h3><p>Here’s where a lot of designs quietly break. Even with a shared Redis counter, if your check is multiple round trips —</p><pre>GET current_count<br>GET previous_count<br>compute estimate<br>if estimate &lt; limit: INCR current_count</pre><p>— two gateway instances can both read “99,” both decide “allow,” and both increment. You just let through one more request than the limit, and it gets worse under real concurrency. Serializing this at the application layer (a “single writer” service that all gateways funnel through) is a natural first idea, but it adds a network hop to every single request and just relocates the bottleneck instead of removing it.</p><p>The better answer is already sitting inside Redis: a single Redis node executes one command — or one Lua script — at a time, full stop, no interleaving. Package the entire read-compute-decide-write sequence as one Lua script and call it via EVAL. Every gateway talks to Redis directly, no extra service in front, and Redis&#39;s own execution model becomes the serialization point for free.</p><pre>-- runs atomically inside Redis, no interleaving possible<br>local current  = tonumber(redis.call(&quot;GET&quot;, KEYS[1]) or 0)<br>local previous = tonumber(redis.call(&quot;GET&quot;, KEYS[2]) or 0)<br>local elapsed  = tonumber(ARGV[1])<br>local window   = tonumber(ARGV[2])<br>local limit    = tonumber(ARGV[3])</pre><pre>local estimate = current + previous * (1 - elapsed / window)</pre><pre>if estimate &gt;= limit then<br>    return 0  -- deny<br>else<br>    redis.call(&quot;INCR&quot;, KEYS[1])<br>    redis.call(&quot;EXPIRE&quot;, KEYS[1], window * 2)<br>    return 1  -- allow<br>end</pre><p><a href="https://stripe.com/blog/rate-limiters">Stripe’s own writeup on rate limiting</a> describes the same pattern for their token-bucket implementation — Redis plus an atomic Lua script, so the read-check-decrement sequence can’t race under concurrent load, and an explicit rule that a Redis outage should never take the whole API down with it.</p><h3>Do you actually need two counters for bursts?</h3><p>Some tenants need more than a flat sustained limit — say, 100/min sustained, but allowed to spike to 150 for a 5-second window. It’s tempting to think the sliding window counter alone handles this, but it mathematically can’t: if the limit is set to 100, the algorithm guarantees no more than ~100 requests in <em>any</em> rolling 60-second window — a 150-request burst inside that same window is precisely what it’s designed to block.</p><p>A token bucket (capacity 150, refilling at 100/60 per second) can express both properties in a single mechanism — this is literally Stripe’s production design. So strictly speaking, one well-tuned bucket can replace two separate counters.</p><p>The case for keeping them separate anyway comes down to three things: not every tenant needs a burst rule, so it’s cleaner as an optional layer on top of a universal sustained check; if “sustained” and “burst” are two separately-worded contractual clauses, you want independently auditable and tunable enforcement for each; and coupling both properties into one bucket’s capacity/refill ratio means tuning one accidentally shifts the other. If neither of those constraints applies to you, the single-bucket version is simpler and production-proven. If they do, run both checks — sliding window counter for the sustained rule, token bucket for the burst allowance — inside the <em>same</em> Lua script, so the two decisions and their writes commit together atomically.</p><h3>What happens when Redis goes down</h3><p>A distributed rate limiter that only works when Redis is healthy isn’t a solved problem, it’s a deferred outage. The failure mode needs to be a deliberate choice, not a default:</p><ul><li><strong>Contractual tenants</strong> (the partner bank in this story) should fail <em>closed</em> to a conservative local cap — e.g., the last known limit divided across your gateway instances — even though it slightly under-serves, because violating the contract is the worse outcome.</li><li><strong>Free-tier / general abuse protection</strong> can fail <em>open</em> with a generous local cap, since blocking legitimate traffic during a brief outage is worse than tolerating some abuse for a few seconds.</li></ul><p>A circuit breaker per gateway instance — trip after a few consecutive Redis timeouts, retry after a cooldown — keeps this from being a manual failover.</p><h3>The takeaway</h3><p>None of the individual pieces here are exotic. Sliding window counters, Lua scripts, token buckets, and circuit breakers are all well-worn tools. What actually separates a production-grade rate limiter from a broken one is recognizing which problem each piece solves: shared state fixes cross-instance visibility, the sliding window formula fixes boundary bursts, the Lua script fixes concurrent races, and the fallback design fixes what happens when your dependency isn’t there. Skip any one of them and the system looks correct in a demo — and quietly overcounts, undercounts, or falls over in production.</p><p><strong>References</strong></p><ul><li><a href="https://blog.cloudflare.com/counting-things-a-lot-of-different-things/">How we built rate limiting capable of scaling to millions of domains — Cloudflare</a></li><li><a href="https://stripe.com/blog/rate-limiters">Scaling your API with rate limiters — Stripe</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26946d67e1fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a Multi‑Agent Smart Compose with LangGraph]]></title>
            <link>https://medium.com/@allam.satyanarayana/how-i-built-a-multi-agent-smart-compose-with-langgraph-3eec18a13d05?source=rss-6f161f7e9dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eec18a13d05</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Allam Satyanarayana]]></dc:creator>
            <pubDate>Tue, 06 Jan 2026 02:54:50 GMT</pubDate>
            <atom:updated>2026-01-06T02:54:50.122Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started tinkering with LangGraph, I wanted to see if I could go beyond a single LLM call. What if text suggestions could be drafted, styled, fact‑checked, and even reviewed by a human — all inside one orchestrated workflow? That curiosity led to this little project: a multi‑agent Smart Compose system.</p><p><a href="https://github.com/satyanarayanaallam/multi-agent-smart-compose">Github</a></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong>Why bother with multiple agents?</strong></p><p>Most of us have seen autocomplete or “smart compose” features. They’re useful, but often too generic. I wanted something that could:</p><ul><li>Draft text suggestions</li><li>Apply a preferred tone (formal, casual, neutral)</li><li>Run a quick feedback check</li><li>Verify factuality</li><li>Ask a human reviewer if needed</li></ul><p>Instead of cramming all that logic into one big model call, I broke it down into agents. Each agent does one job, and a supervisor decides whether to loop back or finish.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p>The workflow at a glance</p><p>Think of it like a relay race:</p><p>User input → Drafting → Styling → Feedback → Fact-check → Human review → Supervisor</p><ul><li>Drafting Agent: generates the initial text (using Gemini or a fallback string).</li><li>Style Agent: adjusts tone.</li><li>Feedback Agent: scores the draft and flags if it’s too short.</li><li>Fact‑Checking Agent: calls a simple Wikipedia search tool.</li><li>Human Review Agent: either auto‑approves or asks for human input.</li><li>Supervisor: decides whether to loop back for revision or finish.</li></ul><p>The magic is in the shared state — a dictionary that carries everything (draft, tone, feedback score, fact‑check result, review decision) from one agent to the next.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong>What I learned along the way</strong></p><ul><li>Stateful design makes debugging easier. Every agent reads/writes explicit keys, so you can trace what happened.</li><li>Small agents are easier to test. Each one is just a function: input state → output state.</li><li>Graceful fallbacks matter. If Gemini fails, the system still produces a deterministic draft. Same for the search tool.</li><li>Human‑in‑the‑loop is underrated. Even a simple approve/revise prompt shows how workflows can blend automation with oversight.</li><li>Supervisor logic is the glue. Conditional edges decide whether to loop or finish, keeping the workflow predictable.</li></ul><p>— — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong>Running it yourself</strong></p><p>I added a simple CLI (run.py) that asks for your input and tone, then prints out:</p><ul><li>Draft</li><li>Styled draft</li><li>Feedback score</li><li>Fact‑check verdict</li><li>Iterations</li></ul><p>There’s also a smoke test that runs the graph with auto_approve=True and checks that a draft exists. It’s a tiny test, but it ensures the whole pipeline doesn’t break.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong>Where this could go next</strong></p><ul><li>Replace the toy feedback heuristic with a learned quality model.</li><li>Add multi‑modal inputs (images, audio) for richer Smart Compose.</li><li>Improve fact‑checking with multiple sources and citations.</li><li>Wrap the workflow in a FastAPI service for easy integration.</li><li>Add monitoring hooks (Prometheus, Grafana) to track drift and latency.</li></ul><p>— — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong>Final thoughts</strong></p><p>This project isn’t about building the perfect autocomplete. It’s about learning how to orchestrate multiple agents in LangGraph and seeing how modular design makes complex workflows manageable. If you’re experimenting with GenAI systems, try breaking them into small agents with a shared state — it’s surprisingly liberating.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eec18a13d05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Building a Small but Mighty Reasoning Model with Gemma‑3‑1B‑IT]]></title>
            <link>https://medium.com/@allam.satyanarayana/building-a-small-but-mighty-reasoning-model-with-gemma-3-1b-it-0caa4dfe4b41?source=rss-6f161f7e9dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/0caa4dfe4b41</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[supervised-fine-tuning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[synthetic-data]]></category>
            <dc:creator><![CDATA[Allam Satyanarayana]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 20:59:06 GMT</pubDate>
            <atom:updated>2025-12-28T20:59:06.724Z</atom:updated>
            <content:encoded><![CDATA[<p>This post walks through the full journey — from generating synthetic data to fine‑tuning with LoRA, experimenting with GRPO rewards, and even designing a curriculum‑based reasoning setup. If you’re curious about how to get a small model to “think out loud,” this is a great place to start.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>🧩 1. Starting with Synthetic Data</strong></p><p>We kicked things off by creating a tiny but clean synthetic dataset. Nothing huge — just enough to teach the model what reasoning looks like.</p><p>We covered three simple domains:</p><ul><li>Arithmetic (two‑digit operations)</li><li>Logic (day‑of‑week offsets)</li><li>Word problems (apples, totals, the classics)</li></ul><p>Each example had:</p><ul><li>a prompt</li><li>a reasoning trace (sometimes short, sometimes detailed)</li><li>a final answer</li><li>a domain label</li></ul><p>🗂️ Why keep it small?</p><p>Because small datasets are easy to regenerate, tweak, and iterate on.</p><p>And for early reasoning behavior, quality beats quantity.</p><p>📦 Data Flow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*U9stfA-hxIGckIpUsJq_gA.jpeg" /><figcaption>synthetic data generation</figcaption></figure><p>This file becomes the backbone for both SFT and GRPO.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>🔧 2. Teaching the Model to Imitate Reasoning (SFT + LoRA)</strong></p><p>Next, we fine‑tuned Gemma‑3‑1B‑IT using LoRA adapters. This keeps memory usage low — perfect for Mac users or anyone working without a big GPU.</p><p><em>🛠️ What we trained the model to do</em></p><ul><li>Read the prompt</li><li>Produce a reasoning trace</li><li>End with a clear “Final answer:”</li></ul><p><em>🔄 SFT Pipeline</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQnTw_QB2C5oS18ginjyQA.png" /><figcaption>SFT Pipeline</figcaption></figure><p>🎉 What we saw</p><p>After SFT, the model reliably produced:</p><ul><li>a structured reasoning section</li><li>a final answer</li><li>consistent formatting</li></ul><p>This gave us a strong foundation for the next stage.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>🎯 3. Making the Model Better at Reasoning (GRPO)</strong></p><p>Once the model learned the format, we wanted it to actually improve its reasoning — not just imitate examples.</p><p>That’s where GRPO comes in.</p><p>We designed a reward function that looks at:</p><ul><li>Correctness</li><li>Format (does it include reasoning + final answer?)</li><li>Length (not too short, not too long)</li><li>Domain style (logic problems should sound logical)</li></ul><p><em>🧠 Reward Flow</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LuwEW8BpEUBwcLbVyMdMg.png" /><figcaption>Reward Flow</figcaption></figure><p><em>🛠️ A couple of fixes along the way</em></p><ul><li>TRL’s AutoProcessor didn’t play nicely with Gemma → solved by passing the tokenizer directly</li><li>Reward function signature mismatch → fixed by accepting prompts, completions, completion_ids=None, **batch</li></ul><p><em>🌱 What this stage achieved</em></p><p>Even with a short run, GRPO nudged the model toward:</p><ul><li>cleaner structure</li><li>more consistent reasoning</li><li>better final answers</li></ul><p>It’s a small step, but a meaningful one.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>🧪 4. A Lightweight GRPO Sandbox on Mac</strong></p><p>Before going all‑in on complex rewards, we built a tiny GRPO prototype using only numeric accuracy as the reward.</p><p>This was mainly to confirm:</p><ul><li>GRPO works on Apple Silicon (MPS)</li><li>TRL behaves correctly</li><li>The environment is stable</li></ul><p>And it did!</p><p>This gave us confidence to scale up.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>🚀 5. A Kaggle‑Style Reasoning Experiment</strong></p><p>This notebook was our “big picture” experiment — a full reasoning setup with:</p><ul><li>Curriculum learning</li><li>Reward annealing</li><li>Structured reasoning tags</li><li>Domain‑aware scoring</li><li>Verbosity penalties</li></ul><p>Even though parts were simulated (to fit Kaggle limits), the structure mirrors a real GRPO training loop.</p><p><strong>📊 What we learned</strong></p><ul><li>Structured reasoning improves reward</li><li>Curriculum stabilizes learning</li><li>Annealing helps the model shift from “explain everything” → “be correct”</li><li>Domain generalization emerges naturally</li></ul><p>This notebook is a great template for anyone building a reasoning‑focused RL pipeline.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>💻 6. Running Everything Locally</strong></p><p>We kept the setup simple:</p><pre>python3 -m venv hf_env<br>source hf_env/bin/activate<br>pip install &quot;transformers&gt;=4.44.0&quot; datasets accelerate peft trl torch</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>🌈 7. What We Took Away from This Project</strong></p><p>Here are the big lessons:</p><p>⭐ 1. You don’t need huge datasets</p><p>A small, well‑designed synthetic dataset can teach structure surprisingly well.</p><p>⭐ 2. LoRA SFT is incredibly efficient</p><p>Gemma‑3‑1B‑IT adapts quickly and stays lightweight.</p><p>⭐ 3. GRPO gives you fine‑grained control</p><p>You can shape behavior through rewards — correctness, structure, verbosity, domain style.</p><p>⭐ 4. Curriculum + annealing works beautifully</p><p>Start with structure → shift toward correctness.</p><p>⭐ 5. The whole pipeline is Mac‑friendly</p><p>MPS + LoRA + TRL is a solid setup for iterative reasoning experiments.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>🎉 Final Thoughts</strong></p><p>This project showed us that you don’t need massive compute or huge datasets to build a model that “shows its work.” With thoughtful synthetic data, lightweight SFT, and a well‑designed GRPO reward system, even a small model like Gemma‑3‑1B‑IT can learn to reason in a structured, interpretable way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0caa4dfe4b41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning Rate Schedulers in Deep Learning: A Practical Comparison with CIFAR‑10]]></title>
            <link>https://medium.com/@allam.satyanarayana/learning-rate-schedulers-in-deep-learning-a-practical-comparison-with-cifar-10-066fdececfc8?source=rss-6f161f7e9dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/066fdececfc8</guid>
            <category><![CDATA[learning-rate-scheduler]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[cifar-10]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Allam Satyanarayana]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 21:00:49 GMT</pubDate>
            <atom:updated>2025-12-26T21:00:49.316Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>🌟 Introduction</strong></p><p>Training deep neural networks is a balancing act. Too high a learning rate and your model bounces around like a pinball; too low and it crawls painfully, stuck in local minima. The solution? Learning rate schedulers — algorithms that adjust the learning rate dynamically during training.</p><p>In this post, we’ll compare three popular schedulers — StepLR, ReduceLROnPlateau, and CosineAnnealingLR — applied to a ResNet18 model trained on CIFAR‑10. Along the way, we’ll look at architecture, training curves, and key observations.</p><p>👉 Full code and experiments are available here: <a href="https://github.com/satyanarayanaallam/learning-rate-scheduler-comparison">GitHub Repository</a></p><p><strong>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</strong></p><p><strong>🏗️ Architecture</strong></p><p>(Insert your architecture diagram here — “Figure 1: ResNet18 adapted for CIFAR‑10”)</p><p>We use ResNet18, a lightweight residual network, fine‑tuned for CIFAR‑10:</p><ul><li>Pretrained ImageNet weights loaded locally.</li><li>Final fully connected layer replaced with nn.Linear(512, 10) for CIFAR‑10’s 10 classes.</li><li>Optimizer: Adam (lr=0.001).</li><li>Loss: CrossEntropyLoss.</li><li>Epochs: 30, batch size 32.</li></ul><p><strong>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</strong></p><p><strong>📚 The Three Schedulers</strong></p><p><em>1. StepLR — The Classic</em></p><p>Every 10 epochs, the learning rate drops by a factor of 0.1.</p><ul><li>Strength: Predictable, easy to reproduce.</li><li>Weakness: Rigid — reduces LR even if the model is still improving.</li></ul><p><em>2. ReduceLROnPlateau — The Adaptive</em></p><p>Watches validation loss. If no improvement for 3 epochs, LR drops by 0.1.</p><ul><li>Strength: Responsive to actual training dynamics.</li><li>Weakness: Slightly more overhead, requires validation monitoring.</li></ul><p><em>3. CosineAnnealingLR — The Elegant</em></p><p>Smoothly decays LR along a cosine curve from 0.001 to 1e‑6.</p><ul><li>Strength: No patience parameters, graceful convergence.</li><li>Weakness: Fixed schedule may not align with dataset quirks.</li></ul><p><strong>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</strong></p><p><strong>📊 Results &amp; Graphs</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJdkOr8qXTkYh80vkLm0_A.png" /></figure><p>Observations from Graphs</p><ul><li>StepLR: Accuracy curve looks like a staircase. Sharp jumps after LR drops, but also instability (accuracy dip at epoch 10 before recovery).</li><li>ReduceLROnPlateau: Smoothest curve. Validation accuracy steadily climbs, peaking at 83.0% around epoch 28. Best overall performance.</li><li>CosineAnnealingLR: Accuracy rises gracefully, peaking around 82.1%, but plateaus earlier. Loss curve increases steadily after mid‑training.</li></ul><p><strong>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</strong></p><p><strong>🔍 Key Takeaways</strong></p><ol><li>StepLR is predictable but rigid. Great for reproducibility, but requires careful tuning.</li><li>ReduceLROnPlateau adapts to training dynamics, achieving the best accuracy in this experiment.</li><li>CosineAnnealingLR offers smooth convergence and minimal tuning, but didn’t outperform ReduceLROnPlateau here.</li></ol><p><strong>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</strong></p><p><strong>📌 References</strong></p><ul><li><a href="https://github.com/satyanarayanaallam/learning-rate-scheduler-comparison">GitHub Repository: Learning Rate Scheduler Comparison</a></li><li><a href="https://www.cs.toronto.edu/~kriz/cifar.html">CIFAR‑10 Dataset (Krizhevsky, 2009)</a></li><li><a href="https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate">PyTorch Documentation: Learning Rate Schedulers</a></li><li><a href="https://arxiv.org/abs/1512.03385">ResNet Paper: Deep Residual Learning for Image Recognition (He et al., 2015)</a></li></ul><p><strong>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</strong></p><p><strong>🏆 Conclusion</strong></p><p>Learning rate schedulers aren’t just technical details — they shape the entire training journey.</p><ul><li>If you want simplicity, go with StepLR.</li><li>If you want performance, ReduceLROnPlateau is your champion.</li><li>If you want elegance and reproducibility, CosineAnnealingLR is a solid default.</li></ul><p>The real lesson? Experiment, measure, and adapt. The right scheduler can be the difference between good and great results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=066fdececfc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training ResNet18 on Document Classification: Lessons from RVL‑CDIP]]></title>
            <link>https://medium.com/@allam.satyanarayana/training-resnet18-on-document-classification-lessons-from-rvl-cdip-106e342ec346?source=rss-6f161f7e9dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/106e342ec346</guid>
            <category><![CDATA[document-classification]]></category>
            <category><![CDATA[model-inference]]></category>
            <category><![CDATA[model-training]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Allam Satyanarayana]]></dc:creator>
            <pubDate>Thu, 25 Dec 2025 13:18:37 GMT</pubDate>
            <atom:updated>2025-12-25T13:30:52.427Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Introduction</em></strong></p><p>Document classification isn’t just an academic exercise — it powers real‑world systems like email filtering, invoice automation, and digital archiving. In this project, I set out to build a complete PyTorch pipeline for classifying documents using the RVL‑CDIP dataset, a massive benchmark of 400,000 scanned pages across 16 categories.</p><p>Instead of reinventing the wheel, I leaned on transfer learning with ResNet18, adapting a proven ImageNet model to the quirks of document images. The result: a robust, reproducible workflow that balances efficiency with accuracy.</p><p>👉 Full code and implementation details are available in my <a href="https://github.com/satyanarayanaallam/pytorch-dataloading">GitHub repo</a>.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong><em>Why RVL‑CDIP?</em></strong></p><p>RVL‑CDIP is a goldmine for document AI. It spans everything from handwritten notes to scientific publications, each with distinct visual cues. Training on such diversity forces the model to generalize — a skill that transfers well to other domains like medical imaging or legal document analysis.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>📐 Architecture: End‑to‑End Pipeline</p><p>At a high level, the system follows a document classification workflow built on PyTorch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*B09ztIMkj3S9M0jeCN3pNQ.jpeg" /></figure><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong><em>Key Challenges &amp; Solutions</em></strong></p><p><em>1. Corrupted TIFFs</em></p><p>Large datasets often contain unreadable files. I patched this with a safe loader that skips bad images instead of crashing the pipeline.</p><p><em>2. Device Agnosticism</em></p><p>Running across environments (CUDA GPUs, Apple Silicon MPS, or CPU) required careful device handling. A simple torch.device check made the code portable.</p><p><em>3. Checkpointing</em></p><p>Training deep models is fragile. I implemented per‑epoch checkpoints plus a “best model” saver, ensuring I could resume training or roll back to the highest‑accuracy weights without starting over.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong><em>Transfer Learning with ResNet18</em></strong></p><p>ResNet18’s pre‑trained filters already recognize edges, textures, and shapes. By swapping out the final fully connected layer for 16 outputs, I repurposed those features for document categories. This cut training time dramatically and boosted performance compared to training from scratch.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong><em>Training Pipeline Highlights</em></strong></p><ul><li>Data preprocessing: resize, normalize, batch with DataLoader</li><li>Loss &amp; optimizer: CrossEntropyLoss + Adam</li><li>Validation loop: monitor accuracy, detect overfitting</li><li>Checkpointing: save both per‑epoch and best model states</li></ul><p>Rather than paste the full loop here, you can explore the training script on GitHub.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong><em>Results</em></strong></p><p>On the held‑out test set, the fine‑tuned ResNet18 achieved strong accuracy across diverse document types. More importantly, the pipeline proved robust and reusable — a template for future classification tasks.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong><em>Lessons Learned</em></strong></p><ul><li>Always guard against corrupted data.</li><li>Device‑agnostic code saves headaches when moving between Mac, Kaggle, and cloud GPUs.</li><li>Checkpointing isn’t optional — it’s insurance.</li><li>Transfer learning is the fastest path to practical results.</li></ul><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong><em>Conclusion</em></strong></p><p>This project demonstrates how a well‑designed PyTorch workflow can tackle document classification at scale. By combining transfer learning, robust data handling, and checkpointing, we get a system that’s both practical and extensible.</p><p>If you’re working on image classification in any domain — documents, medical scans, or satellite imagery — this pipeline is a solid starting point.</p><p>👉 Explore the full implementation here: <a href="https://github.com/satyanarayanaallam/pytorch-dataloading">GitHub: pytorch-dataloading</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=106e342ec346" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PyTorch Model Training: From Creation to Inference]]></title>
            <link>https://medium.com/@allam.satyanarayana/pytorch-model-training-from-creation-to-inference-5c97d67fd008?source=rss-6f161f7e9dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c97d67fd008</guid>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Allam Satyanarayana]]></dc:creator>
            <pubDate>Thu, 25 Dec 2025 01:26:33 GMT</pubDate>
            <atom:updated>2025-12-25T01:28:09.227Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>PyTorch has become the go‑to framework for deep learning practitioners who want flexibility and speed. In this post, we’ll walk through the complete lifecycle of a PyTorch model — from understanding tensor dimensions, building CNNs, training with validation, saving checkpoints, resuming training, and finally performing inference.</p><p>All code snippets and extended examples are available in my <a href="https://github.com/satyanarayanaallam/pytorch-serialization-and-version-control">GitHub repo.</a></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>1. Understanding Tensor Dimensions</strong></p><p>Before diving into models, you need to master tensor shapes. Misaligned dimensions are one of the most common beginner mistakes.</p><ul><li>1D tensors: (batch_size,) → labels</li><li>2D tensors: (batch_size, features) → tabular data</li><li>3D tensors: (batch_size, seq_len, features) → text/time‑series</li><li>4D tensors: (batch_size, channels, height, width) → images</li><li>5D tensors: (batch, channels, depth, height, width) → 3D scans/videos</li></ul><p>👉 See the <a href="https://github.com/satyanarayanaallam/pytorch-serialization-and-version-control/blob/main/tensor_cheatsheet.md">tensor dimension cheatsheet</a> in the repo.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>2. Convolution &amp; Pooling Formulas</strong></p><p>When designing CNNs, you must calculate how dimensions change after each layer.</p><ul><li>Convolution:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*bjxVeUqvWQ3m55TmpAOleQ.png" /></figure><ul><li>Pooling:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*iAXRrQmARqjW15f0teN22A.png" /></figure><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>3. Building a CNN Model</strong></p><p>For CIFAR‑10 style images (3×32×32):</p><ul><li>Conv → Pool → Conv → Pool → Flatten → FC → Output</li><li>Dimension tracing ensures the fully connected layer input size matches the flattened tensor.</li></ul><pre>class ConvolutionModel(nn.Module):<br>    ...</pre><p>Full implementation: <a href="https://github.com/satyanarayanaallam/pytorch-serialization-and-version-control/blob/main/model_creation.ipynb">CNN model code</a>.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>4. Training Loop with Validation</strong></p><p>A robust training loop separates training and validation phases:</p><ul><li>model.train() → enables dropout, batch norm updates</li><li>model.eval() → disables training behaviors</li><li>torch.no_grad() → speeds up validation/inference</li></ul><pre>for epoch in range(num_epochs):<br>    model.train()<br>    ...<br>    model.eval()<br>    ...</pre><p>Check the <a href="https://github.com/satyanarayanaallam/pytorch-serialization-and-version-control/blob/main/model_creation.ipynb">training loop example</a>.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>5. Model Checkpointing</strong></p><p>Checkpointing ensures you don’t lose progress and can resume training later.</p><pre>torch.save({<br>    &#39;epoch&#39;: epoch,<br>    &#39;model_state_dict&#39;: model.state_dict(),<br>    &#39;optimizer_state_dict&#39;: optimizer.state_dict(),<br>    &#39;loss&#39;: val_loss,<br>}, &#39;checkpoints/best_model.pt&#39;)</pre><p>Loading checkpoints:</p><pre>checkpoint = torch.load(&#39;checkpoints/best_model.pt&#39;)<br>model.load_state_dict(checkpoint[&#39;model_state_dict&#39;])<br>optimizer.load_state_dict(checkpoint[&#39;optimizer_state_dict&#39;])</pre><p>See <a href="https://github.com/satyanarayanaallam/pytorch-serialization-and-version-control/blob/main/model_creation.ipynb">checkpoint utilities</a>.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>6. Inference and Predictions</strong></p><p>Switch to evaluation mode and disable gradients:</p><pre>model.eval()<br>with torch.no_grad():<br>    output = model(test_data)<br>    probs = torch.softmax(output, dim=1)<br>    conf, preds = torch.max(probs, dim=1)</pre><p>Detailed inference examples: <a href="https://github.com/satyanarayanaallam/pytorch-serialization-and-version-control/blob/main/model_creation.ipynb">inference notebook</a>.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>7. Resuming Training</strong></p><p>Load checkpoint, restore optimizer state, and continue training from the saved epoch:</p><pre>checkpoint = torch.load(&#39;checkpoints/best_model.pt&#39;)<br>start_epoch = checkpoint[&#39;epoch&#39;] + 1</pre><p>Resume training script: <a href="https://github.com/satyanarayanaallam/pytorch-serialization-and-version-control/blob/main/model_creation.ipynb">resume training</a>.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>8. Transfer Learning</strong></p><p>Leverage pre‑trained models (e.g., ResNet from torchvision.models):</p><ul><li>Freeze early layers</li><li>Replace final classifier layer</li><li>Train only the new head</li></ul><pre>for param in model.parameters():<br>    param.requires_grad = False<br>model.fc = nn.Linear(512, new_classes)</pre><p>Transfer learning demo: <a href="https://github.com/satyanarayanaallam/pytorch-serialization-and-version-control/blob/main/model_creation.ipynb">transfer learning</a>.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>Key Takeaways</strong></p><ul><li>Tensor dimensions are the foundation of PyTorch modeling.</li><li>Convolution/pooling formulas help you design correct architectures.</li><li>Training loops must separate training vs validation.</li><li>Checkpointing saves progress and enables reproducibility.</li><li>Inference requires eval() and no_grad().</li><li>Transfer learning accelerates training with limited data.</li></ul><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>Final Thoughts</strong></p><p>This workflow <strong>from model creation to inference</strong> is the backbone of every PyTorch project. By mastering checkpoints, inference, and transfer learning, you’ll be ready to tackle real‑world problems and deploy models confidently.</p><p>👉 Explore the full code and examples in my <a href="https://github.com/satyanarayanaallam/pytorch-serialization-and-version-control/tree/main">GitHub repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c97d67fd008" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ PCA vs t‑SNE: Dimensionality Reduction Demystified]]></title>
            <link>https://medium.com/@allam.satyanarayana/pca-vs-t-sne-dimensionality-reduction-demystified-dae31f3628e3?source=rss-6f161f7e9dbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/dae31f3628e3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[principal-component]]></category>
            <dc:creator><![CDATA[Allam Satyanarayana]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 00:02:21 GMT</pubDate>
            <atom:updated>2025-12-22T00:02:21.006Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction</p><p>In the age of high‑dimensional data, visualization and feature reduction are essential. Whether you’re working with images, text embeddings, or tabular datasets, dimensionality reduction techniques like PCA and t‑SNE help us uncover hidden patterns, reduce noise, and make models more efficient.</p><p>In this post, we’ll explore the concepts behind PCA and t‑SNE, why they matter, and how they differ — with practical code examples you can run on Kaggle.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong>🧩 PCA: Principal Component Analysis</strong></p><p>What it does</p><p>PCA finds new axes (principal components) that capture the maximum variance in your data.</p><ul><li>Eigenvectors → directions of maximum variance.</li><li>Eigenvalues → amount of variance explained along each direction.</li><li>Orthogonality → ensures components are independent and non‑redundant.</li></ul><p>Why it matters</p><ul><li>Reduces dimensionality while preserving most information.</li><li>Speeds up training and reduces overfitting.</li><li>Provides interpretable variance ratios to decide how many features to keep.</li></ul><p>Scree Plot Example</p><pre>from sklearn.datasets import load_digits<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.decomposition import PCA<br>import matplotlib.pyplot as plt<br>import numpy as np<br><br>digits = load_digits()<br>X = StandardScaler().fit_transform(digits.data)<br><br>pca = PCA().fit(X)<br>explained = pca.explained_variance_ratio_<br>cum_explained = np.cumsum(explained)<br><br>plt.figure(figsize=(8,5))<br>plt.plot(explained, marker=&#39;o&#39;, label=&quot;Individual variance&quot;)<br>plt.plot(cum_explained, marker=&#39;s&#39;, label=&quot;Cumulative variance&quot;)<br>plt.axhline(y=0.90, color=&#39;r&#39;, linestyle=&#39;--&#39;, label=&quot;90% threshold&quot;)<br>plt.axhline(y=0.95, color=&#39;g&#39;, linestyle=&#39;--&#39;, label=&quot;95% threshold&quot;)<br>plt.xlabel(&quot;Principal Component&quot;)<br>plt.ylabel(&quot;Explained Variance Ratio&quot;)<br>plt.title(&quot;Scree Plot for PCA on Digits Dataset&quot;)<br>plt.legend()<br>plt.show()</pre><p>👉 You’ll see that ~20–30 components explain 90–95% of the variance, meaning we can reduce from 64 pixel features to ~25 PCA features without losing much information.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p>🧩<strong> t‑SNE: t‑Distributed Stochastic Neighbor Embedding</strong></p><p>What it does</p><p>t‑SNE is a non‑linear technique that preserves local neighborhoods.</p><ul><li>Points close in high‑dimensional space remain close in 2D.</li><li>Excellent for visualizing clusters (digits, embeddings, customer segments).</li></ul><p>Why it matters</p><ul><li>Reveals hidden groupings that PCA may miss.</li><li>Ideal for exploratory data analysis and visualization.</li><li>Doesn’t provide variance ratios — it’s about cluster separation, not feature selection.</li></ul><p>Visualization Example</p><pre>from sklearn.manifold import TSNE<br><br>tsne = TSNE(n_components=2, random_state=42, perplexity=30, n_iter=1000)<br>X_tsne = tsne.fit_transform(X)<br><br>plt.figure(figsize=(8,6))<br>plt.scatter(X_tsne[:,0], X_tsne[:,1], c=digits.target, cmap=&#39;tab10&#39;, s=15)<br>plt.title(&quot;t-SNE Visualization of Digits Dataset&quot;)<br>plt.colorbar()<br>plt.show()</pre><p>👉 Unlike PCA, t‑SNE produces tight, well‑separated clusters of digits, making it easier to see natural groupings.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong>🎯 PCA vs t‑SNE: When to Use</strong></p><ul><li>PCA → linear, fast, interpretable, great for dimensionality reduction before modeling.</li><li>t‑SNE → non‑linear, slower, great for visualization and cluster exploration.</li><li>Together → PCA can reduce dimensions first (e.g., from 64 → 30), then t‑SNE can visualize those reduced features efficiently.</li></ul><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong>🧩 Training vs Inference with PCA</strong></p><ul><li>During training:</li></ul><p>You fit PCA on your training data. This computes the principal components (eigenvectors) and their directions of maximum variance.</p><p>Then you project your training data onto those components → reduced dimensionality.</p><ul><li>During inference:</li></ul><p>You must apply the same PCA transformation to new/unseen data before feeding it into the trained model.</p><p>Why? Because your model was trained in the PCA space (new rotated axes). If you feed raw features, they won’t align with the learned weights.</p><p>👉 So yes, inference data must also be reduced using PCA — but using the already fitted PCA object from training, not refitting PCA again.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong>🎯 Key Principle</strong></p><ul><li>PCA is not just “dropping features.” It’s a linear transformation into a new coordinate system.</li><li>The transformation is defined by the eigenvectors you learned during training.</li><li>At inference, you apply the same transformation to project new data into that same PCA space.</li></ul><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong>🔧 Example in Code</strong></p><pre>from sklearn.decomposition import PCA<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.linear_model import LogisticRegression<br><br># Training phase<br>scaler = StandardScaler()<br>X_train_scaled = scaler.fit_transform(X_train)<br><br>pca = PCA(n_components=20)<br>X_train_pca = pca.fit_transform(X_train_scaled)<br><br>model = LogisticRegression()<br>model.fit(X_train_pca, y_train)<br><br># Inference phase<br>X_test_scaled = scaler.transform(X_test)       # use same scaler<br>X_test_pca = pca.transform(X_test_scaled)     # use same PCA transform<br>y_pred = model.predict(X_test_pca)</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong>📚 References &amp; Resources</strong></p><ul><li><a href="https://stackoverflow.com/questions/55045012/do-i-have-to-do-fit-pca-separately-for-train-and-test-data">Stack Overflow: Do I have to fit PCA separately for train and test data?</a> — Clear explanation that PCA should be fit on training data only, then applied to test data.</li><li><a href="https://stats.stackexchange.com/questions/125172/pca-on-train-and-test-datasets-should-i-run-one-pca-on-traintest-or-two-separa">Cross Validated (Stats.SE): PCA on train and test datasets</a> — Discussion on why PCA must be fit on training data and reused for test.</li><li><a href="https://datascience.stackexchange.com/questions/131198/scaling-and-pca-for-test-data-before-prediction">Data Science Stack Exchange: Scaling and PCA for test data before prediction</a> — Reinforces the workflow: fit scaler + PCA on training, transform test.</li><li><a href="https://www.geeksforgeeks.org/python/training-data-vs-testing-data/">GeeksforGeeks: Training vs Testing Data</a> — General background on why training/test separation matters.</li></ul><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong>Conclusion</strong></p><p>Dimensionality reduction is more than a preprocessing step — it’s a lens into your data.</p><ul><li>PCA tells you which features matter most.</li><li>t‑SNE shows you how your data clusters.</li><li>Used together, they provide both efficiency and insight.</li></ul><p>Whether you’re preparing for interviews or building production pipelines, mastering PCA and t‑SNE will sharpen your ability to handle high‑dimensional datasets with confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dae31f3628e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>