<?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 Srinivas kodali on Medium]]></title>
        <description><![CDATA[Stories by Srinivas kodali on Medium]]></description>
        <link>https://medium.com/@srinivascoolguy?source=rss-6a54a072b0e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Srinivas kodali on Medium</title>
            <link>https://medium.com/@srinivascoolguy?source=rss-6a54a072b0e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:59:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@srinivascoolguy/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[The GPU Does the Math. The CPU Runs the Show.]]></title>
            <link>https://pub.towardsai.net/the-gpu-does-the-math-the-cpu-runs-the-show-f5983ecfa9d6?source=rss-6a54a072b0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5983ecfa9d6</guid>
            <category><![CDATA[kv-cache]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai-infrastructure]]></category>
            <dc:creator><![CDATA[Srinivas kodali]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 17:31:01 GMT</pubDate>
            <atom:updated>2026-11-25T17:31:01.891Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyavDdHRDwcNqP3jkAF56g.png" /><figcaption>The GPU Does the Math. The CPU Runs the Show.</figcaption></figure><p>Nov 23, 2026 · @Srinivas Kodali</p><p><em>The GPU does the math. The CPU runs the loop around it. Agents make that loop longer, and that changes how we should size inference servers, from CPU cores to RAM.</em></p><p>Most talk about inference capacity starts and ends with GPUs. I wanted to understand what the rest of the server is doing while the GPU works, so I went through serving-engine design notes, recent research papers and vendor benchmarks. The picture that came out is simple: the GPU can only go as fast as the CPU feeds it.</p><p>For years, the CPU side was an afterthought. Agents have moved it to the center. An agent calls tools, reads the results and sends a longer prompt back to the model, and most of that work lands on the CPU. In 2026, server CPU demand rose largely for this reason (<a href="https://spectrum.ieee.org/ai-cpu-comeback">IEEE Spectrum</a>).</p><p>This article walks through the phases of inference one at a time and shows what the CPU and the GPU each do in every phase. Then it looks at what changes as a deployment scales, takes on a question that comes up in every server spec (is more RAM worth it?), and ends with what I would check before buying another GPU. It builds on my earlier pieces, <a href="https://pub.towardsai.net/pcie-in-ai-inference-where-it-shines-and-where-it-lags-ad862bd9e1ec?source=friends_link&amp;sk=0ff3dc5f1d6239a7c7a0af9adca608d6"><em>PCIe in AI Inference: Where It Shines and Where It Lags</em></a> and <a href="https://pub.towardsai.net/when-the-kv-cache-spills-over-pcie-996781bd7658?source=friends_link&amp;sk=9773a3324b54b018f4896651f5df8dcf"><em>When the KV Cache Spills Over PCIe</em></a>, which looked at the link between the two chips.</p><h3>1. A simple mental model</h3><p>I personally like to cook, so the picture that works best for me is a restaurant kitchen. A restaurant kitchen makes a good picture. The GPU is a huge stove that can cook hundreds of dishes at once. The CPU is the expediter: it takes the orders, decides what goes on the stove next, plates the food and runs out for missing ingredients. A faster stove does not help if the expediter can’t keep up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6F2ohJwv2re_BmDp24R3tA.png" /><figcaption><em>Figure 1: The path of one request through a serving engine such as vLLM, SGLang or TensorRT-LLM.</em></figcaption></figure><p>Three things in this picture matter most:</p><ul><li><strong>The CPU touches every request first and last.</strong> Parsing, tokenizing, detokenizing and streaming are all CPU work.</li><li><strong>Decode is a tight loop between the two chips.</strong> After every step, the CPU collects the new tokens, updates each request, checks for stop conditions and launches the next step. This is the hot path.</li><li><strong>Agents add a second, slower loop.</strong> Each tool call runs on the CPU, and the whole conversation is tokenized again before it goes back to the GPU.</li></ul><h3>2. Why the work splits this way</h3><p>The split is not random. The GPU is built for bulk math and fast memory. The CPU is built for branching logic, small varied tasks and large memory. Table 1 puts them side by side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aheuYoD_NUYqLcnz5nPC-g.png" /><figcaption><em>Table 1: GPU vs. CPU at a glance: what each chip is built for.</em></figcaption></figure><p>The row that explains the most is the decode limit. Decode reads all the model weights for every token, so it runs at the speed of memory. An 8B model in BF16 has about 16 GB of weights, so the speed limit for one user is roughly memory bandwidth divided by 16 GB.</p><p>That one division explains the split. It is why the GPU does the model math, and why the CPU’s larger but slower memory works better as an overflow tier, or as a home for model parts that don’t fit on the GPU.</p><h3>3. The phases of inference, one by one</h3><p>When people say “inference”, they usually mean the model math. In practice, one request passes through six phases, and only two of them are mostly GPU work. Figure 2 shows who is busy in each phase. Table 2 sums it up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPvHd_jumPBoLgDjfoKRUg.png" /><figcaption><em>Figure 2: Who is busy in each phase of one request. Not to scale.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Svxu2fRsT2__6xx91SCRJg.png" /><figcaption><em>Table 2: The phases of inference at a glance.</em></figcaption></figure><h3>Phase 1: Intake (CPU)</h3><p>The request arrives as text over HTTP. The CPU parses it, applies the model’s chat template and turns the text into token IDs. If the engine keeps a prefix cache, the CPU also checks whether the start of this prompt has been seen before.</p><p>Tokenizing sounds trivial, but its cost grows with prompt length. A 100-token chat message costs almost nothing. A 100,000-token document, or an agent that resends its whole history every turn, is a different story. All of this happens before the GPU sees anything, so it adds straight to time to first token (TTFT).</p><h3>Phase 2: Scheduling (CPU)</h3><p>Next, the scheduler decides which waiting requests join the next batch. It finds free space in GPU memory for each request’s KV cache, decides whether to split a long prompt into chunks, and sometimes pauses a request to make room. The result is a batch plan and a set of input tensors, which the CPU copies to the GPU.</p><p>This is the engine’s brain, and its core loop usually runs on one main thread. That detail matters later: a single slow thread can hold back a whole GPU.</p><h3>Phase 3: Prefill (GPU, compute-bound)</h3><p>Prefill reads the whole prompt in one pass and writes the KV cache: the keys and values for every token, in every layer, that later tokens will look back at. Because the GPU processes thousands of tokens together, every weight it loads gets reused thousands of times. That makes prefill compute-bound. The tensor cores are the limit, not memory.</p><p>To get a feel for the cost: a forward pass needs about 2 FLOPs per parameter per token. For an 8B model and an 8,000-token prompt, that comes to about 130 trillion FLOPs. An H100 peaks at 989 TFLOPS in dense BF16 (<a href="https://www.nvidia.com/en-us/data-center/h100.html">NVIDIA</a>); if it sustains 500–600 TFLOPS in practice, prefill takes roughly a quarter of a second. That number comes back in the RAM section.</p><p>The CPU’s role here is small but real. It launches the GPU kernels, and for very long prompts it feeds the GPU one chunk at a time so that other users’ decode steps don’t stall.</p><h3>Phase 4: Decode (GPU and CPU, every token)</h3><p>Decode writes the answer one token at a time for every request in the batch. Each step reads all the model weights and each request’s KV cache, but does very little math per byte it reads. That makes decode memory-bound.</p><p>Here is the simple calculation that made decode click for me. A GPU has two speeds: how fast it does math, and how fast it reads data from its memory.</p><ol><li><strong>Compare the two speeds.</strong> An H200-class GPU can do about 989 trillion math operations (FLOPs) per second, but it reads only about 4.8 trillion bytes per second from memory (<a href="https://www.nvidia.com/en-eu/data-center/h200/">NVIDIA</a>). Divide one by the other and you get about 200. So for every byte the GPU reads, it can do about 200 operations. If a task does less math than that for each byte, the GPU spends most of its time waiting for data.</li><li><strong>Count the math in decode.</strong> For each new token, the GPU reads every weight in the model. Each weight is 2 bytes and is used for just 2 operations: one multiply and one add. That is only 1 operation per byte, so the compute units mostly sit and wait for memory.</li><li><strong>Add more requests to the batch.</strong> The GPU reads each weight once and uses it for every request in the batch. With about 200 requests, there is finally enough math for each byte read to keep the GPU busy.</li><li><strong>Remember the KV cache.</strong> Each request also reads its own KV cache, and that part can’t be shared with other requests. So every extra request adds more reading, and in practice the batch must be even larger before math becomes the limit.</li></ol><p>Two things follow from that:</p><ul><li>Adding users barely changes the step time<strong>.</strong> The step time is set mainly by reading the weights. For an 8B model, reading 16 GB at 4.8 TB/s takes about 3.3 ms, whether the batch holds one user or a few dozen.</li><li><strong>The CPU’s share keeps growing.</strong> After every step, the CPU collects the new tokens, updates each request, checks stop conditions and launches the next step. That work grows with every user, while the GPU’s step time barely moves.</li></ul><p>If the CPU does this work while the GPU waits, every step has a small gap, and thousands of steps add up. Modern engines hide the gap by preparing step N+1 on the CPU while the GPU runs step N (Figure 3). CUDA Graphs help too, by turning many small kernel launches into one. This overlap is now standard in vLLM, SGLang and TensorRT-LLM. With it, the GPU no longer sits idle while the CPU gets the next step ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Azh5ksF1a2R_cksFuarbZA.png" /><figcaption><em>Figure 3: Without overlap, the GPU waits for the CPU at every step. With overlap, the CPU prepares the next step while the GPU works.</em></figcaption></figure><h3>Phase 5: Output (CPU)</h3><p>The new token IDs go back to the CPU, which turns them into text (detokenizing), checks for stop strings and streams the text to the user. The work per token is light, but it runs for every token of every user, so at high concurrency it adds up. Newer engines move this work out of the core loop so it can’t delay the next step.</p><h3>Phase 6: The agent loop (CPU)</h3><p>A plain chat request ends at Phase 5. An agent’s request doesn’t. Its output is a tool call: search the web, run code, query a database, read a file. The CPU runs the tool, often inside a sandbox, adds the result to the conversation and sends the longer prompt back to Phase 1.</p><p>Three things make this phase heavy for the CPU:</p><ul><li><strong>Tools are pure CPU and I/O work.</strong> While a tool runs, the GPU has nothing to do for that request.</li><li><strong>The context grows every turn.</strong> Tokenizing and prefill grow with it, unless the KV cache from the last turn is still around.</li><li><strong>Checks run around every step.</strong> Guardrails and safety filters, often small models, run before and after each turn, and they often stay on the CPU.</li></ul><p>This is the phase that changed the CPU story. In a s<a href="https://arxiv.org/pdf/2511.00739">tudy of agent workloads</a>, tool processing on the CPU made up as much as 90.6% of end-to-end latency.</p><h3>4. What changes at scale</h3><p>Scaling inference is not one thing. A deployment can serve more users, run a bigger model, accept longer prompts, add more servers or add agents. Each one loads the GPU and the CPU differently, and it’s easy to scale the GPU side and forget the other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zN76H31h2jGQUvcvUoGChA.png" /><figcaption><em>Table 3: What grows on each side at scale.</em></figcaption></figure><h3>More users on one GPU</h3><p>In decode, adding users to the batch is the most efficient way to raise throughput, because the weights are read once per step for the whole batch. But CPU work per step grows with every user: more tokens to collect, more requests to update, more text to stream. At high concurrency, each step can end up waiting on the CPU instead of on GPU memory.</p><h3>A bigger model on more GPUs</h3><p>When a model is too big for one GPU, engines split each layer across several GPUs (tensor parallelism). Each GPU gets its own CPU worker process. Every step, all workers must launch their part before the GPUs can exchange results, so the group moves at the pace of its slowest worker. CPU needs therefore grow with the number of GPUs, not the size of the model, and one busy core can slow all eight GPUs.</p><h3>Longer prompts</h3><p>Longer context raises three costs at once: tokenizing (CPU, grows with length), prefill attention (GPU, grows faster than length) and KV cache size (memory, grows with length). For a model like Llama 3.1 8B (32 layers, 8 KV heads of size 128, BF16, per its <a href="https://huggingface.co/unsloth/Meta-Llama-3.1-8B-Instruct/blob/main/config.json">published configuration</a>), every token of context holds 2 × 32 × 8 × 128 × 2 bytes, or 128 KB, of KV cache. An 8,000-token conversation needs about 1 GB. A 128,000-token one needs about 16 GB, the same as the model’s own weights. Memory, not math, is usually the first wall.</p><h3>More servers</h3><p>Past one server, copies of the model sit behind a router. The router is CPU work too, and a smart one saves GPU work. If it sends a follow-up message to the copy that already holds that conversation’s KV cache, prefill is skipped entirely. That’s the technical case for routing by cache hits instead of plain round-robin: a hit skips prefill, the most compute-heavy phase of the request.</p><h3>More agents</h3><p>Agent traffic scales with tool calls per second, not tokens per second. A coding agent that runs tests, or a research agent that fetches pages, can keep many CPU cores busy while barely touching the GPU. This is the part of the system most likely to be undersized, because it never shows up in a GPU-first capacity plan.</p><h3>5. Is more RAM worth adding?</h3><p>My short answer: yes, up to the size of the KV working set, if the traffic reuses context. Past that point, extra RAM mostly sits idle. Here is how I got there.</p><h3>What RAM does for inference</h3><p>GPU memory is small and fast. Server RAM is large and slower, but reading saved results from it avoids redoing the math. RAM earns its place in an inference server in three ways:</p><ul><li><strong>A second tier for the KV cache.</strong> When GPU memory fills, the engine can move older KV blocks to RAM instead of throwing them away.</li><li><strong>A home for weights that don’t fit.</strong> Smaller setups can keep parts of a large model, such as the experts of a mixture-of-experts model, in RAM and run them on the CPU.</li><li><strong>Fast restarts and scale-up.</strong> Model files kept in RAM go straight to the GPU over PCIe, without waiting on disk or network storage.</li></ul><p>The first one carries most of the value, and a worked example shows why.</p><h3>A worked example</h3><p>The example uses an 8B model on one 80 GB GPU. The weights use 16 GB. After the engine’s working buffers, roughly 50–60 GB is left for KV cache. At 128 KB per token, that’s room for about 400,000–480,000 tokens: 50–60 conversations of 8,000 tokens each.</p><p>In the example, each GPU serves 200 active conversations of about 8,000 tokens, with users replying every minute or two. Their KV cache adds up to about 200 GB, and the GPU holds only about a quarter of it. Without a RAM tier, most replies mean running prefill again from scratch.</p><p>With a RAM tier, the engine reloads the conversation’s 1 GB of KV cache over PCIe instead. A PCIe Gen5 x16 link carries about 64 GB/s in each direction, or around 50 GB/s after protocol overhead, so the reload takes about 20 milliseconds. Recomputing it takes about 250 milliseconds, as we saw in the prefill phase. The reason reloading is the better choice is technical: it only moves bytes over PCIe, while recomputing repeats about 130 trillion FLOPs of GPU work. During a reload, the GPU’s compute stays free for other users. Even if every conversation came back once a minute, reload traffic would be about 3–4 GB/s per GPU, well within what the link can carry.</p><p>Across an 8-GPU server, those 1,600 conversations need about 1.6 TB of KV cache. That fits in the system memory of a typical 8-GPU server: NVIDIA’s <a href="https://nvidia.com/en-us/data-center/dgx-h100">DGX H100</a> pairs 640 GB of GPU memory with 2 TB of system memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-13W9WM_DeVYeoDHw1zmw.png" /><figcaption><em>Figure 4: The KV working set outgrows GPU memory long before it outgrows server RAM. My estimate for the example above.</em></figcaption></figure><h3>When more RAM does not help</h3><ul><li><strong>Traffic without reuse.</strong> One-shot requests with unique prompts never come back. Their KV cache is useless the moment the answer ends.</li><li><strong>Short prompts.</strong> If prefill takes a few milliseconds, recomputing takes about as long as reloading, so keeping the cache saves no time.</li><li><strong>Too few cores, not too little memory.</strong> If the GPU is waiting on scheduling or tools, more RAM changes nothing.</li><li><strong>A busy PCIe link.</strong> Reloads share the link with everything else. Past a point the link, not the RAM size, sets the limit. My earlier article, <em>When the KV Cache Spills Over PCIe</em>, goes deep on this.</li><li><strong>Past the working set.</strong> Once RAM holds the KV cache of every conversation likely to come back, extra capacity only holds conversations that won’t.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_8pU4vnkgbbZxCifE62_Q.png" /><figcaption><em>Table 4: Does more RAM help? A quick check by workload.</em></figcaption></figure><p>So is more RAM good? For chat and agent workloads with long conversations that keep coming back, yes. It lets the GPU serve a returning user without repeating prefill, because the conversation’s KV cache is still a PCIe transfer away. For short, one-shot traffic, the limit is somewhere else, so CPU cores or the engine version are the place to look.</p><h3>6. How to tell, and what to fix</h3><p>A CPU-starved GPU is easy to miss, because the GPU itself looks healthy. Its kernels run at normal speed while latency climbs.</p><p>The cleanest test changes only the CPU side: the same load runs again with more cores per GPU. If latency improves while GPU kernel times stay the same, the CPU was the limit. A <a href="https://arxiv.org/pdf/2603.22774">2026 Georgia Tech study</a> ran this kind of test on 8-GPU servers. With too few cores, time to first token on long prompts went up, while GPU kernel times changed by less than 1%. The GPU was waiting, not working.</p><p>Current versions of vLLM, SGLang and TensorRT-LLM overlap CPU work with GPU work by default, so an upgrade removes the gap between steps. Dedicated cores give the tokenizer, the scheduler and each GPU worker room of their own, so none of them waits behind another.</p><h3>7. My rules of thumb for sizing the CPU side</h3><ul><li><strong>Engine cores first.</strong> Start with 4–8 dedicated cores per GPU for the serving engine alone. A <a href="https://arxiv.org/pdf/2603.22774">2026 study</a> measured slowdowns below that range, because the tokenizer, the scheduler and the GPU workers start competing for the same cores.</li><li><strong>Fast cores for the loop.</strong> The engine’s control loop runs largely on one thread, so per-core speed matters more than core count there.</li><li><strong>A separate pool for agents.</strong> Size tool and sandbox cores from the expected number of tool calls per second, not from the GPU count.</li><li><strong>RAM for the KV working set.</strong> Size RAM from the KV cache of the conversations likely to come back, not just the OS and the model files (Section 5).</li><li><strong>Re-profile after every GPU upgrade.</strong> The bottleneck often moves to the CPU.</li></ul><p>The industry is moving the same way. Training-era servers paired roughly one CPU with eight GPUs. Newer rack-scale designs pair one CPU with every two GPUs, and agent-heavy deployments are heading toward one-to-one .</p><h3>8. The takeaway</h3><p>Of the six phases, only prefill and the math inside decode belong to the GPU. Intake, scheduling, the per-step control, output and the agent loop all run on the CPU, and RAM decides whether a returning conversation is reloaded in about 20 milliseconds or recomputed in about 250.</p><p>The GPU still does the math, and nothing I read changes that. What has changed is how much work surrounds the math. I now think of the CPU and its memory as part of the inference engine, not as the part that keeps the GPU fed. They should be sized from a profile of the actual workload, not from an old ratio.</p><h3>References</h3><ul><li>Chung, Jia, Jezghani, Kim (Georgia Tech), <a href="https://arxiv.org/pdf/2603.22774">Characterizing CPU-Induced Slowdowns in Multi-GPU LLM Inference</a>, arXiv, March 2026</li><li>Raj et al. (Georgia Tech), <a href="https://arxiv.org/abs/2511.00739">Towards Understanding, Analyzing, and Optimizing Agentic AI Execution: A CPU-Centric Perspective</a>, arXiv, 2025–2026</li><li>M. S. Smith, <a href="https://spectrum.ieee.org/ai-cpu-comeback">The CPU Comeback Is Upon Us</a>, IEEE Spectrum, August 2026</li><li>Bowerman and Ableidinger, <a href="https://redhat.com/en/blog/cpu-back-rethinking-cpu-gpu-split-llm-inference">The CPU is back: Rethinking the CPU-GPU split for LLM inference</a>, Red Hat, August 2026</li><li>Tensormesh and University of Chicago, <a href="https://arxiv.org/pdf/2510.09665">LMCache: An Efficient KV Cache Layer for Enterprise-Scale LLM Inference</a>, arXiv, October 2025</li><li>Chen et al., <a href="https://madsys.cs.tsinghua.edu.cn/publication/ktransformers-unleashing-the-full-potential-of-cpu/gpu-hybrid-inference-for-moe-models/">KTransformers: Unleashing the Full Potential of CPU/GPU Hybrid Inference for MoE Models</a>, SOSP 2025</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5983ecfa9d6" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/the-gpu-does-the-math-the-cpu-runs-the-show-f5983ecfa9d6">The GPU Does the Math. The CPU Runs the Show.</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When the KV Cache Spills Over PCIe]]></title>
            <link>https://pub.towardsai.net/when-the-kv-cache-spills-over-pcie-996781bd7658?source=rss-6a54a072b0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/996781bd7658</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-infrastructure]]></category>
            <category><![CDATA[gpu]]></category>
            <dc:creator><![CDATA[Srinivas kodali]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 21:01:01 GMT</pubDate>
            <atom:updated>2026-11-17T21:01:01.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l--dUeAMxl7_C6fS7yvwPw.png" /><figcaption>When the KV Cache Spills Over PCIe</figcaption></figure><p>Nov 14, 2026 · @Srinivas Kodali</p><p>One model, one 8-GPU server, 200 long-context users. Where the KV cache goes when GPU memory runs out, what PCIe does to response time, and how to keep it under control.</p><p>In my last article, <a href="https://pub.towardsai.net/pcie-in-ai-inference-where-it-shines-and-where-it-lags-ad862bd9e1ec">PCIe in AI Inference: Where It Shines and Where It Lags</a>, PCIe sat mostly idle while the GPU wrote tokens. It mattered only when data had to move in bulk.</p><p>In long-context serving, the biggest bulk mover is the KV cache. Every chat, document and agent step leaves one behind. When GPU memory fills up, the cache spills into CPU memory and SSDs, and PCIe becomes the only road back.</p><p>This article follows one production setup end to end: how big the cache gets, where it lives, how long it takes to bring back, and what breaks under real load.</p><h3>The setup</h3><p>One example runs through the whole article: Llama 3.1 70B served by vLLM on a DGX H100-class server. The hardware numbers come from public spec sheets, and the software is open source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQVpzJty1FpMJBARlP6JOg.png" /><figcaption><em>Table 1. The production setup used in this article.</em></figcaption></figure><p>The workload is a typical coding or support assistant. Users paste documents, keep long chat histories, run agent steps, and pause to think between turns.</p><h3>How big is the KV cache?</h3><p>For every token in the context, each layer keeps one key and one value vector per KV head. For Llama 3.1 70B, that comes to:</p><p><strong>KV per token = 2 (key + value) × 80 layers × 8 KV heads × 128 dims × 2 bytes = 327,680 bytes</strong></p><p>That is about 320 KB per token in BF16, or 160 KB in FP8. Multiply it by the context length to get each user’s cache.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYHhIAQDxu_J6pI15SJHZg.png" /><figcaption><em>Table 2. KV cache per user, and how many users fit in about 400 GB of HBM.</em></figcaption></figure><p>Why 400 GB? Start with 640 GB of HBM. Keep 10% back as a safety margin, then subtract 141 GB of weights and some working memory for activations.</p><h3>The math that forces a spill</h3><p>Our 200 sessions average 32K tokens each, so they need 200 × 10.7 GB = 2.15 TB of KV cache. HBM holds about 37 of them.</p><p>That leaves 163 sessions with two choices:</p><ul><li><strong>Drop and recompute.</strong> Throw the cache away and rebuild it from the text on the next turn.</li><li><strong>Park it.</strong> Copy the cache to CPU memory or SSD, and bring it back on the next turn.</li></ul><p>Recompute costs GPU time. Parking costs PCIe time. The rest of this article is about that trade.</p><p>FP8 changes the picture. It halves the total to 1.07 TB, which fits in HBM plus CPU memory with no SSD needed.</p><h3>The spill path</h3><p>A parked KV cache moves down a ladder. Each step away from the GPU adds capacity and loses bandwidth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_fuUbOJpFh8KrRtJfbFyw.png" /><figcaption><em>Figure 1. The spill path on an 8× H100 server.</em></figcaption></figure><p>Two numbers matter most. The road from CPU memory back to the GPU runs at about 50 GB/s in practice. The <a href="https://vllm.ai/blog/2026-01-08-kv-offloading-connector">vLLM team measured</a> that one-way peak on an H100, against 64 GB/s on paper. That is about 67 times narrower than HBM.</p><p>SSDs are slower again. A Gen4 data center drive reads about 6 to 7 GB/s, and <a href="https://developers.redhat.com/articles/2026/11/02/benchmarking-tiered-kv-cache-offloading-h100-gpus-openshift-ai-3-5">Red Hat measured</a> 6.2 GB/s during its H100 inference tests.</p><h3>A returning user: recompute or reload?</h3><p>A user comes back after five minutes, and their 32K-token KV cache was parked. What does the next answer cost?</p><p>With tensor parallelism across 8 GPUs, each GPU holds one-eighth of the cache. So each GPU pulls 1.34 GB over its own PCIe link, and all eight pull at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSJ8qQpzSjqvgAWZqC4mEQ.png" /><figcaption><em>Figure 2. Time to bring back one 32K-token user before the first new token.</em></figcaption></figure><p>Reloading from CPU memory is more than 50 times faster than recomputing. Even the SSD path is at least 7 times faster.</p><h3>How long does recompute really take?</h3><p>Start with the work. Prefill costs about 2 FLOP per parameter per token, plus attention, which grows with the square of the context:</p><p><strong>Prefill work ≈ 2 × parameters × tokens + 2 × layers × hidden size × tokens²</strong></p><p>For 32K tokens on Llama 3.1 70B, that is about 4.6 + 1.4 = 6.0 PFLOP.</p><p>Eight H100s peak at 7.9 PFLOP/s in dense BF16, or 989 TFLOP/s each. (The 1,979 TFLOP/s on the datasheet assumes sparsity, which dense models don’t use.) At that peak, recompute would take 0.76 s. Real prefill never runs at peak, because each of these steps needs compute or time beyond the raw math:</p><ul><li><strong>Matrix multiplies</strong> do most of the work, but they never keep every tensor core busy.</li><li><strong>Attention</strong> grows with the square of the context and runs less efficiently than plain matrix multiplies.</li><li><strong>Small steps</strong> like normalization, softmax and activations add little math but still take time.</li><li><strong>Chunked prefill</strong> splits the prompt into pieces, which adds kernel launches and re-reads of earlier KV.</li><li><strong>Syncing the 8 GPUs</strong> after every layer moves data over NVLink, and the FLOP count doesn’t include it.</li></ul><p>Together, these put recompute at roughly 1.5 to 2.5 s on an idle server. FP8 roughly halves it. To get the real number for your own setup, measure a single 32K-token prefill:</p><pre>vllm bench latency --model meta-llama/Llama-3.1-70B-Instruct -tp 8 --input-len 32768 --output-len 1 --batch-size 1 --no-enable-prefix-caching</pre><p>Under load, recompute gets much slower. It waits behind other users’ prefills and shares the GPUs with their decode steps. <a href="https://blog.lmcache.ai/en/2026/04/22/lmcache-on-amazon-sagemaker-hyperpod-accelerating-llm-inference-with-managed-tiered-kv-cache/">LMCache measured</a> Llama 3.1 70B on 8× H100 with 100 chat sessions of only 12K tokens each and a small CPU cache. Time to first token was 4.5 s at P50 and 8.3 s at P90.</p><p>Recompute also has a hidden cost: every second of it is GPU time taken from users who are already generating tokens.</p><h3>What breaks under real load</h3><p>The 27 ms above is the best case: one user, an idle bus and well-tuned code. Production adds traffic, topology and wear.</p><h3>1. Return storms turn PCIe into a queue</h3><p>Users don’t come back one at a time. A meeting ends, a batch of agents wakes up, or the morning rush starts. If 20 users return together, each GPU must pull 20 × 1.34 GB = 27 GB before the last of them sees a token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rp6eL9ZJly0_fCLxMxN8qw.png" /><figcaption><em>Figure 3. Wait for the last user when many return at once.</em></figcaption></figure><p>At the full 50 GB/s, about 18 users fit inside a 500 ms budget. At 15 GB/s, the sustained rate <a href="https://arxiv.org/html/2601.19910v1">one study</a> measured on an H100 server, only 5 do. FP8 doubles each of these numbers.</p><h3>2. The link is shared</h3><p>The GPU’s PCIe link doesn’t belong to the KV cache alone. In many 8-GPU servers, each GPU sits behind a PCIe switch with its network card, and some designs put two GPUs on one switch. Network traffic, storage reads and KV reloads then compete for the same lanes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XYp4AVpZlExsenP5Zs1boA.png" /><figcaption><em>Figure 4. Three kinds of traffic share one GPU’s PCIe link.</em></figcaption></figure><h3>3. The two directions fight</h3><p>Offload writes new KV to CPU memory while reloads pull old KV back. PCIe is full duplex on paper, but host-side limits can make the two directions slow each other down. Test both directions at once with nvbandwidth before you trust one-way numbers.</p><h3>4. Tiny transfers waste the bus</h3><p>vLLM stores KV in 16-token blocks. In its older layout, one Llama 3.1 70B block was only 8 KB per layer, and copy engines are poor at small copies. The <a href="https://vllm.ai/blog/2026-01-08-kv-offloading-connector">newer layout</a> packs all layers into one 1.25 MB block, which raised offload throughput about tenfold.</p><h3>5. One slow GPU sets the pace</h3><p>With tensor parallelism, a reload finishes only when all eight GPUs finish. One link running at half width or an older PCIe generation slows down every user. Check link speed and width on all eight GPUs, not just one.</p><h3>6. The buffer sits on the wrong CPU</h3><p>If a GPU’s pinned host buffer sits on the far CPU socket, every copy crosses the link between the sockets. nvidia-smi topo -m labels that path SYS, the slowest kind of GPU path.</p><h3>7. SSDs wear out and fail</h3><p>KV offload writes all day. Read-intensive drives such as the <a href="https://www.storagereview.com/news/micron-7450-ssd-announced">Micron 7450 PRO</a> are rated for one full drive write per day, so eight 3.84 TB drives can absorb about 31 TB a day. A steady 1 GB/s of KV writes is 86 TB a day, which wears the drives out in under 2 years instead of 5.</p><p>On DGX H100, the data drives also ship as <a href="https://docs.nvidia.com/dgx/dgxh100-user-guide/introduction-to-dgxh100.html">RAID 0</a>. One failed drive empties the whole tier, and a restart means a cold cache.</p><h3>8. Requests miss a cache that exists</h3><p>With several replicas, a returning user can land on a replica that never saw their KV cache, and the system recomputes anyway. With 4 replicas and plain round-robin routing, a returning user lands on the right server only 1 time in 4, so about 75% of returning turns recompute for nothing. Sticky or KV-aware routing fixes this by sending each turn back to the replica that holds its cache.</p><h3>9. Parked KV is user data</h3><p>The KV cache is a working copy of the user’s conversation. On disk, it needs the same encryption and deletion rules as chat logs. DGX H100’s data drives are self-encrypting, which helps, but retention rules are still your job.</p><h3>When to offload, and when not to</h3><p>Offload pays off when the same context comes back. When it doesn’t come back, offload just burns bandwidth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRFArJOcXoNCMMxqDgpdzA.png" /><figcaption><em>Table 4. Where the KV cache should live, by workload.</em></figcaption></figure><p><em>Table 4. Where the KV cache should live, by workload.</em></p><p>Reuse is the deciding number. The longer the context, the more a recompute costs, so long contexts pay back the offload even when only some sessions return.</p><h3>Key takeaways</h3><ul><li>A 32K-token user on Llama 3.1 70B carries 10.7 GB of KV cache, and an 8× H100 server holds about 37 of them in HBM.</li><li>For one user, reloading from CPU memory over PCIe is more than 50× faster than recomputing, and the gap grows under load.</li><li>Under load, PCIe becomes a queue: about 18 users returning at once use up a 500 ms budget, even at full speed.</li><li>Most fixes come down to moving fewer, bigger bytes over the right path: FP8 KV, large blocks, the local CPU socket, and a known PCIe topology.</li></ul><p>FP8 halves nearly every number in this article. In the next article, I look at quantization: shrinking weights and the KV cache so one GPU node serves more tokens per second.</p><h3>References</h3><ol><li><a href="https://huggingface.co/neuralmagic/Meta-Llama-3.1-70B-Instruct-FP8/blob/9f5dfe39a764599bee5c95e965c755e982b704a7/config.json">Llama 3.1 70B Instruct config</a>: layers, KV heads, head size and hidden size for the KV and prefill formulas</li><li><a href="https://www.nvidia.com/en-us/data-center/h100.html">NVIDIA H100 specifications</a>: 80 GB HBM3, 3.35 TB/s, 989 TFLOP/s dense BF16</li><li><a href="https://developer.nvidia.com/blog/nvidia-hopper-architecture-in-depth/">NVIDIA Hopper architecture in depth</a>: PCIe Gen5 at 64 GB/s each way</li><li><a href="https://docs.nvidia.com/dgx/dgxh100-user-guide/introduction-to-dgxh100.html">NVIDIA DGX H100/H200 User Guide</a>: 2 TB memory, 8× 3.84 TB self-encrypting NVMe in RAID 0</li><li><a href="https://vllm.ai/blog/2026-01-08-kv-offloading-connector">vLLM: Inside vLLM’s new KV Offloading Connector</a>: about 50 GB/s measured one-way on H100, block sizes</li><li><a href="https://developers.redhat.com/articles/2026/11/02/benchmarking-tiered-kv-cache-offloading-h100-gpus-openshift-ai-3-5">Red Hat: Benchmarking tiered KV cache offloading on H100 GPUs</a>: 6.2 GB/s NVMe reads</li><li><a href="https://arxiv.org/html/2601.19910v1">Meng, Lee and Wang (arXiv 2601.19910)</a>: 15 GB/s sustained PCIe rate on H100</li><li><a href="https://www.storagereview.com/news/micron-7450-ssd-announced">StorageReview: Micron 7450 SSD specifications</a>: one drive write per day</li><li><a href="https://blog.lmcache.ai/en/2026/04/22/lmcache-on-amazon-sagemaker-hyperpod-accelerating-llm-inference-with-managed-tiered-kv-cache/">LMCache on Amazon SageMaker HyperPod</a>: time to first token under load on 8× H100</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=996781bd7658" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/when-the-kv-cache-spills-over-pcie-996781bd7658">When the KV Cache Spills Over PCIe</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PCIe in AI Inference: Where It Shines and Where It Lags]]></title>
            <link>https://pub.towardsai.net/pcie-in-ai-inference-where-it-shines-and-where-it-lags-ad862bd9e1ec?source=rss-6a54a072b0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad862bd9e1ec</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[aiml]]></category>
            <category><![CDATA[ai-infrastructure]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[pcie]]></category>
            <dc:creator><![CDATA[Srinivas kodali]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 07:09:24 GMT</pubDate>
            <atom:updated>2026-11-07T07:28:46.275Z</atom:updated>
            <content:encoded><![CDATA[<p>Nov 7, 2026 · @Srinivas Kodali</p><p>Most talk about AI inference hardware is about two things: HBM, the fast memory on the GPU, and NVLink, the fast link between GPUs. That makes sense. How fast a model produces each token depends mostly on those two.</p><p>PCIe gets much less attention, and it is often misjudged. Some people think PCIe servers can’t do serious inference. Others ignore PCIe until a model takes a minute to load, or a long chat suddenly slows down.</p><p>From the systems side of AI infrastructure, where GPUs connect to the rest of the server, PCIe looks different. The details that matter are how many PCIe lanes each device gets, the switches and signal boosters (retimers) in between, where the network cards and drives sit, and whether each link really runs at full speed. How a server is wired matters as much as which PCIe generation it uses. So the honest answer to “does PCIe slow inference down?” is: it depends.</p><p>This article follows the inference data path one link at a time. It uses only public specs, datasheets, model configs and published benchmarks. Where a number is calculated, the inputs are shown, so anyone can check it.</p><p>The short answer: PCIe works well when each GPU can do its job on its own. It struggles when GPUs must talk to each other for every token they produce, or when data has to come from outside GPU memory for every token.</p><h3>Where PCIe sits</h3><p>In a typical 8-GPU server, the GPUs talk to each other over NVLink. Almost everything else goes over PCIe. NVIDIA describes the usual PCIe server as two CPUs plus <a href="https://developer.nvidia.com/blog/?p=99991">two to four PCIe switches</a>. The switches connect the GPUs to each other and to the network cards.</p><p>A good public example is the <a href="https://docs.nvidia.com/dgx/dgxh100-user-guide/introduction-to-dgxh100.html">NVIDIA DGX H100</a>. It has eight H100 GPUs, two PCIe Gen5 Xeon CPUs, 2 TB of system memory, ten ConnectX-7 network cards and eight NVMe drives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61PeP9MEZjMl7HTQUbc69A.png" /></figure><p>During inference, PCIe carries four kinds of traffic:</p><ul><li>model weights coming in from storage</li><li>KV cache moving between the GPU and system memory</li><li>network traffic through the network cards</li><li>small control messages between the CPU and the GPUs</li></ul><p>On GPUs without NVLink, PCIe also carries all the GPU-to-GPU traffic.</p><h3>The numbers that matter</h3><p>A PCIe Gen5 x16 link moves about 64 GB/s in each direction, before overhead. An H100 GPU reads its own HBM at <a href="https://openzeka.com/wp-content/uploads/2023/12/h100-datasheet-1.pdf">3.35 TB/s</a>, about 50 times faster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtTEqoMM10EarkExQWSDEw.png" /></figure><p>Two things often confuse people when reading spec sheets.</p><p>First, GPU datasheets usually add both directions together. NVIDIA lists the H100’s PCIe link as 128 GB/s. But copying data from system memory into the GPU only uses one direction, so it gets half of that.</p><p>Second, these are raw numbers. Real copies are slower, because every packet carries extra header data. The real speed is best measured with NVIDIA’s free <a href="https://github.com/NVIDIA/nvbandwidth">nvbandwidth</a> tool, not taken from the datasheet.</p><p>One more thing from the chart: a Gen5 x16 slot has only about 28% more bandwidth than a 400 Gb/s network card needs. This matters later.</p><h3>While writing tokens, PCIe is mostly idle</h3><p>Take one example: <a href="https://arxiv.org/pdf/2407.21783">Llama 3.1 70B</a> in BF16 (2 bytes per number), running on eight H100 GPUs with tensor parallelism.</p><p>The model’s weights are about 141 GB: 70.6 billion parameters at 2 bytes each. Split across eight GPUs, each GPU holds about 17.6 GB. To write each new token, every GPU has to read all 17.6 GB from its HBM. At 3.35 TB/s, that alone takes about 5.3 ms.</p><p>During that time, very little crosses PCIe. A token ID goes in, and the chosen token comes back. Even copying the model’s full list of token scores (the logits) to the CPU is only about 0.5 MB (128,256 × 4 bytes). That takes about 8 microseconds on a Gen5 link, under 0.2% of the step.</p><p>Reading the prompt (prefill) needs a lot of compute, but its input is small too. A 128K-token prompt is only about 0.5 MB of token IDs.</p><p>So once the model is loaded and its KV cache fits in GPU memory, PCIe sits almost idle. The interesting part is what happens around that.</p><h3>Where PCIe shines</h3><h3>When each GPU runs its own copy of the model</h3><p>The clearest public evidence comes from MLPerf, the industry’s standard AI benchmark. In the <a href="https://soterralabs-site.pages.dev/anvil/mlperf">v5.1 round</a>, on Llama 2 70B:</p><ul><li>8-GPU HGX H200 systems, with NVLink, produced about 4,290 to 4,410 tokens per second per GPU in the offline test.</li><li>A 4-GPU server with H200 NVL cards, the PCIe version of the same chip, produced about 3,760.</li></ul><p>That’s 85 to 88% of the NVLink systems. In the server test, which adds response-time limits, it reached 80 to 83%.</p><p>The gap is small because NVLink is barely used here. H200 has enough memory that NVIDIA’s own submission <a href="https://developer.nvidia.com/blog/nvidia-h200-tensor-core-gpus-and-nvidia-tensorrt-llm-set-mlperf-llm-inference-records">doesn’t split the model across GPUs</a> for this benchmark. Each GPU works alone, so there’s little GPU-to-GPU traffic. The rest of the gap lines up with power: the PCIe card is limited to <a href="https://www.itcreations.com/nvidia-gpu/nvidia-h200-tensor-core-gpu">600 W instead of 700 W</a>, and its FP8 compute rating is <a href="https://elmark-automation.com/shop/nvidia-tesla-h200-nvl">about 84%</a> of the SXM version’s.</p><h3>Loading the model</h3><p>Loading the weights is the biggest single transfer an inference server makes. But storage is usually slower than PCIe, so storage sets the speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EeL8h47mj7oGEUM9jWbReA.png" /></figure><p>These are best-case numbers. In practice, reading files, unpacking the weights and setting up memory often take longer than the copy itself. Copying through system memory first adds more time, and <a href="https://docs.nvidia.com/gpudirect-storage/design-guide/index.html">GPUDirect Storage</a> avoids that extra step. PCIe only becomes the limit when the weights are already in system memory. That’s common when servers scale up and down, or switch between models.</p><h3>Bringing KV cache back</h3><p>This is where PCIe is most useful. The size of the KV cache is easy to work out from a model’s config:</p><p>2 (keys and values) × layers × KV heads × head size × bytes per value</p><p>For Llama 3.1 70B (80 layers, 8 KV heads, head size 128, BF16), that’s 320 KiB per token. A 128K-token conversation needs about 40 GiB, roughly half of an 80 GB H100, for just one user.</p><p>When that user comes back, the server has two choices: compute the cache again from the prompt, or load the saved copy from system memory. On eight H100s, recomputing 128K tokens takes about 4 × 1⁰¹⁶ operations, roughly half for the weights and half for attention. That’s about 5 seconds even at full speed, and closer to 10 seconds at a more typical 50% utilization. Loading the saved copy, 5 GiB per GPU over a Gen5 link, takes about a tenth of a second.</p><p>There’s a simple test that works for any model and GPU. Compare two numbers:</p><ul><li>the work to recompute one token (about 2 × parameters), divided by the bytes of KV cache for that token</li><li>the GPU’s compute speed, divided by the link speed</li></ul><p>If the first number is bigger, loading the saved copy wins. For the 70B model, the first number is about 430,000 operations per byte. On a Gen5 link, the second is about 15,000 for an H100 in BF16 and about 35,000 for a B200. So reloading wins by 12 to 28 times. And that’s before counting attention, whose cost grows with the square of the prompt length.</p><p>Open-source inference engines already work this way. vLLM’s <a href="https://docs.vllm.ai/en/latest/features/kv_offloading_usage/">OffloadingConnector</a> keeps finished KV blocks in pinned system memory. SGLang’s <a href="https://docs.sglang.io/docs/advanced_features/hicache_design">HiCache</a> uses GPU memory, system memory and storage as three cache levels.</p><h3>Where PCIe lags</h3><h3>Tensor parallelism without NVLink</h3><p>With tensor parallelism, every layer of the model is split across the GPUs. Each GPU computes part of the result, and then the GPUs add their parts together in an operation called an all-reduce. The standard design, from NVIDIA’s Megatron-LM, needs two all-reduces per layer when generating: one after the attention block and one after the MLP block.</p><p>Llama 3.1 70B has 80 layers, so every token needs 80 × 2 = 160 all-reduces. Each layer has to wait for its own all-reduce to finish before the next layer can start.</p><p>How much data does each all-reduce carry? One token’s activations are a vector of 8,192 numbers, the model’s hidden size. In BF16, that’s 8,192 × 2 bytes = 16 KiB. With one request at a time, each all-reduce moves only 16 KiB. That’s tiny, so the fixed delay of each trip matters more than bandwidth.</p><p>With more requests at once, the data grows. At a batch of 64 requests:</p><p>- each all-reduce carries 64 × 16 KiB = 1 MiB<br>- 160 all-reduces carry 160 MiB, about 168 MB per step<br>- on 8 GPUs, the common ring all-reduce makes each GPU send 2 × (8 − 1) / 8 = 1.75 times that amount, so about 290 MB per GPU per step</p><p>Moving 290 MB takes:</p><p>- about 0.65 ms over NVLink, at 450 GB/s per direction (half of the H100’s 900 GB/s total)<br>- about 4.6 ms over a PCIe Gen5 x16 link, at 64 GB/s</p><p>Each step already needs about 5.3 ms just to read the weights from HBM. So over PCIe, communication takes almost as long as the work itself. And 4.6 ms is a best case: it assumes the full 64 GB/s and no overlap with compute. Real copies run closer to 50 GB/s, each of the 160 all-reduces adds its own small delay, and NVIDIA notes that GPU-to-GPU traffic crossing between CPU sockets in a regular PCIe server can drop to 25 GB/s or less.</p><p>That’s why vLLM’s documentation recommends pipeline parallelism instead of tensor parallelism when GPUs don’t have NVLink. Where tensor parallelism on PCIe can’t be avoided, keep the group small and under one switch.</p><h3>Reading from outside GPU memory for every token</h3><p>Offloading works because the data comes back once and is then used from HBM. Keeping the weights, or the active KV cache, in system memory or CXL memory and reading them over PCIe for every token does not work. A Gen5 x16 link is about 50 times slower than HBM, so anything kept on the far side slows down by roughly that much.</p><h3>Network cards are outgrowing Gen5</h3><p>Gen5 servers are usually built with 400 Gb/s network cards, and for good reason. A 400 Gb/s card moves 50 GB/s in each direction, and a Gen5 x16 slot carries about 64 GB/s, so the card fits with about 28% to spare. The DGX H100, for example, uses ConnectX-7 cards at 400 Gb/s.</p><p>The next step, 800 Gb/s, moves 100 GB/s in each direction. That’s more than a Gen5 x16 slot can carry. A card that fast needs a Gen6 x16 link, or two Gen5 x16 links. That’s why NVIDIA’s ConnectX-8 moved to PCIe Gen6, with up to 48 lanes and a PCIe switch built in.</p><p>So 800 Gb/s cards are paired with Gen6 GPUs. <a href="https://www.tomshardware.com/pc-components/gpus/nvidia-shares-blackwell-ultras-secrets-nvfp4-boost-detailed-and-pcie-6-0-support">Blackwell Ultra</a> is the first data center GPU with a PCIe Gen6 x16 link, which carries about 128 GB/s each way, enough for 800 Gb/s. ConnectX-8 has a PCIe switch built in: in NVIDIA’s GB300 systems, it <a href="https://docs.nvidia.com/multi-node-nvlink-systems/grace-blackwell-cx8-gpudirect-rdma-guide/platform_software_and_configuration.html">connects to the GPU over Gen6 x16</a> and to the CPU over Gen5 x16. Network traffic goes straight from the GPU through the ConnectX-8 and never touches the CPU’s Gen5 link. Traffic to system memory, such as KV cache offload, still crosses Gen5. With Gen5 GPUs, an 800 Gb/s card is <a href="https://developer.nvidia.com/blog/?p=99991">shared by two GPUs</a> instead, giving each one 400 Gb/s, which fits its Gen5 link.</p><h3>Shared uplinks, when traffic goes to system memory</h3><p>Most PCIe traffic in an inference server never reaches the CPU. GPU-to-network traffic with GPUDirect RDMA, GPU-to-GPU copies under the same switch, and GPUDirect Storage reads from drives under the same switch all stay inside the switch. During steady token generation, the link from the switch up to the CPU is close to idle.</p><p>The uplink matters only for traffic to or from system memory: KV cache offload and reload, model loading from weights cached in system memory, and network traffic that falls back to system memory when GPUDirect RDMA is turned off, as in some virtual machines. Where two GPUs share one x16 uplink and both reload KV cache at the same time, each gets about half the link. Reloading 5 GiB per GPU then takes about 0.17 s instead of 0.08 s. That’s slower, but still far faster than the 5 to 10 seconds needed to recompute it. So shared uplinks are worth checking when offload is heavy, but they don’t change the bigger picture.</p><h3>What Gen6 and Gen7 change</h3><p>PCIe has roughly doubled its speed every three years. Gen6 (64 GT/s) <a href="https://convergedigest.com/pci-sig-targets-2028-release-of-pcie-8-0-at-256-gt-s/?amp=1">was released in 2022</a>, <a href="https://www.hpcwire.com/?p=181452">Gen7 (128 GT/s) in 2025</a>, and <a href="https://www.storagereview.com/news/pci-sig-unveils-pcie-8-0-256-gt-s-bandwidth-coming-by-2028">Gen8 (256 GT/s)</a> is planned for 2028.</p><p>To get there, Gen6 switched to PAM4 signaling, which needs error correction. Networking links that use PAM4 accept about 100 ns of delay for this. PCI-SIG instead aimed for <a href="https://snia.org/sites/default/files/SDC/2022/SNIA-SDC22-DasSharma-PCIe%206.0-Specification-and-Beyond-Enabling-Storage.pdf">under 10 ns of extra delay</a>, error correction included. So each generation doubles the bandwidth while the delay stays about the same.</p><p>For inference, that means big transfers, like model loading and KV cache reloads, get faster. Gen6 slots also let 800 Gb/s network cards run at full speed. But it doesn’t make token generation faster, and it doesn’t help much with small all-reduces, because those are limited by delay, not bandwidth.</p><p>One practical warning: every PCIe link sets its speed separately, and it runs at the highest generation both ends support. Data often crosses two or three links, for example GPU to switch to network card, and it moves only as fast as the slowest one. A Gen6 network card plugged in behind a Gen5 switch, or fed by a Gen5 GPU, gets Gen5 speed: about 64 GB/s instead of 128. So check every hop on the path with lspci -vv, comparing what each link can do (LnkCap) with what it is actually running at (LnkSta).</p><h3>A short checklist</h3><p>For inference on PCIe servers, these checks are the place to start:</p><ol><li>Run nvidia-smi topo -m. Keep tensor-parallel groups, and each GPU with its network card, under the same PCIe switch.</li><li>Look for links running below their capability. In lspci -vv, compare LnkSta (current) with LnkCap (maximum). A GPU that came up at x8 has lost half its bandwidth.</li><li>Measure with nvbandwidth instead of trusting the datasheet.</li><li>On bare metal, make sure PCI ACS isn’t forcing GPU-to-GPU traffic up through the CPU. NCCL’s <a href="https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/troubleshooting/gpu_troubleshooting.html">troubleshooting guide</a> explains how to check.</li><li>Use pinned system memory for KV cache offload, on the CPU socket closest to the GPU.</li><li>Count how many devices share each uplink before planning offload traffic.</li></ol><h3>Where PCIe shines, and where it lags</h3><p>PCIe works best when each GPU can do its job alone: one copy of the model per GPU, or per small group of GPUs joined by an NVLink bridge. PCIe then carries prompts, tokens and the occasional big transfer. In that setup, a server with H200 PCIe cards reached about 85–88% of an HGX system’s per-GPU speed on Llama 2 70B in MLPerf’s offline test. PCIe also handles model loading well, because storage is usually the slower part. And it makes KV cache offload worth it: reloading a long conversation’s cache from system memory is more than ten times faster than recomputing it, and CXL memory can add more room for that cache. Pipeline parallelism and separate model copies work well over PCIe, and these servers cost less, use less power and fit standard air-cooled racks.</p><p>PCIe lags when GPUs must talk all the time. With tensor parallelism, every token waits on 160 GPU-to-GPU syncs for a 70B model, long prompts can be slowed by communication, and traffic between CPU sockets can drop to 25 GB/s or less. It also lags when data must be read from outside GPU memory for every token, since a Gen5 x16 link is about 50 times slower than HBM. Two more weak spots are 800 Gb/s network cards in Gen5 x16 slots, and shared switch uplinks where offload, loading and network traffic compete. For models that need many GPUs working as one, such as 405B-class or large mixture-of-experts (MoE) models, a scale-up fabric like NVLink is still the better choice.</p><h3>References</h3><p><strong>Specs and standards</strong></p><ul><li><a href="https://www.hpcwire.com/?p=181452">PCI-SIG releases PCIe 7.0</a> (HPCwire, June 2025)</li><li><a href="https://www.storagereview.com/news/pci-sig-unveils-pcie-8-0-256-gt-s-bandwidth-coming-by-2028">PCI-SIG unveils PCIe 8.0</a> (StorageReview, August 2025)</li><li><a href="https://convergedigest.com/pci-sig-targets-2028-release-of-pcie-8-0-at-256-gt-s/?amp=1">PCI and PCIe generation history</a> (Converge Digest)</li><li><a href="https://snia.org/sites/default/files/SDC/2022/SNIA-SDC22-DasSharma-PCIe%206.0-Specification-and-Beyond-Enabling-Storage.pdf">PCIe 6.0 Specification and Beyond</a>, D. Das Sharma (SNIA SDC 2022)</li><li><a href="https://openzeka.com/wp-content/uploads/2023/12/h100-datasheet-1.pdf">NVIDIA H100 datasheet</a></li><li><a href="https://www.itcreations.com/nvidia-gpu/nvidia-h200-tensor-core-gpu">NVIDIA H200 SXM and NVL specifications</a> and <a href="https://elmark-automation.com/shop/nvidia-tesla-h200-nvl">H200 NVL Tensor Core figures</a></li><li><a href="https://dam-cdn.nvd.orangelogic.com/AssetLink/e4k1p5h7us424s6o4322743uo1lh4h6m.pdf">NVIDIA ConnectX-8 SuperNIC datasheet</a></li><li><a href="https://convergedigest.com/innodisk-unveils-pcie-gen5-ssd-series/?amp=1">Innodisk PCIe Gen5 SSD series</a> (Converge Digest)</li></ul><p><strong>Systems and benchmarks</strong></p><ul><li><a href="https://docs.nvidia.com/dgx/dgxh100-user-guide/introduction-to-dgxh100.html">NVIDIA DGX H100/H200 user guide</a></li><li><a href="https://developer.nvidia.com/blog/?p=99991">ConnectX-8 SuperNICs and PCIe Gen6 platform architecture</a> (NVIDIA Technical Blog, May 2025)</li><li><a href="https://soterralabs-site.pages.dev/anvil/mlperf">MLPerf Inference v5.1, Llama 2 70B results</a> (aggregated from MLCommons)</li><li><a href="https://developer.nvidia.com/blog/nvidia-h200-tensor-core-gpus-and-nvidia-tensorrt-llm-set-mlperf-llm-inference-records">NVIDIA H200 and TensorRT-LLM MLPerf results</a> (NVIDIA Technical Blog)</li><li><a href="https://docs.nvidia.com/multi-node-nvlink-systems/grace-blackwell-cx8-gpudirect-rdma-guide/platform_software_and_configuration.html">NVIDIA: Grace Blackwell + ConnectX-8 GPUDirect RDMA guide</a></li><li><a href="https://www.tomshardware.com/pc-components/gpus/nvidia-shares-blackwell-ultras-secrets-nvfp4-boost-detailed-and-pcie-6-0-support">Tom’s Hardware: Blackwell Ultra PCIe 6.0 support</a></li><li><a href="https://wccftech.com/nvidia-connectx-8-supernic-designed-for-blackwell-systems-pcie-g6-800gbe-speed/">Wccftech: ConnectX-8 for Blackwell systems</a></li><li><a href="https://www.servethehome.com/gigabyte-w775-v10-l01-hands-on-bringing-nvidia-gb300-deskside/7/">ServeTheHome: GB300 deskside ConnectX-8 measurements</a></li><li><a href="https://developer.nvidia.com/blog/nvidia-connectx-8-supernics-advance-ai-platform-architecture-with-pcie-gen6-connectivity">NVIDIA: ConnectX-8 and PCIe Gen6 platform architecture</a></li></ul><p><strong>Models and software</strong></p><ul><li><a href="https://arxiv.org/pdf/2407.21783">The Llama 3 Herd of Models</a> (Meta, arXiv 2407.21783)</li><li><a href="https://docs.vllm.ai/en/latest/features/kv_offloading_usage/">vLLM KV Offloading Usage Guide</a> and <a href="https://docs.vllm.ai/serving/parallelism_scaling.html">vLLM Parallelism and Scaling</a></li><li><a href="https://docs.sglang.io/docs/advanced_features/hicache_design">SGLang HiCache system design</a></li><li><a href="https://docs.nvidia.com/gpudirect-storage/design-guide/index.html">NVIDIA GPUDirect Storage design guide</a></li><li><a href="https://github.com/NVIDIA/nvbandwidth">NVIDIA nvbandwidth</a></li><li><a href="https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/troubleshooting/gpu_troubleshooting.html">NCCL GPU troubleshooting guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad862bd9e1ec" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/pcie-in-ai-inference-where-it-shines-and-where-it-lags-ad862bd9e1ec">PCIe in AI Inference: Where It Shines and Where It Lags</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When 100% GPU Utilization Is Good — and When It Is Not]]></title>
            <link>https://medium.com/@srinivascoolguy/when-100-gpu-utilization-is-good-and-when-it-is-not-fb8febc6988b?source=rss-6a54a072b0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb8febc6988b</guid>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ai-infrastructure]]></category>
            <category><![CDATA[gpu-utilization]]></category>
            <category><![CDATA[high-perfomance-computing]]></category>
            <dc:creator><![CDATA[Srinivas kodali]]></dc:creator>
            <pubDate>Tue, 16 Dec 2025 18:58:08 GMT</pubDate>
            <atom:updated>2025-12-16T18:58:08.662Z</atom:updated>
            <content:encoded><![CDATA[<h3>When 100% GPU Utilization Is Good — and When It Is Not</h3><h3>A practical look at GPU SMs, and performance trade-offs in model execution</h3><h3>TL;DR</h3><ul><li><strong>100% GPU utilization does not automatically mean optimal performance</strong></li><li>During training, running multiple models improves <em>GPU efficiency</em> but <strong>reduces per-model speed</strong></li><li>During inference, co-locating models is often the <em>right</em> strategy</li><li>The real optimization question is <strong>what metric matters: time-to-train, latency, or cost?</strong></li></ul><h3>The Common Misconception About GPU Utilization</h3><p>GPU dashboards love to show a single, comforting number: <strong>GPU utilization</strong>. When it reads 100%, it feels like the system is perfectly optimized.</p><p>In reality, that number often hides more than it reveals.</p><p>During deep learning training workloads, GPUs can appear fully utilized while memory remains partially idle, CPUs quietly bottleneck progress, and adding another model keeps utilization at 100% — but slows everything down. Understanding why requires looking beyond surface-level metrics and into how GPUs actually schedule work.</p><p>This article breaks down what 100% GPU utilization really means in practice, using GPT-2 training behavior to explain the roles of Streaming Multiprocessors (SMs), and the trade-offs between performance and efficiency.</p><h3>Experimental Context</h3><p>The behavior described below is based on <strong>GPT-2 training workloads</strong> executed with:</p><ul><li><strong>PyTorch</strong></li><li><strong>Bare-metal deployment</strong></li><li><strong>Two NVIDIA A10 GPUs</strong></li><li>Independent training processes</li></ul><p>The focus is on <strong>resource behavior</strong>, not absolute performance numbers.</p><h3>Case 1: Single Training Job</h3><p>When a single GPT-2 training job runs across both GPUs, the following pattern is commonly observed.</p><h3>Observed Behavior</h3><ul><li><strong>GPU utilization:</strong> ~100%</li><li><strong>GPU memory usage:</strong> ~50% per GPU</li></ul><figure><img alt="GPU Utilization Graph" src="https://cdn-images-1.medium.com/max/1024/1*6YKCM5u_JtcQKnQlu5gg6w.png" /><figcaption>GPU Utilization at ~100% but the memory at ~50%</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASrXrMSBxYBJxxKoJgwZmA.png" /><figcaption>nvidia-smi showing ~50% memory usage</figcaption></figure><h3>What This Pattern Indicates</h3><p>Despite the GPU being fully busy:</p><ul><li>The workload is <strong>compute-bound</strong></li><li>GPU memory capacity is <strong>only partially used</strong></li><li>There is sufficient memory headroom for additional workloads</li></ul><p><strong><em>A GPU can be compute-saturated while still having significant free memory.</em></strong></p><h3>Case 2: Two Concurrent Training Jobs</h3><p>When a second identical GPT-2 training job is introduced and runs concurrently:</p><ul><li>Both jobs share the same GPUs</li><li>Each job executes as an independent PyTorch process</li></ul><h3>Observed Behavior Under Contention</h3><h3>GPU Compute</h3><ul><li><strong>Total GPU utilization:</strong> ~100%</li><li>Compute time is <strong>shared between processes</strong></li></ul><h3>GPU Memory</h3><ul><li><strong>Memory usage:</strong> ~100% per GPU</li><li>Each process consumes approximately <strong>50% of GPU memory</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jMwAgZuT-20yf67kVjmSUQ.png" /><figcaption>Graph showing increasing the Memory Usage with shared GPU Utilization</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwUQeaMxM_N6p8oFiqiWug.png" /><figcaption>nvidia-smi process view with two 2 jobs</figcaption></figure><h3>The Key Insight: Utilization Is Not Performance</h3><p>At this point, GPU utilization remains unchanged, yet the system behavior is fundamentally different.</p><p><strong><em>The GPU does not become faster — it becomes more contested.</em></strong></p><p>What changes internally:</p><ul><li>SM time is divided</li><li>Each training job receives fewer compute cycles</li><li>Training throughput per job decreases</li></ul><p>At the same time:</p><ul><li>Overall GPU efficiency increases</li><li>More total work is completed per GPU-hour</li></ul><h3>Does GPU Sharing Reduce Performance?</h3><p><strong>Yes — for individual training jobs.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*QIS1V5AFJvDgJ8oJHHAoGQ.png" /><figcaption>Comparison</figcaption></figure><p>This trade-off is unavoidable when compute resources are shared.</p><h3>Is 100% GPU Utilization Good or Bad?</h3><p>Neither — it is <strong>context-dependent</strong>.</p><h3>When Fast Training Matters</h3><ul><li>Run <strong>one training job per GPU</strong></li><li>Avoid GPU over-subscription</li><li>Scale using data parallelism</li></ul><blockquote><strong><em>For training, isolation consistently delivers the best time-to-train.</em></strong></blockquote><h3>When Cost Efficiency or Throughput Matters</h3><ul><li>Co-locate multiple workloads</li><li>Increase memory utilization</li><li>Accept slower per-job execution</li></ul><blockquote><strong><em>For inference and multi-tenant systems, sharing is often the optimal design.</em></strong></blockquote><h3>GPU Utilization vs Memory Utilization</h3><p>Asking which metric is “more important” misses the point.</p><h3>Training Workloads</h3><ul><li>Compute is the limiting factor</li><li>Memory only needs to be sufficient</li><li>Excess memory does not improve training speed</li></ul><p><strong>Optimize for compute isolation</strong></p><h3>Inference Workloads</h3><ul><li>Compute is often underutilized</li><li>Memory becomes the dominant constraint</li><li>Packing models improves efficiency</li></ul><p><strong>Optimize for memory utilization</strong></p><h3>GPU Utilization: What 100% Really Means</h3><p>GPU utilization is primarily a measure of how busy the GPU’s <strong>Streaming Multiprocessors (SMs)</strong> are.</p><h3>What Is an SM?</h3><p>An <strong>SM (Streaming Multiprocessor)</strong> is the fundamental compute block inside an NVIDIA GPU. Each SM contains:</p><ul><li>CUDA cores</li><li>Tensor Cores (for matrix and AI workloads)</li><li>Schedulers</li><li>Registers and shared memory</li></ul><p>SMs execute GPU threads in groups called <strong>warps</strong> (32 threads) and rapidly switch between warps to keep execution units busy.</p><blockquote><em>You can think of SMs as the GPU equivalent of CPU cores — except each SM runs thousands of threads over time.</em></blockquote><h3>Interpreting 100% GPU Utilization</h3><p>When GPU utilization shows <strong>~100%</strong>, it means:</p><ul><li>Most or all SMs are continuously scheduled</li><li>There are no idle gaps in kernel execution</li><li>The GPU is <em>busy</em>, not necessarily <em>optimal</em></li></ul><p>Importantly:</p><blockquote><strong><em>100% GPU utilization means SM time is fully allocated — it does not mean the GPU cannot accept more work.</em></strong></blockquote><p>As seen with concurrent GPT-2 training jobs, additional workloads can still be admitted if:</p><ul><li>Memory capacity is available, and</li><li>The system is willing to share SM time</li></ul><p>In such cases:</p><ul><li>GPU utilization remains at 100%</li><li>SMs are time-sliced across processes</li><li><strong>Per-job performance decreases</strong>, even though the GPU appears fully utilized</li></ul><h3>Final Verdict</h3><blockquote><strong><em>100% GPU utilization is a scheduling outcome, not a performance guarantee.</em></strong></blockquote><ul><li>In training, it can signal contention</li><li>In inference, it often signals efficiency</li></ul><p>The correct optimization target depends on whether the goal is <strong>time-to-train, latency, or cost per GPU-hour</strong>.</p><h3>Key Takeaway</h3><blockquote><em>GPUs should not be optimized to look busy — they should be optimized to deliver the right outcome.</em></blockquote><p>Sometimes that means one model per GPU.<br>Sometimes it means many.</p><p>Understanding the difference is the foundation of effective GPU system design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb8febc6988b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Memory Allocation — GLIBC Way]]></title>
            <link>https://medium.com/@srinivascoolguy/dynamic-memory-allocation-glibc-way-c4ffdb618aba?source=rss-6a54a072b0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4ffdb618aba</guid>
            <category><![CDATA[malloc-internal]]></category>
            <dc:creator><![CDATA[Srinivas kodali]]></dc:creator>
            <pubDate>Sat, 25 Jul 2020 20:57:51 GMT</pubDate>
            <atom:updated>2020-07-25T20:57:51.483Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dynamic Memory Allocation — GLIBC Way</h3><p>How to create a memory while a program is in execution state(run time).<br>Well, The Answer is the famous API <em>malloc()</em>.</p><p>But, Where it is implemented? How it is implemented?<br>Is it compiler specific? Or a separate library? <br>Implementation changes version to version? …<br>Still more questions? Let’s unfold them one by one.</p><p><em>malloc()</em> is implemented as part of C library(libc).</p><p>We have different implementation of C libraries.<br>GNU C library — glibc, the most widely used library in the linux distributions. Most of the generic implementations, man pages talks about GNU implementations due its wide coverage.</p><p>musl libc, uClibc — are the other C libraries which are used mostly in embedded Linux systems due to their less memory footprint and the limited features which are required for specific applications.</p><p>Now we understand to use <em>malloc()</em> API we require a raw material such as C library. And creating an application is not possible without a compiler.<br>Like, C libraries we have different compilers available. But we stick to the well known and most widely used GNU Compiler Collection- GCC.</p><p>As the Computers are evolving day by day, to make <em>malloc()</em> more effective to match the new architectures, the <em>malloc()</em> implementation varies between the library versions.</p><p>How to know which version of glibc is used in the installed compiler(gcc, in our case) on your computer?<br>gcc toolchain provides <strong><em>gnu_get_libc_version()</em></strong> API to identify the glibc version which it is used. This api is declared in “<em>gnu/libc-version.h</em>”</p><blockquote>#include &lt;stdio.h&gt;<br>#include &lt;gnu/libc-version.h&gt;<br>int main() {<br> printf(“libc version: %s\n”, <strong>gnu_get_libc_version()</strong>);<br>}<em><br>Output: </em>libc version: 2.27</blockquote><p>There is no need to have the same versions for both gcc &amp; glibc.<br>Gcc version can be obtained by executing the following command on terminal.</p><blockquote>gcc -v<br><em>gcc version 7.5.0 (Ubuntu 7.5.0–3ubuntu1~18.04)</em></blockquote><p>We all set to deep dive in to the malloc() implementation with library glibc-2.27.</p><blockquote>void *malloc(size_t size) API allocates size bytes and returns a pointer to the allocated memory.</blockquote><p>In fact, malloc() API internally works with chunks(memory). A chunk is a block of memory which contains the size requested by user and the information about the requested size and its status.</p><p>Internal implementation of chunk as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*9P13pnZSCaC1zB6Fo2S1Ng.png" /><figcaption>malloc_chunk representation</figcaption></figure><p>From the above representation, mem is the actual pointer returned by malloc() API. chunk is the pointer to hold the information about the user memory requested. <br>For every malloc() call a chunk is created, and all the chunks are continuous in Heap memory of a process. <br>The structure representation of chunk as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*mAG-t-b8nK4ZBHLNp0qRLQ.png" /><figcaption>malloc_chunk structure</figcaption></figure><p>From the above structure, “struct malloc_chunk* fd” is the actual pointer which returned by malloc() API and holds the user requested data.<br>An extra 2*8 bytes of memory is created to hold the user requested size information. <br>mchunk_size represents the current chunk size(extra padded bytes of 16 + user requested data). Also last 3 bits represents AMP flags, which we will discuss later.<br>mchunk_size represents the previous chunk size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*7DflGjaQdOvTktSj_iOEMw.png" /><figcaption>Source for demonstration</figcaption></figure><p>The above source code is to print chunk information for requested size.<br>Here three sizes 6,25,0 allocated using malloc() API. And as discussed earlier additional 16 bytes will be allocated for padding. Guess the chunk size with the information we have so far.<br>To calculate the chunk size, a logic has been used( &amp; ~0x7). Could you guess the reason for this? Yes, you are pretty close. This is for additional AMP flags which are part of member chunk_size. If we do not ignore those flags the chunk size will be more by the value of flags.<br>A: NON_MAIN_ARENA, If this bit is cleared, chunks belongs to main arena(This is not relevant for our topic, can be ignored). <br>M: IS_MAPPED, if bit is set, the chunk is allocated via mmap directly and other 2 bits (A &amp; P) will be ignored.<br>P: PREV_INUSE, This represents the previous chunk is in use. If this bit is 0, size of previous chunk is updated.</p><p>The output of the above source as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*rqP7coHfCe8Rj8fzubW_VA.png" /><figcaption>Output</figcaption></figure><p>For requested memory of 6 bytes, a total of 32 bytes allocated. But it should be 6 + 16 = 22 bytes. Why additional 10 bytes are padded?<br>Additional bytes are padded because, The smallest chunk size is 32. So even 6 bytes are requested the chunk is allocated for 32 bytes.</p><p>For requested memory of 25 bytes, a total of 48 bytes allocated. But it should be 41 as the minimum chunk size criteria is matched???<br>Chunk size should be 32(minimum size) or multiple of 16 bytes.</p><p>For requested memory of 0 bytes, Why malloc allocated chunk instead of returning a failure?<br>malloc() allocates a minimum chunk(32 bytes) first and increments it later. So even for malloc(0), smallest possible chunk is created internally.</p><blockquote>How to identify the chunk size with pointer returned by malloc()?<br>Void* ptr=malloc(16);<br>size_t *chunk_size = ptr;<br>chunk_size[-1] &amp; ~0x07; &lt;&lt;&lt; Gives the chunk size directly,</blockquote><p>void *free(void *ptr) API frees the memory pointed by ptr, and it must have been returned by malloc() API. <br>Anytime, did u get the question how free() API knows the number of bytes to be cleared with only one pointer? This is what we have discussed so far. Actually free will simply alter the flags</p><p>It is clear that free() can frees the memory which is returned by malloc(). <br>If invalid address(which is not returned by malloc) is passed to free(), it will fail or undefined behavior can occur.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4ffdb618aba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Custom kernel on Ubuntu]]></title>
            <link>https://medium.com/@srinivascoolguy/building-custom-kernel-on-ubuntu-3a9e0df8e66f?source=rss-6a54a072b0e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a9e0df8e66f</guid>
            <category><![CDATA[compile-kernel]]></category>
            <category><![CDATA[building-linux]]></category>
            <category><![CDATA[build-linux-source]]></category>
            <dc:creator><![CDATA[Srinivas kodali]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 08:28:38 GMT</pubDate>
            <atom:updated>2020-06-02T08:42:59.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*9cpWWnjJZKG7yj73U-G5zA.jpeg" /></figure><p>The following are the dependencies to be met on the linux machine(Ubuntu).</p><p><strong>Dependencies:</strong></p><p><em>kernel-package</em></p><p><em>libncurses5-dev</em></p><p><em>wget</em></p><p><em>tar</em></p><p><em>make</em></p><p><em>gcc</em></p><p><em>flex</em></p><p><em>bison</em></p><p><em>libelf-dev/libelf-devel/elfutils-libelf-devel</em></p><p><em>libssl-dev/openssl-devel</em></p><p><strong>Downloading the kernel:</strong></p><blockquote>A kernel source is require to build it. It is recommended to use the kernel source from the official release which is available in kernel.org.</blockquote><p>Select the kernel based on host OS kernel version. Host kernel version can be checked by issuing the command ‘uname -a’ on a terminal.</p><p>wget <a href="https://www.kernel.org/pub/linux/kernel/v5.x/linux-5.3.tar.gz">https://www.kernel.org/pub/linux/kernel/v5.x/linux-5.3.tar.gz</a></p><p><em>“My host has linux-5.3, So downloaded linux-5.3”</em></p><p><strong>Building the kernel:</strong></p><p>It is a good practice to keep and build the kernel source from “/usr/src/” directory.</p><p>cd /usr/src</p><p>Download the kernel and untar it. If the source is already available copy here.</p><p><em>wget </em><a href="https://www.kernel.org/pub/linux/kernel/v5.x/linux-5.3.tar.xz"><em>https://www.kernel.org/pub/linux/kernel/v5.x/linux-5.3.tar.xz</em></a></p><p><em>tar -xz linux-5.3.tar.gz</em></p><p><em>ln -s linux-5.3 linux</em>(optional step. shorter names are easy for traversal)</p><p>Change the directory to linux(if link created or linux-5.3). It depends on the kernel version.</p><p><em>cd linux/</em></p><p>Select a default config based on the architecture, which kernel is going ot be installed. In my case, x86_64 is used. This information can get from ‘uname -a’</p><p><em>make ARCH=x86_84 defconfig</em></p><p>If required modify the configuration using “make menuconfig” and save it.</p><p>Its time to compile the kernel. Use the following command to do the same.</p><p><em>make -j40</em></p><p>Let the kernel build by taking its own time… have coffee, snacks… if possible dinner….</p><p><strong>Install the kernel:</strong></p><p><em>make modules_install</em></p><p><em>make install</em></p><p>This step does the following things:</p><p>copy the bzimage,vmlinuz &amp; initrd.img from arch/&lt;x86_64&gt;/bzImage to /boot/bzIMage-kernelversion</p><p>copy the System.map to /boot/System.map-&lt;kerneversion&gt;</p><p>copy the config to /boot/config-&lt;kernelversion&gt;</p><p><strong>Updating the grub config:</strong></p><p>Ubuntu uses grub loader to load the kernel on boot. grub config to be updated to load it the same on from next boot.</p><p>update-initramfs -c -k &lt;kernelversion&gt;. <br>update-grub</p><p>Here kernelversion is the variable and its value is equals to custom kernel version. This can be obtained from “make kernelversion”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a9e0df8e66f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>