<?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 Ankush Dhanda on Medium]]></title>
        <description><![CDATA[Stories by Ankush Dhanda on Medium]]></description>
        <link>https://medium.com/@ankushwork21?source=rss-6027130df4cf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*I1ctu3yeR92TclQplAAi4A.jpeg</url>
            <title>Stories by Ankush Dhanda on Medium</title>
            <link>https://medium.com/@ankushwork21?source=rss-6027130df4cf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:41:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankushwork21/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[How GPUs Actually Run LLMs: CUDA, Tensor Cores, and the Memory Bandwidth Bottleneck]]></title>
            <link>https://medium.com/@ankushwork21/how-gpus-actually-run-llms-cuda-tensor-cores-and-the-memory-bandwidth-bottleneck-50bb093c3137?source=rss-6027130df4cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/50bb093c3137</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <dc:creator><![CDATA[Ankush Dhanda]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 13:44:42 GMT</pubDate>
            <atom:updated>2026-10-25T13:44:42.792Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 3 of LLM Inference Engineering — Understanding how GPUs execute transformer computations, why memory bandwidth matters, and how batching improves inference performance.</em></p><h3>Introduction: Why Doesn’t a Powerful GPU Generate Tokens Instantly?</h3><p>Modern GPUs can perform trillions of mathematical operations every second.</p><p>An NVIDIA RTX 3090, for example, has more than 10,000 CUDA cores, specialized Tensor Cores, and 24 GB of video memory.</p><p>That sounds like enormous computational power.</p><p>Yet when we run a large language model, generating text can still be surprisingly slow.</p><p>Why?</p><p>If a GPU can execute so many calculations in parallel, why might generating just one additional token take several milliseconds?</p><p>The answer is that <strong>GPU performance depends not only on how quickly calculations can be performed, but also on how quickly the required data can reach the computational hardware.</strong></p><p>This distinction is particularly important for LLM inference.</p><p>In this article, we’ll explore GPU architecture, CUDA programming, memory bandwidth, arithmetic intensity, and the differences between the prefill and decode phases.</p><p>We’ll also perform a small experiment using a real model’s weight dimensions to understand why processing multiple tokens together can be more efficient than processing them individually.</p><p>The goal is simple:</p><p><strong>We want to understand what actually limits LLM inference performance before attempting to optimize it.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g65HpuM8p6x87edLv1QOuQ.png" /></figure><h3>1. What Kind of Computation Does an LLM Perform?</h3><p>In our previous article, we explored how transformer models contain learned numerical parameters called weights.</p><p>One example was a Query projection matrix from Qwen2.5–0.5B-Instruct.</p><p>Its dimensions were:</p><p>896 rows × 896 columns.</p><p>During inference, the model uses this matrix to transform a token’s hidden representation.</p><p>This is a matrix-vector multiplication.</p><p>Imagine an input vector containing 896 numbers.</p><p>The model multiplies that input by its learned weight matrix to produce an output containing another 896 numbers.</p><p>How many calculations are involved?</p><p>First, calculate the number of weight elements:</p><p>896 × 896 = 802,816</p><p>Each weight contributes to a multiplication and accumulation.</p><p>Using the common approximation of two floating-point operations per multiply-accumulate:</p><p>2 × 896 × 896 ≈ 1.61 million FLOPs</p><p><strong>Just one projection for one token involves approximately 1.61 million floating-point operations.</strong></p><p>Now imagine a transformer with 24 layers, multiple attention projections in each layer, and large feed-forward networks.</p><p>A modern LLM may contain billions of parameters.</p><p>During token generation, many of these weights participate in computation repeatedly.</p><p>Fortunately, much of the mathematical work can be parallelized.</p><p>That is why GPUs are so useful for LLM inference.</p><h3>2. Why Are GPUs Better Suited Than CPUs for This Work?</h3><p>CPUs and GPUs are both processors, but they are designed around different priorities.</p><h3>CPUs: Flexible and Latency-Oriented</h3><p>A CPU is designed for a wide range of operations.</p><p>It handles operating-system tasks, application logic, interrupts, branching, memory management, and sequential computation.</p><p>Modern CPU cores use sophisticated techniques such as branch prediction, caching, and out-of-order execution.</p><p>These capabilities make CPUs very effective at handling diverse, complex workloads.</p><h3>GPUs: Designed for Parallel Throughput</h3><p>A GPU is designed to perform large numbers of similar operations on different data elements.</p><p>Imagine we have one million numbers that must each be multiplied by another number.</p><p>If the calculations are independent, many can happen in parallel.</p><p>A GPU has substantial hardware dedicated to this kind of high-throughput execution.</p><p>The difference can be summarized like this:</p><p><strong>CPU characteristics:</strong></p><ul><li>Designed for versatile workloads.</li><li>Relatively fewer, sophisticated cores.</li><li>Strong performance for complex control flow.</li><li>Often responsible for coordinating the application.</li></ul><p><strong>GPU characteristics:</strong></p><ul><li>Designed for highly parallel workloads.</li><li>Large numbers of arithmetic execution resources.</li><li>High throughput for suitable numerical operations.</li><li>Particularly effective for tensor and matrix computations.</li></ul><p>This doesn’t mean that GPUs are always faster.</p><p>A very small operation may execute more efficiently on a CPU because launching work on the GPU introduces overhead.</p><p>But transformer models perform enormous quantities of regular numerical computation.</p><p>This makes them excellent candidates for GPU acceleration.</p><h3>3. Understanding GPU Architecture: SMs, CUDA Cores, and Tensor Cores</h3><p>Let’s use the NVIDIA RTX 3090 as our reference GPU.</p><p>Some relevant specifications are:</p><ul><li>GPU architecture: NVIDIA Ampere.</li><li>Streaming Multiprocessors: 82.</li><li>CUDA cores: 10,496.</li><li>Tensor Cores: 328.</li><li>VRAM: 24 GB GDDR6X.</li><li>Peak theoretical memory bandwidth: approximately 936 GB/s.</li><li>CUDA compute capability: 8.6.</li></ul><p>These specifications describe different hardware resources.</p><p>To understand them, let’s begin with the Streaming Multiprocessor.</p><h3>What Is a Streaming Multiprocessor?</h3><p>A Streaming Multiprocessor, or SM, is one of the GPU’s main execution units.</p><p>It contains resources responsible for scheduling and executing GPU work.</p><p>An SM includes arithmetic execution units, warp schedulers, registers, shared memory, and specialized computational resources.</p><p>A GPU contains multiple SMs working concurrently.</p><p>The RTX 3090 has 82 of them.</p><h3>What Are CUDA Cores?</h3><p>CUDA cores are arithmetic execution resources within the GPU.</p><p>They perform operations such as floating-point arithmetic.</p><p>However, an important distinction is that <strong>a CUDA core is not the same thing as a CPU core or a CUDA software thread</strong>.</p><p>When a CUDA program launches thousands of threads, those threads are scheduled onto the GPU’s available execution resources.</p><p>Having 10,496 CUDA cores does not mean that exactly 10,496 application requests can execute simultaneously.</p><h3>What Are Tensor Cores?</h3><p>Tensor Cores are specialized hardware units designed to accelerate supported matrix operations.</p><p>This matters because transformer models perform a tremendous number of matrix multiplications.</p><p>Optimized kernels can use Tensor Core instructions to achieve substantially higher throughput for suitable operations.</p><p>For example, FP16 and BF16 matrix operations commonly benefit from Tensor Core acceleration.</p><p>But software must actually use a compatible kernel and data layout.</p><p><strong>A GPU having Tensor Cores does not automatically mean that every mathematical operation uses them.</strong></p><p>This is one reason inference frameworks and optimized GPU libraries matter so much.</p><h3>4. What Exactly Is CUDA?</h3><p>Now that we understand the hardware, how do applications tell the GPU what to do?</p><p>CUDA is NVIDIA’s parallel computing platform and programming model.</p><p>It allows developers and software frameworks to execute parallel workloads on NVIDIA GPUs.</p><p>A simplified software execution path looks like this:</p><p>Application → PyTorch or inference engine → GPU kernels and libraries → CUDA driver → NVIDIA GPU</p><h3>What Is a CUDA Kernel?</h3><p>A CUDA kernel is a function executed on the GPU.</p><p>Let’s consider a simple example.</p><p>Suppose we have two arrays:</p><p>A = [1, 2, 3, 4]</p><p>B = [5, 6, 7, 8]</p><p>We want to calculate:</p><p>C = [6, 8, 10, 12]</p><p>Each element can be calculated independently.</p><p>One CUDA thread could calculate C[0].</p><p>Another could calculate C[1].</p><p>Other threads could calculate the remaining elements.</p><p>A simple CUDA C++ kernel looks like this:</p><pre>__global__ void vectorAdd(<br>    const float* A,<br>    const float* B,<br>    float* C,<br>    int N<br>) {<br>    int i = blockIdx.x * blockDim.x<br>          + threadIdx.x;<br>    if (i &lt; N) {<br>        C[i] = A[i] + B[i];<br>    }<br>}</pre><p>Each thread uses its index to identify which element to process.</p><p>This is a simple illustration of parallel execution.</p><p>A complete application would also allocate memory, prepare inputs, launch the kernel, and retrieve the results.</p><h3>Threads, Blocks, Grids, and Warps</h3><p>CUDA organizes work using several concepts.</p><p><strong>Thread:</strong> One logical execution instance of a GPU kernel.</p><p><strong>Thread block:</strong> A collection of threads that can cooperate using shared memory and synchronization.</p><p><strong>Grid:</strong> The collection of thread blocks launched for a kernel.</p><p><strong>Warp:</strong> A group of 32 CUDA threads on NVIDIA GPUs.</p><p>When a kernel launches, the GPU schedules thread blocks onto available SMs.</p><p>Threads within those blocks are organized into warps for instruction execution.</p><p>A useful detail is that the GPU can have far more logical threads than physical execution units.</p><p>The hardware schedules this work over time.</p><p>For example, a block containing 256 threads is organized into eight warps.</p><p>Multiple warps may be resident on an SM. While one warp waits for data, another ready warp may execute.</p><p>This is one mechanism GPUs use to hide memory latency.</p><h3>Where Do PyTorch and vLLM Fit?</h3><p>When a developer performs a matrix multiplication using GPU-resident PyTorch tensors, PyTorch can dispatch the work to suitable GPU libraries or kernels.</p><p>Similarly, vLLM uses optimized execution paths for transformer inference.</p><p>The user doesn’t normally write CUDA kernels manually.</p><p>But understanding how those kernels operate helps us reason about performance.</p><h3>5. Understanding GPU Memory: Registers, Cache, and VRAM</h3><p>Now we reach one of the most important topics in GPU performance.</p><p>A GPU contains different levels of memory.</p><p>These memories have different capacities, access characteristics, and purposes.</p><h3>Registers</h3><p>Registers provide very fast storage used by executing threads.</p><p>They hold values needed during computation.</p><p>However, register capacity is limited.</p><h3>Shared Memory</h3><p>Shared memory is on-chip storage accessible to threads within the same thread block.</p><p>It is useful when threads need to reuse data or cooperate.</p><h3>L1 and L2 Cache</h3><p>Caches help reduce the need to repeatedly access slower levels of memory.</p><p>L1 caching operates close to SM execution resources.</p><p>L2 cache is shared across the GPU’s SMs.</p><h3>Global GPU Memory — VRAM</h3><p>VRAM provides the large storage capacity used for model weights, token activations, KV caches, and other runtime data.</p><p>Our reference RTX 3090 has 24 GB of GDDR6X VRAM.</p><p>That is enough to hold many small and medium-sized models entirely on the GPU.</p><p>But there’s an important distinction:</p><p><strong>Storing something in VRAM is not the same as having it immediately available inside the arithmetic execution units.</strong></p><p>The GPU still needs to access the data through its memory hierarchy.</p><p>This is where memory bandwidth becomes important.</p><h3>6. Why Does Memory Bandwidth Matter if the Model Is Already in VRAM?</h3><p>This question confused me initially because the obvious assumption is:</p><p>“If the model weights are already loaded on the GPU, why would memory access still be a bottleneck?”</p><p>The answer comes from understanding where the weights are stored versus where calculations happen.</p><p>Let’s consider a hypothetical 7-billion-parameter model using FP16 weights.</p><p>Each parameter occupies 2 bytes.</p><p>Therefore:</p><p>7 billion parameters × 2 bytes = 14 GB</p><p>The model occupies approximately 14 GB of raw weight storage.</p><p>Suppose we load all these weights into GPU VRAM.</p><p>Now the model is resident on the GPU.</p><p>During inference, the arithmetic units still need to access those weights.</p><p>A 14 GB model cannot fit entirely inside the small on-chip registers and caches.</p><p>Large quantities of weight data must be read from VRAM as the model executes.</p><p>This leads to two different types of data movement.</p><p><strong>Model loading:</strong></p><p>The model checkpoint is read from storage and its weights are placed on the GPU.</p><p>This normally happens when the model is initialized, not on every token.</p><p><strong>Model execution:</strong></p><p>The GPU repeatedly accesses the resident weight tensors to perform matrix operations.</p><p>This happens during inference.</p><p>The second kind of movement is why VRAM bandwidth remains important even after the model has finished loading.</p><h3>7. VRAM Capacity vs Memory Bandwidth</h3><p>These two specifications answer entirely different questions.</p><h3>VRAM Capacity</h3><p>How much data can the GPU hold?</p><p>For the RTX 3090, the answer is 24 GB.</p><p>This determines whether model weights, KV caches, and runtime allocations can fit on the device.</p><h3>Memory Bandwidth</h3><p>How quickly can data be transferred through the GPU’s memory system?</p><p>For the RTX 3090, the published theoretical peak is approximately 936 GB/s.</p><p>A useful analogy is a warehouse.</p><p>The warehouse’s size represents memory capacity.</p><p>Its conveyor system represents bandwidth.</p><p>A warehouse can store enormous quantities of goods, but the rate at which those goods reach workers can still limit production.</p><p>Similarly, a GPU can hold an entire model in VRAM while being limited by how quickly its compute units receive the necessary weight data.</p><h3>What About Memory Latency?</h3><p>Memory latency and bandwidth are related but different concepts.</p><p>Memory latency describes how long an access takes.</p><p>Memory bandwidth describes how much data can be transferred over time.</p><p>A memory system can support high aggregate bandwidth while individual memory accesses still have significant latency.</p><p>GPU scheduling and caching help manage these limitations.</p><p>For LLM inference, both can matter, but bandwidth is particularly important when substantial weight data must be accessed for relatively little new computation.</p><h3>8. Prefill vs Decode: Why Do They Behave Differently?</h3><p>Recall that autoregressive inference has two major phases.</p><p><strong>Prefill:</strong> Processing the input prompt.</p><p><strong>Decode:</strong> Generating subsequent tokens one at a time.</p><p>These phases often stress different hardware resources.</p><h3>Prefill: Processing Many Token Positions</h3><p>Suppose an input prompt contains 128 token positions.</p><p>Each token has a hidden representation containing 896 values.</p><p>We can arrange those representations into a matrix.</p><p>Input shape: 128 × 896</p><p>Our Query projection weight matrix has the dimensions:</p><p>Weight shape: 896 × 896</p><p>The GPU can multiply the input matrix by the transposed weight matrix.</p><p>This is a matrix-matrix multiplication.</p><p>The same weights participate in computations for 128 token positions.</p><p>That creates opportunities for data reuse and efficient parallel execution.</p><h3>Decode: Processing One New Position</h3><p>During single-request autoregressive decoding, the model generally processes one new token position at each step.</p><p>The corresponding projection resembles a matrix-vector multiplication.</p><p>There is much less work available to reuse weight data across token positions.</p><p>The model still needs to access large weight matrices.</p><p>But it performs comparatively little arithmetic per weight value loaded.</p><p>This is one reason low-batch decode is often limited by memory bandwidth.</p><h3>A Simple Comparison</h3><p><strong>Prefill commonly involves:</strong></p><ul><li>Multiple prompt positions processed together.</li><li>Large matrix-matrix operations.</li><li>Greater opportunities for parallel execution and weight reuse.</li><li>Higher arithmetic intensity for many projection operations.</li></ul><p><strong>Single-request decode commonly involves:</strong></p><ul><li>One new position per iteration.</li><li>Matrix-vector or small matrix-matrix operations.</li><li>Lower opportunities to amortize weight reads.</li><li>Greater sensitivity to memory bandwidth.</li></ul><p>These are tendencies, not universal rules.</p><p>The actual bottleneck depends on prompt length, context length, batch size, hardware, model architecture, and kernel implementation.</p><h3>9. Why Doesn’t Processing 128 Tokens Require 128 Copies of the Model?</h3><p>This is another useful concept to understand before studying batching.</p><p>Imagine that we have one weight matrix containing 802,816 BF16 parameters.</p><p>Its raw storage size is:</p><p>802,816 × 2 bytes = 1,605,632 bytes</p><p>That is approximately 1.53 MiB.</p><p>Now compare two workloads.</p><p><strong>Workload A:</strong> Process one token position.</p><p><strong>Workload B:</strong> Process 128 token positions together.</p><p>Do we need to duplicate the model weights 128 times for Workload B?</p><p>No.</p><p>Both workloads use the same weight matrix.</p><p>The input and output activation tensors become larger when more positions are processed, but the learned weight matrix remains unchanged.</p><p>For one token, the input tensor contains 896 BF16 values.</p><p>Its raw storage is:</p><p>896 × 2 = 1,792 bytes, or 1.75 KiB.</p><p>For 128 token positions:</p><p>128 × 896 × 2 = 229,376 bytes, or 224 KiB.</p><p>So in this simplified projection example:</p><ul><li>Weight storage stays at approximately 1.53 MiB.</li><li>Input activation storage increases from 1.75 KiB to 224 KiB.</li><li>Output activation storage grows similarly.</li></ul><p>Real transformer execution also requires attention data and temporary workspaces.</p><p>But the fundamental point remains:</p><p><strong>Increasing the number of token positions does not inherently require duplicating the model’s learned weights.</strong></p><p>Instead, the existing weights are reused for more calculations.</p><p>This is one of the foundations of efficient batched inference.</p><h3>10. Understanding Arithmetic Intensity</h3><p>Now we can explain why weight reuse matters mathematically.</p><p>Arithmetic intensity measures how much computation is performed for each byte transferred.</p><p>The formula is:</p><p><strong>Arithmetic intensity = Floating-point operations ÷ Bytes transferred</strong></p><p>A workload with low arithmetic intensity performs relatively little computation for each byte of data moved.</p><p>A workload with high arithmetic intensity performs more computation relative to the data movement.</p><p>Let’s use our Query projection again.</p><p>The weight matrix contains:</p><p>896 × 896 = 802,816 elements.</p><p>At BF16, it occupies approximately 1.61 million bytes.</p><h3>Case A: One Token</h3><p>The approximate arithmetic work is:</p><p>2 × 896 × 896 = 1.61 million FLOPs.</p><p>If we count one read of the complete weight matrix:</p><p>1.61 million FLOPs ÷ 1.61 million weight bytes</p><p>≈ 1 FLOP per weight byte.</p><h3>Case B: 128 Tokens</h3><p>Now we perform the projection for 128 positions.</p><p>The approximate arithmetic work becomes:</p><p>2 × 128 × 896 × 896</p><p>≈ 205.52 million FLOPs.</p><p>Suppose an idealized kernel can read the weight matrix once and reuse its values across all 128 positions.</p><p>Then:</p><p>205.52 million FLOPs ÷ 1.61 million weight bytes</p><p>≈ 128 FLOPs per weight byte.</p><p>The difference is substantial.</p><p>We perform much more arithmetic for each byte of weight data.</p><h3>Is This the Actual Arithmetic Intensity?</h3><p>Not quite.</p><p>So far, we’re counting only the model-weight traffic.</p><p>A real kernel also reads input activations, writes output activations, and may generate other memory traffic.</p><p>If we additionally count one read of the input activations and one write of the output activations, the idealized arithmetic intensity for this 128-token example is approximately 99.6 FLOPs per byte.</p><p>Actual kernel behavior depends on caching, memory access patterns, tiling, and other implementation details.</p><p>But the intuition remains:</p><p><strong>Reusing data for more calculations can improve the GPU’s ability to utilize its arithmetic resources.</strong></p><p>That is one reason matrix-matrix multiplication is often much more efficient than a sequence of tiny matrix-vector operations.</p><h3>11. Compute-Bound vs Memory-Bound Workloads</h3><p>At this point, we can define two important performance bottlenecks.</p><h3>Compute-Bound</h3><p>A workload is compute-bound when the available arithmetic throughput limits performance.</p><p>The hardware can supply the required data quickly enough, but completing the calculations takes time.</p><p>Faster arithmetic units or more efficient computation may improve performance.</p><h3>Memory-Bandwidth-Bound</h3><p>A workload is memory-bandwidth-bound when moving data limits performance.</p><p>The arithmetic hardware has more capacity than the workload can effectively use because supplying the data dominates execution time.</p><p>Imagine a hypothetical operation.</p><p>Moving its data requires 15 milliseconds.</p><p>Performing its arithmetic would require only 1 millisecond.</p><p>Even if we make the arithmetic hardware twice as fast, the data movement still dominates.</p><p>Some computation and data transfers can overlap, so the actual execution time isn’t necessarily their sum.</p><p>But improving arithmetic alone may provide little benefit when bandwidth is the limiting resource.</p><p>This is why a GPU with enormous theoretical compute performance can still struggle with certain LLM decoding workloads.</p><h3>12. The Roofline Model: Understanding the Performance Ceiling</h3><p>The Roofline Model is a framework used in performance engineering to understand whether a workload is limited by computation or memory bandwidth.</p><p>It combines three quantities:</p><ul><li>Peak arithmetic throughput.</li><li>Memory bandwidth.</li><li>Arithmetic intensity.</li></ul><p>The simplified formula is:</p><p><strong>Performance ≤ Minimum(Peak Compute, Memory Bandwidth × Arithmetic Intensity)</strong></p><p>Let’s work through an example.</p><h3>Example A: Low Arithmetic Intensity</h3><p>Suppose a hypothetical GPU has:</p><ul><li>Peak compute: 100 TFLOPs.</li><li>Memory bandwidth: 1 TB/s.</li><li>Workload arithmetic intensity: 10 FLOPs/byte.</li></ul><p>The memory-bandwidth limit is:</p><p>1 TB/s × 10 FLOPs/byte = 10 TFLOPs.</p><p>Even though the GPU could theoretically perform 100 TFLOPs, the memory system can support only 10 TFLOPs for this workload.</p><p>The workload is bandwidth-bound under these assumptions.</p><h3>Example B: High Arithmetic Intensity</h3><p>Keep the same GPU.</p><p>Now increase arithmetic intensity to 200 FLOPs/byte.</p><p>The bandwidth ceiling becomes:</p><p>1 TB/s × 200 FLOPs/byte = 200 TFLOPs.</p><p>But the GPU’s maximum compute throughput is only 100 TFLOPs.</p><p>Therefore, the compute hardware becomes the limiting factor.</p><h3>The Engineering Insight</h3><p>Increasing arithmetic intensity can move a workload from being bandwidth-limited toward being compute-limited.</p><p>This is why optimized GPU kernels focus on data reuse, efficient memory access, and tiling.</p><p>It also helps explain why comparing GPU TFLOPs alone is insufficient for predicting LLM inference speed.</p><h3>13. How Memory Bandwidth Limits Token Generation</h3><p>Let’s apply everything we’ve learned to a hypothetical 7B language model.</p><p>Suppose:</p><ul><li>The model has 7 billion parameters.</li><li>Weights use FP16.</li><li>The raw weight storage is approximately 14 GB.</li><li>The GPU has a theoretical peak bandwidth of 936 GB/s.</li></ul><p>Assume that during single-request decode, each token requires approximately 14 GB of weight data to be read from VRAM.</p><p>What is the minimum transfer time?</p><p><strong>Transfer time = Data transferred ÷ Bandwidth</strong></p><p>Therefore:</p><p>14 GB ÷ 936 GB/s ≈ 0.015 seconds.</p><p>That’s approximately 15 milliseconds.</p><p>Now calculate the corresponding token rate:</p><p>936 GB/s ÷ 14 GB/token ≈ 66.9 tokens/second.</p><p>So our simplified calculation suggests approximately <strong>67 tokens per second</strong> as the weight-bandwidth ceiling under these particular assumptions.</p><h3>Does This Mean an RTX 3090 Will Generate Exactly 67 Tokens per Second?</h3><p>No.</p><p>This is not a measured benchmark.</p><p>It is a theoretical estimate that makes several simplifying assumptions.</p><p>For example, we have assumed:</p><ul><li>Approximately 14 GB of weight traffic per generated token.</li><li>Perfectly achieved peak memory bandwidth.</li><li>One active request.</li><li>No additional attention or KV-cache overhead.</li><li>No extra latency from kernel launches or scheduling.</li><li>No limiting arithmetic bottleneck.</li></ul><p>Actual implementations may read different amounts of data from VRAM because of cache behavior and other optimizations.</p><p>Real performance can be higher or lower than this simplified estimate under different conditions.</p><p>Nevertheless, the calculation teaches something useful:</p><p><strong>The amount of weight data that must be accessed during each decode step can impose a substantial performance limit, even on a GPU with enormous arithmetic capability.</strong></p><h3>14. Why Batching Improves LLM Inference Throughput</h3><p>Now imagine an inference server handling 16 users.</p><p>Each user is generating a response from the same model.</p><p>Without batching, we might process their decode steps separately.</p><p>That would create many small operations, each needing to access model weights.</p><p>With batching, the server can collect the current token representations from multiple active sequences and process them together.</p><p>The important detail is that all these requests use the same model weights.</p><p>This creates opportunities to reuse loaded weight data across multiple token positions.</p><p>Instead of doing a small amount of work per weight read, the GPU can do more work using those weights.</p><p>The result can be significantly higher aggregate throughput.</p><h3>Why Not Use the Largest Batch Possible?</h3><p>Because batching creates trade-offs.</p><p>A larger batch means:</p><ul><li>More arithmetic work.</li><li>More activation data.</li><li>More KV-cache requirements.</li><li>Additional scheduling demands.</li><li>Potential changes in per-request latency.</li></ul><p>Eventually, increasing batch size may provide diminishing throughput gains.</p><p>The workload may become compute-bound or encounter another resource limit.</p><p>This is why inference engines must balance throughput, latency, and memory consumption.</p><p>vLLM uses scheduling and batching techniques to manage this trade-off across multiple active requests.</p><p>We’ll examine its continuous batching and memory management in detail later in the series.</p><h3>15. Hands-On Experiment: Understanding GPU Resources and Weight Reuse</h3><p>Let’s conduct a lightweight experiment.</p><p>Our goal is to verify GPU hardware capabilities and analyze how the amount of arithmetic changes when we process more token positions.</p><p>We’ll use an RTX 3090 as the reference GPU, but the arithmetic experiment works on any machine with Python 3.</p><h3>Experiment A: Inspect the GPU</h3><p>For an NVIDIA GPU, run:</p><pre>nvidia-smi --query-gpu=name,compute_cap,memory.total --format=csv</pre><p>On our reference workstation, the observed results were:</p><ul><li>GPU: NVIDIA GeForce RTX 3090.</li><li>Compute capability: 8.6.</li><li>Total reported memory: 24,576 MiB.</li></ul><p>This confirms the hardware architecture and device memory capacity.</p><p>Next, inspect the GPU’s current activity:</p><pre>nvidia-smi --query-gpu=utilization.gpu,memory.used,clocks.mem,power.draw --format=csv</pre><p>At idle, the reference GPU reported:</p><ul><li>GPU utilization: 0%.</li><li>Used GPU memory: 27 MiB.</li><li>Memory clock: 405 MHz.</li><li>Power draw: 14.46 W.</li></ul><p>These are observations from a single idle sample.</p><p>They are not model-inference benchmarks.</p><p>The GPU’s clocks and power consumption can change substantially under load.</p><h3>Experiment B: Calculate Weight Reuse</h3><p>We’ll use the same Query projection matrix we discussed earlier.</p><p>Save the following Python script as projection_analysis.py:</p><pre>input_dim = 896<br>output_dim = 896<br>bytes_per_weight = 2  # BF16<br>weight_elements = input_dim * output_dim<br>weight_bytes = weight_elements * bytes_per_weight<br>print(<br>    &quot;Raw weight storage:&quot;,<br>    round(weight_bytes / 1024**2, 2),<br>    &quot;MiB&quot;<br>)<br>for tokens in [1, 8, 32, 128]:<br>    flops = 2 * input_dim * output_dim * tokens<br>    # Idealized weight reuse:<br>    # each weight read once for the operation.<br>    work_per_weight_byte = flops / weight_bytes<br>    print(<br>        f&quot;Tokens: {tokens}, &quot;<br>        f&quot;FLOPs: {flops / 1e6:.2f} million, &quot;<br>        f&quot;FLOPs per weight byte: &quot;<br>        f&quot;{work_per_weight_byte:.1f}&quot;<br>    )</pre><p>Run:</p><pre>python3 projection_analysis.py</pre><h3>Calculated Results</h3><p><strong>For 1 token:</strong></p><ul><li>Approximate computation: 1.61 million FLOPs.</li><li>FLOPs per weight byte: 1.</li></ul><p><strong>For 8 tokens:</strong></p><ul><li>Approximate computation: 12.85 million FLOPs.</li><li>FLOPs per weight byte: 8.</li></ul><p><strong>For 32 tokens:</strong></p><ul><li>Approximate computation: 51.38 million FLOPs.</li><li>FLOPs per weight byte: 32.</li></ul><p><strong>For 128 tokens:</strong></p><ul><li>Approximate computation: 205.52 million FLOPs.</li><li>FLOPs per weight byte: 128.</li></ul><h3>Prediction</h3><p>We expected that processing more token positions using the same weight matrix would increase arithmetic work without requiring additional copies of the learned weights.</p><h3>Observation</h3><p>The model’s weight matrix remains approximately 1.53 MiB for every case.</p><p>The amount of computation increases as we process more token positions.</p><p>The idealized arithmetic work per weight byte also increases.</p><h3>Conclusion</h3><p>Processing multiple token positions together creates greater opportunities for data reuse and GPU utilization.</p><p>This helps explain why large matrix operations and batching can be efficient.</p><p>However, this experiment used arithmetic calculations rather than executing a GPU kernel.</p><p>Therefore, <strong>we have not measured actual CUDA kernel performance, GPU utilization during computation, or tokens per second</strong>.</p><p>Those measurements will be the subject of later experiments.</p><p>This distinction between prediction, calculation, and actual measurement is important in performance engineering.</p><h3>16. Common Misconceptions</h3><h3>More CUDA Cores Always Mean Faster LLM Inference</h3><p>Not necessarily.</p><p>If a workload is constrained by memory bandwidth, additional arithmetic units may not improve speed significantly.</p><h3>Model Weights Are Already in VRAM, So Memory Bandwidth Shouldn’t Matter</h3><p>Incorrect.</p><p>The compute units must still access the resident weight data through the GPU memory hierarchy.</p><h3>Processing 128 Tokens Requires 128 Copies of the Model</h3><p>Incorrect.</p><p>The same learned weights can be reused across many token positions.</p><h3>Tensor Cores Accelerate Every Operation</h3><p>No.</p><p>They accelerate supported matrix operations when compatible software kernels and data layouts are used.</p><h3>Prefill Is Always Compute-Bound</h3><p>Not always.</p><p>The bottleneck depends on the workload and implementation.</p><p>Prefill commonly offers greater opportunities for parallel computation, but that does not guarantee compute saturation.</p><h3>Decode Is Always Memory-Bandwidth-Bound</h3><p>Not always.</p><p>Low-batch decode often encounters memory-bandwidth limitations, but large batches, long contexts, and other factors can shift the bottleneck.</p><h3>Published Memory Bandwidth Is the Bandwidth Every Program Achieves</h3><p>No.</p><p>Peak bandwidth is a theoretical hardware rating.</p><p>Actual bandwidth depends on memory access efficiency, caches, kernel implementation, and other factors.</p><h3>17. Quick Revision Notes</h3><p>These notes summarize the important concepts for future revision.</p><h3>GPU Architecture</h3><p><strong>CPU:</strong> General-purpose processor optimized for versatile, latency-sensitive execution.</p><p><strong>GPU:</strong> Parallel processor optimized for high-throughput numerical workloads.</p><p><strong>Streaming Multiprocessor:</strong> Hardware responsible for scheduling and executing groups of GPU threads.</p><p><strong>CUDA core:</strong> Arithmetic execution resource within an SM.</p><p><strong>Tensor Core:</strong> Specialized hardware that accelerates supported matrix operations.</p><h3>CUDA Programming</h3><p><strong>Kernel:</strong> Function executed on the GPU.</p><p><strong>Thread:</strong> Logical execution instance of the kernel.</p><p><strong>Block:</strong> Group of threads that can cooperate.</p><p><strong>Grid:</strong> Collection of thread blocks launched for a kernel.</p><p><strong>Warp:</strong> Group of 32 NVIDIA GPU threads scheduled for execution.</p><h3>Memory Concepts</h3><p><strong>VRAM capacity:</strong> Determines how much model and runtime data can fit on the GPU.</p><p><strong>Memory bandwidth:</strong> Determines the theoretical rate of data transfer.</p><p><strong>Memory latency:</strong> Describes how long memory access takes.</p><p><strong>Registers and caches:</strong> Provide smaller, faster storage close to execution resources.</p><p><strong>Global memory:</strong> Large GPU memory used to hold model weights and other tensors.</p><h3>Important Formulas</h3><p><strong>Linear projection computation</strong></p><p>For T token positions and a weight matrix with M rows and N columns:</p><p>FLOPs ≈ 2 × T × M × N</p><p><strong>Raw model-weight storage</strong></p><p>Weight bytes = Parameter count × Bytes per parameter</p><p><strong>Arithmetic intensity</strong></p><p>Arithmetic intensity = FLOPs ÷ Bytes transferred</p><p><strong>Idealized memory-transfer time</strong></p><p>Transfer time = Bytes transferred ÷ Memory bandwidth</p><p><strong>Roofline performance limit</strong></p><p>Achievable performance ≤ Minimum(Peak compute, Bandwidth × Arithmetic intensity)</p><h3>Five Key Takeaways</h3><p><strong>1. GPUs need enough parallel work to use their computational resources efficiently.</strong></p><p><strong>2. Model weights fitting in VRAM does not eliminate memory-transfer costs during computation.</strong></p><p><strong>3. Prefill often provides better opportunities for weight reuse than low-batch decode.</strong></p><p><strong>4. Batching allows multiple requests to share model weights during combined execution.</strong></p><p><strong>5. The Roofline Model helps identify whether computation or data movement is the more important bottleneck.</strong></p><h3>18. What’s Next?</h3><p>We now understand why GPUs are well suited to transformer computation, how CUDA organizes execution, and why memory bandwidth can become a major bottleneck during LLM inference.</p><p>But theoretical calculations are only the beginning.</p><p>There are more questions we need to answer experimentally.</p><p>For example:</p><ul><li>What happens to execution speed when we change numerical precision?</li><li>How do FP32, FP16, and BF16 differ on GPU hardware?</li><li>How do we measure actual CUDA kernel execution time?</li><li>How does GPU utilization change with batch size?</li><li>When do Tensor Cores provide their largest benefits?</li><li>How can quantization reduce model memory and memory traffic?</li><li>How do inference engines such as vLLM manage these hardware constraints?</li></ul><p>We’ll explore these topics through increasingly practical experiments.</p><p>Because running an LLM is one thing.</p><p><strong>Understanding why it performs the way it does — and how to make it faster — is a different engineering skill.</strong></p><h3>Further Reading</h3><ul><li>NVIDIA CUDA C++ Programming Guide: <a href="https://docs.nvidia.com/cuda/cuda-c-programming-guide/">https://docs.nvidia.com/cuda/cuda-c-programming-guide/</a></li><li>NVIDIA CUDA Programming Model: <a href="https://developer.nvidia.com/blog/cuda-refresher-cuda-programming-model/">https://developer.nvidia.com/blog/cuda-refresher-cuda-programming-model/</a></li><li>NVIDIA RTX 3090 Specifications: <a href="https://www.nvidia.com/en-in/geforce/graphics-cards/30-series/rtx-3090-3090ti/">https://www.nvidia.com/en-in/geforce/graphics-cards/30-series/rtx-3090-3090ti/</a></li><li>NVIDIA LLM Inference Optimization: <a href="https://developer.nvidia.com/blog/mastering-llm-techniques-inference-optimization/">https://developer.nvidia.com/blog/mastering-llm-techniques-inference-optimization/</a></li><li>Berkeley Lab Roofline Performance Model: <a href="https://amcr.lbl.gov/departments/computer-science-department/ppan/roofline-performance-model/">https://amcr.lbl.gov/departments/computer-science-department/ppan/roofline-performance-model/</a></li></ul><p><em>Part 3 of LLM Inference Engineering: From GPU Fundamentals to Production Serving.</em></p><p><strong>The goal isn’t simply to run a language model on a GPU. It’s to understand where the time goes — and how to improve it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50bb093c3137" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside an LLM Model: What Are We Actually Downloading?]]></title>
            <link>https://medium.com/@ankushwork21/inside-an-llm-model-what-are-we-actually-downloading-488fb1d22aea?source=rss-6027130df4cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/488fb1d22aea</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <dc:creator><![CDATA[Ankush Dhanda]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 19:02:21 GMT</pubDate>
            <atom:updated>2026-10-24T19:02:21.012Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2 of LLM Inference Engineering — Understanding model files, transformer weights, attention heads, tokenizers, and GPU memory from first principles.</em></p><h3>Introduction</h3><p>When someone says, “I downloaded a 7-billion-parameter LLM,” what exactly did they download?</p><p>Is it a program? A neural network? A collection of mathematical equations? Or a file containing billions of numbers?</p><p>And if the model requires 14 GB of memory, why might it consume significantly more memory when we actually run it?</p><p>These are some of the questions I wanted to understand before hosting my first LLM.</p><p>In the previous articles, we explored the hardware and software stack required for LLM inference and how an autoregressive model generates tokens.</p><p>Now, let’s look inside the model itself.</p><p>We’ll explore:</p><ul><li>What files are present in a model repository</li><li>How a model’s architecture is described</li><li>What trained weights actually contain</li><li>Why attention layers have Query, Key, and Value projections</li><li>How model architecture affects memory consumption</li><li>How tokenizers and chat templates work</li><li>How model weights move from storage into GPU memory</li><li>How to inspect a real LLM without downloading its entire checkpoint</li></ul><p>We’ll also conduct three lightweight experiments using a real open-weight model.</p><p>The goal is to develop an important engineering capability:</p><p><strong>Given a model repository, we should be able to understand its architecture and estimate its memory requirements before attempting to run it.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWGHBnwFMSGRpJDpUniHfg.png" /></figure><h3>1. A Model Is More Than a Collection of Weights</h3><p>Let’s start with a thought experiment.</p><p>Suppose someone gives us a file containing seven billion floating-point numbers.</p><p>Can we use those numbers to generate text?</p><p>Not yet.</p><p>We would need to know what those numbers represent.</p><p>For example:</p><ul><li>How many transformer layers does the model contain?</li><li>How large is each layer?</li><li>Which parameters belong to attention?</li><li>Which parameters belong to the feed-forward network?</li><li>How are input tokens represented?</li><li>How are the numerical parameters arranged?</li><li>Which software implements the model’s operations?</li></ul><p>The numbers alone are not enough.</p><p>A useful way to understand an LLM is to separate four components.</p><p><strong>1. Architecture</strong></p><p>Defines the model’s computational structure: transformer layers, attention heads, hidden dimensions, feed-forward networks, and other operations.</p><p><strong>2. Model weights</strong></p><p>The numerical parameters learned during training. These determine how the model transforms its inputs.</p><p><strong>3. Tokenizer</strong></p><p>Defines how text is converted into token IDs and how token IDs are converted back into text.</p><p><strong>4. Inference runtime</strong></p><p>The software that constructs the model, loads its parameters, executes computations, and generates tokens.</p><p>Conceptually:</p><pre>Model Configuration<br>          (Architecture)<br>                 |<br>                 v<br>         Model Implementation<br>                 |<br>                 v<br>         Load Trained Weights<br>                 |<br>                 v<br>          Executable Model<br>                 ^<br>                 |<br>         Token IDs / Tensors<br>                 ^<br>                 |<br>             Tokenizer<br>                 ^<br>                 |<br>             User Text</pre><p>The configuration describes how the model should be constructed. The actual implementation of those operations comes from the model runtime or framework.</p><p><strong>Key takeaway:</strong> Downloading a model checkpoint is not the same as downloading a standalone executable application.</p><h3>2. What Files Are Inside a Model Repository?</h3><p>Many open-weight LLMs are distributed through Hugging Face repositories.</p><p>A typical Transformers-compatible repository might contain:</p><pre>example-model/<br>│<br>├── config.json<br>│<br>├── tokenizer.json<br>├── tokenizer_config.json<br>├── special_tokens_map.json<br>│<br>├── generation_config.json<br>│<br>├── model-00001-of-00003.safetensors<br>├── model-00002-of-00003.safetensors<br>├── model-00003-of-00003.safetensors<br>│<br>├── model.safetensors.index.json<br>│<br>├── README.md<br>└── LICENSE</pre><p>This is an illustrative directory. Not every model repository contains every file, and some models have a single weight file instead of multiple shards.</p><p>Let’s understand the important ones.</p><p>FilePurposeconfig.jsonDescribes model architecture and configurationtokenizer.jsonContains tokenization rules and vocabulary datatokenizer_config.jsonContains tokenizer settings and potentially a chat templatespecial_tokens_map.jsonDefines special tokens, when providedgeneration_config.jsonContains default text-generation settings.safetensorsStores learned tensor parametersmodel.safetensors.index.jsonMaps tensor names to checkpoint shardsREADME.mdModel documentation, capabilities, limitations and usageLICENSEDefines applicable usage and distribution terms</p><p>There are three files worth understanding first:</p><p><strong>config.json tells us how the model is structured.</strong></p><p><strong>.safetensors contains the model&#39;s learned numerical parameters.</strong></p><p><strong>tokenizer.json defines how text is converted into tokens.</strong></p><p>We will start with the configuration.</p><h3>3. Understanding config.json — The Model’s Blueprint</h3><p>For our experiments, we’ll use <a href="https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct">Qwen2.5–0.5B-Instruct</a>, a small open-weight instruction-tuned language model.</p><p>We deliberately chose a small model because our goal is to understand the architecture before experimenting with larger models.</p><p>Its configuration contains fields such as:</p><pre>{<br>  &quot;architectures&quot;: [&quot;Qwen2ForCausalLM&quot;],<br>  &quot;hidden_size&quot;: 896,<br>  &quot;num_hidden_layers&quot;: 24,<br>  &quot;num_attention_heads&quot;: 14,<br>  &quot;num_key_value_heads&quot;: 2,<br>  &quot;intermediate_size&quot;: 4864,<br>  &quot;vocab_size&quot;: 151936,<br>  &quot;max_position_embeddings&quot;: 32768,<br>  &quot;torch_dtype&quot;: &quot;bfloat16&quot;,<br>  &quot;tie_word_embeddings&quot;: true<br>}</pre><p>These are selected fields from the actual model configuration.</p><p>Let’s break them down.</p><h3>Hidden Size</h3><pre>hidden_size = 896</pre><p>The hidden size represents the dimension of the model’s token representations as they move through the transformer.</p><p>For example, one token’s hidden representation contains 896 numerical components.</p><h3>Number of Layers</h3><pre>num_hidden_layers = 24</pre><p>The model contains 24 transformer layers.</p><p>Each layer performs learned transformations on the token representations.</p><p>The output from one layer becomes the input to the next.</p><h3>Attention Heads</h3><pre>num_attention_heads = 14<br>num_key_value_heads = 2</pre><p>These fields describe how attention is organized.</p><p>The model has 14 Query heads but only 2 Key/Value heads.</p><p>Why the difference?</p><p>We’ll discuss that shortly.</p><h3>Intermediate Size</h3><pre>intermediate_size = 4864</pre><p>This represents the intermediate dimension used within the model’s feed-forward network.</p><p>The MLP is a major source of learned parameters, so this value has a substantial influence on model size.</p><h3>Vocabulary Size</h3><pre>vocab_size = 151936</pre><p>This describes the model’s configured vocabulary dimension.</p><p>It influences the size of the token embedding matrix and the output vocabulary projection.</p><h3>Tied Word Embeddings</h3><pre>tie_word_embeddings = true</pre><p>This means the input token embedding weights are shared with the output language-model projection.</p><p>Rather than maintaining two independent learned matrices, the model reuses the embedding parameters.</p><p>This reduces the number of unique parameters that need to be stored.</p><h3>Why Is This Configuration Useful?</h3><p>Without downloading the model weights, we already know:</p><ul><li>The number of transformer layers</li><li>The hidden representation size</li><li>The number of attention heads</li><li>The number of KV heads</li><li>The MLP intermediate size</li><li>The configured vocabulary dimension</li><li>The declared checkpoint precision</li></ul><p>From these values alone, we can begin estimating memory requirements.</p><h3>4. What Exactly Are Model Weights?</h3><p>A model weight is a numerical parameter learned during training.</p><p>Consider a simple matrix multiplication:</p><p><strong>Output = Weight Matrix × Input Vector</strong></p><p>Suppose:</p><pre>Input:<br>[2, 3]<br>Weights:<br>[0.5  0.2]<br>[0.1  0.8]</pre><p>The output is calculated by multiplying the input by the weight matrix.</p><p>The four numerical values in the matrix are parameters.</p><p>During training, an optimizer adjusts learned parameters to improve the model’s objective.</p><p>During ordinary inference, those parameters remain fixed while the model uses them to perform calculations.</p><p>A transformer contains many weight matrices.</p><p>Some represent token embeddings. Others are used in attention or feed-forward operations.</p><h3>What Is a Tensor?</h3><p>A tensor is a multidimensional array of numerical values.</p><p>For example:</p><pre>Tensor shape: [2, 3]<br>[0.1  0.2  0.3]<br>[0.4  0.5  0.6]</pre><p>This tensor contains:</p><p>2 × 3 = 6 numerical elements.</p><p>If a weight matrix has shape:</p><pre>[896, 896]</pre><p>then it contains:</p><p>896 × 896 = 802,816 parameters.</p><p>How much memory do these parameters occupy?</p><p>That depends on their numerical representation.</p><p>RepresentationBytes per parameterFP324FP162BF162INT8Approximately 1INT4Approximately 0.5</p><p>For a BF16 tensor containing 802,816 elements:</p><p>802,816 × 2 = 1,605,632 bytes.</p><p>This is approximately <strong>1.53 MiB</strong>.</p><p>Now imagine hundreds of tensors distributed across dozens of transformer layers.</p><p>That is how LLMs accumulate hundreds of millions or billions of parameters.</p><h3>5. Where Are These Weights Used Inside a Transformer?</h3><p>A simplified decoder-only transformer contains:</p><pre>Input Token IDs<br>                 |<br>                 v<br>          Token Embeddings<br>                 |<br>                 v<br>       +---------------------+<br>       | Transformer Layer 1 |<br>       |                     |<br>       | Attention           |<br>       | MLP                 |<br>       | Normalization       |<br>       +---------------------+<br>                 |<br>                 v<br>       +---------------------+<br>       | Transformer Layer 2 |<br>       +---------------------+<br>                 |<br>                ...<br>                 |<br>                 v<br>       +---------------------+<br>       | Final Transformer   |<br>       | Layer               |<br>       +---------------------+<br>                 |<br>                 v<br>          Output Projection<br>                 |<br>                 v<br>               Logits</pre><p>Each transformer layer contains multiple learned parameter tensors.</p><p>Let’s examine the main groups.</p><h3>A. Embedding Weights</h3><p>The embedding layer maps token IDs to numerical vectors.</p><p>For our example model:</p><pre>model.embed_tokens.weight<br>Shape: [151936, 896]</pre><p>Why these dimensions?</p><p>The model has a configured vocabulary dimension of 151,936, and each entry has an embedding containing 896 components.</p><p>The parameter count is:</p><p>151,936 × 896 = 136,134,656</p><p>That’s approximately <strong>136 million parameters in a single embedding matrix</strong>.</p><p>Notice that a substantial portion of this relatively small model’s parameters belongs to its token embeddings.</p><h3>B. Attention Projection Weights</h3><p>Inside attention, the transformer computes Query, Key, and Value representations.</p><p>The learned projection matrices are often named:</p><pre>q_proj.weight<br>k_proj.weight<br>v_proj.weight<br>o_proj.weight</pre><p>Their responsibilities are:</p><p>ProjectionPurposeQProduces Query representationsKProduces Key representationsVProduces Value representationsOProjects the combined attention output back into the hidden space</p><p>The Query and Key vectors are used to calculate attention scores.</p><p>The corresponding Value vectors supply the information combined using those scores.</p><p>The attention mechanism can be written as:</p><p><strong>Attention(Q, K, V) = softmax(QKᵀ / √dₖ)V</strong></p><p>This expression describes the central mathematical operation of scaled dot-product attention. In causal attention, masking also prevents token positions from attending to the future.</p><p>Let’s inspect the actual weight dimensions.</p><p>TensorShapeq_proj.weight[896, 896]k_proj.weight[128, 896]v_proj.weight[128, 896]o_proj.weight[896, 896]</p><p>Why are the Key and Value projections much smaller than the Query projection?</p><p>That brings us to Grouped-Query Attention.</p><h3>6. Query Heads, KV Heads, and Grouped-Query Attention</h3><p>This topic is important because it connects model architecture directly to GPU memory requirements.</p><p>First, attention heads have nothing to do with tokenization.</p><p>Tokenization determines the input token IDs.</p><p>Attention operates on the token representations inside the transformer.</p><h3>Understanding an Attention Head</h3><p>An attention head calculates a set of attention weights and uses them to combine information from token positions.</p><p>A useful intuition is:</p><ul><li><strong>Query:</strong> What information am I looking for?</li><li><strong>Key:</strong> What information is available to match against?</li><li><strong>Value:</strong> What information can be contributed?</li></ul><p>A model can use multiple attention heads so that different learned projections can represent different attention patterns.</p><h3>Multi-Head Attention (MHA)</h3><p>In conventional Multi-Head Attention, each Query head has its own corresponding Key and Value heads.</p><p>For example:</p><pre>14 Query Heads<br>14 Key Heads<br>14 Value Heads</pre><p>Each Query head uses its corresponding Key/Value representations.</p><h3>Grouped-Query Attention (GQA)</h3><p>Grouped-Query Attention allows multiple Query heads to share the same Key and Value heads.</p><p>Our example model uses:</p><pre>14 Query Heads<br> 2 Key Heads<br> 2 Value Heads</pre><p>Therefore:</p><p>14 / 2 = 7</p><p><strong>Each KV group serves 7 Query heads.</strong></p><p>Conceptually:</p><pre>Q1 ──┐<br>Q2 ──┤<br>Q3 ──┤<br>Q4 ──┼──&gt; Shared K1 and V1<br>Q5 ──┤<br>Q6 ──┤<br>Q7 ──┘</pre><pre>Q8  ─┐<br>Q9  ─┤<br>Q10 ─┤<br>Q11 ─┼──&gt; Shared K2 and V2<br>Q12 ─┤<br>Q13 ─┤<br>Q14 ─┘</pre><p>Each Query head still has its own Query representation, meaning its attention weights can differ even when Keys and Values are shared.</p><h3>Why Does This Reduce Model Weight Size?</h3><p>The model’s hidden dimension is 896.</p><p>Its Query head dimension is:</p><p>896 / 14 = 64</p><p>So the Query projection outputs:</p><p>14 × 64 = 896 components.</p><p>The Key projection outputs:</p><p>2 × 64 = 128 components.</p><p>That explains these shapes:</p><pre>Query: [896, 896]<br>Key:   [128, 896]<br>Value: [128, 896]</pre><p>Both projections receive 896-dimensional hidden vectors, but their output dimensions differ.</p><p>Smaller K and V projections require fewer learned parameters.</p><h3>Why Does This Reduce KV-Cache Memory?</h3><p>During autoregressive inference, the engine stores previously computed Keys and Values so they can be reused.</p><p>It does not generally need to retain previous Query vectors in the persistent attention cache.</p><p>With fewer KV heads, fewer distinct Key/Value values need to be stored for each token position.</p><p>Consider the same architecture with 4,096 cached token positions.</p><p>Attention architectureKV headsTheoretical KV cacheMulti-Head Attention14336 MiBGrouped-Query Attention248 MiBMulti-Query Attention124 MiB</p><p>These calculations assume 24 layers, 64 dimensions per KV head, and BF16 cache elements.</p><p>In this comparison, GQA requires <strong>7 times less KV-cache storage</strong> than the equivalent 14-KV-head architecture.</p><p>That doesn’t mean the entire model becomes seven times smaller or seven times faster.</p><p>The benefit specifically concerns the K/V projections and cache, while the model still performs many other computations.</p><p><strong>Key takeaway:</strong> Architecture choices affect not only model quality and parameter count, but also memory consumption and serving efficiency.</p><h3>7. The MLP: Another Major Source of Model Parameters</h3><p>Attention receives considerable attention in LLM discussions, but it isn’t the only computationally significant part of a transformer.</p><p>Each transformer layer also contains a feed-forward network, often called the MLP.</p><p>Our example model has three main MLP projection matrices:</p><pre>mlp.gate_proj.weight<br>Shape: [4864, 896]<br>mlp.up_proj.weight<br>Shape: [4864, 896]<br>mlp.down_proj.weight<br>Shape: [896, 4864]</pre><p>The model uses a gated MLP design.</p><p>The up and gate projections transform the hidden representation into a larger intermediate space.</p><p>The down projection returns the intermediate result to the hidden dimension.</p><p>Let’s calculate the parameter count.</p><p>Each matrix contains:</p><p>4,864 × 896 = 4,358,144 parameters.</p><p>Across the three matrices:</p><p>3 × 4,358,144 = 13,074,432 parameters.</p><p>That’s approximately <strong>13 million MLP parameters per transformer layer</strong>.</p><p>The model contains 24 transformer layers.</p><p>Therefore, the MLP projections alone account for approximately:</p><p>13,074,432 × 24 = 313,786,368 parameters.</p><p>Over <strong>313 million parameters</strong> are associated with the MLP projection matrices.</p><p>An important distinction emerges:</p><p><strong>Attention architecture strongly influences KV-cache requirements, while MLP matrices can account for a large proportion of the model’s learned weights.</strong></p><p>Understanding both is necessary for estimating model memory and computation.</p><h3>8. Inside a Safetensors Checkpoint</h3><p>Now that we understand the model’s architecture and weight tensors, where are these numbers physically stored?</p><p>For this model, they are stored in a file called:</p><p>model.safetensors</p><p>Safetensors is a format designed to store numerical tensors with metadata describing their contents.</p><p>Conceptually:</p><pre>model.safetensors<br>│<br>├── Header length<br>│<br>├── JSON metadata header<br>│   ├── Tensor names<br>│   ├── Tensor shapes<br>│   ├── Data types<br>│   └── Byte offsets<br>│<br>└── Binary tensor data<br>    ├── Embedding weights<br>    ├── Attention weights<br>    ├── MLP weights<br>    └── Other parameters</pre><p>The file contains an eight-byte header-length field, followed by JSON metadata and the binary tensor payload.</p><p>A header entry can look conceptually like this:</p><pre>{<br>  &quot;model.layers.0.self_attn.q_proj.weight&quot;: {<br>    &quot;dtype&quot;: &quot;BF16&quot;,<br>    &quot;shape&quot;: [896, 896],<br>    &quot;data_offsets&quot;: [0, 1605632]<br>  }<br>}</pre><p>This is an illustrative entry rather than the checkpoint’s exact byte offsets.</p><p>The useful property is that we can inspect a tensor’s name, shape, dtype, and location without loading the actual numerical values.</p><p>For example:</p><ul><li>Tensor name: q_proj.weight</li><li>Shape: [896, 896]</li><li>Precision: BF16</li><li>Parameter count: 802,816</li><li>Raw storage: approximately 1.53 MiB</li></ul><h3>Why Are Large Checkpoints Split Into Shards?</h3><p>Some models have checkpoints occupying tens or hundreds of gigabytes.</p><p>Instead of placing every tensor in one enormous file, the publisher may divide them into multiple files called shards.</p><p>For example:</p><pre>model-00001-of-00003.safetensors<br>model-00002-of-00003.safetensors<br>model-00003-of-00003.safetensors</pre><p>An index file can map tensor names to the shards containing their data.</p><p>Sharding helps distribute and load large checkpoints.</p><p>However, <strong>splitting a checkpoint into smaller files does not reduce the total amount of memory required to hold its weights</strong>.</p><p>The total stored tensor data remains the same.</p><h3>9. How Much Memory Does the Actual Model Require?</h3><p>Let’s connect theory with a real checkpoint inspection.</p><p>We examined the metadata of Qwen2.5–0.5B-Instruct without downloading its full weight data.</p><p>The checkpoint reported:</p><p>MetricObserved resultStored tensors290Parameter elements494,032,768Stored dtypeBF16Raw weight storage942.29 MiB</p><p>This matches what we would expect from a model with approximately 0.5 billion parameters.</p><p>The raw weight memory is:</p><p>494,032,768 × 2 bytes</p><p>= 988,065,536 bytes</p><p>= <strong>942.29 MiB</strong></p><p>This also explains why the model’s safetensors checkpoint is approximately 988 MB in decimal storage units.</p><h3>Why Is This Calculation Useful?</h3><p>Suppose we want to evaluate a different model.</p><p>If we know its parameter count and precision, we can begin with:</p><p><strong>Weight memory ≈ Parameters × Bytes per parameter</strong></p><p>For example:</p><p>Model parametersFP16/BF16 raw weight storage0.5B~1 GB3B~6 GB7B~14 GB14B~28 GB32B~64 GB</p><p>These are decimal GB estimates for ordinary dense parameter storage.</p><p>Real checkpoint sizes can differ due to architecture details, mixed precision, quantization metadata, and other stored tensors.</p><p>And these numbers describe <strong>weights only</strong>.</p><p>They do not tell us the total memory consumed by a running inference server.</p><h3>10. Model Weights vs KV Cache — A Critical Distinction</h3><p>At this point, it’s useful to clarify two things that are often confused.</p><p>Both model weights and KV-cache tensors occupy GPU memory.</p><p>But they are not the same kind of data.</p><p>Model weightsKV cacheLearned during trainingCalculated during inferenceStored in checkpoint filesCreated and managed by the runtimeUsually fixed during inferenceChanges as token sequences are processedShared by requests using the same model instanceAssociated with sequences, with possible prefix sharingUsed to compute Q, K, V and other representationsStores previously computed K and V representations</p><p>For example:</p><p>k_proj.weight is a learned matrix.</p><p>When the model processes a token representation, it applies that matrix to calculate a Key vector.</p><p>The resulting Key vector can then be stored in the KV cache.</p><p><strong>The model’s Key projection weights are not the same thing as the cached Key vectors.</strong></p><p>This is important when estimating GPU memory.</p><h3>Estimating KV-Cache Memory</h3><p>For a conventional full-context KV cache, a useful formula is:</p><p><strong>KV bytes = 2 × Layers × KV heads × Head dimension × Bytes per element × Cached token positions</strong></p><p>The factor of two accounts for Keys and Values.</p><p>For our example model:</p><ul><li>Layers = 24</li><li>KV heads = 2</li><li>Head dimension = 64</li><li>BF16 = 2 bytes</li></ul><p>The cache required per token position is:</p><p>2 × 24 × 2 × 64 × 2</p><p>= 12,288 bytes</p><p>= <strong>12 KiB per cached token position</strong></p><p>For 4,096 tokens:</p><p>4,096 × 12 KiB = <strong>48 MiB</strong></p><p>For 16 independent requests, each having 4,096 cached tokens:</p><p>16 × 48 MiB = <strong>768 MiB</strong></p><p>These are theoretical KV tensor storage calculations, not actual GPU allocation measurements.</p><h3>Why Context Length and Concurrency Matter</h3><p>The KV-cache requirement increases as more token positions are cached.</p><p>It also grows when we serve more independent requests simultaneously.</p><p>Therefore, we must consider both:</p><ul><li>Whether the model’s weights fit in VRAM</li><li>Whether enough memory remains for the intended context length and concurrency</li></ul><p>This explains why a model may run successfully for one short prompt but struggle with many long requests.</p><h3>11. Understanding Tokenizer Files and Chat Templates</h3><p>We’ve spent considerable time on weight tensors.</p><p>Now let’s look at the files that connect human language to those tensors.</p><h3>tokenizer.json</h3><p>The tokenizer defines how text is converted into token IDs.</p><p>Our example model uses a BPE tokenizer, short for Byte Pair Encoding.</p><p>BPE-based tokenizers represent text through a learned vocabulary and tokenization rules.</p><p>A token may represent a complete word, a subword, or another text fragment.</p><h3>tokenizer_config.json</h3><p>This file contains tokenizer settings and may include a chat template.</p><p>Why do we need a chat template?</p><p>Because instruction-tuned language models are often trained using structured conversations.</p><p>The model needs to distinguish between roles such as:</p><ul><li>System</li><li>User</li><li>Assistant</li></ul><p>For example, a Qwen-style conversation can be formatted as:</p><pre>&lt;|im_start|&gt;user<br>What is a GPU?<br>&lt;|im_end|&gt;<br>&lt;|im_start|&gt;assistant</pre><p>These markers are part of the structured input expected by the model.</p><p>A chat template transforms a list of conversation messages into the correct serialized text/token structure.</p><p>The tokenizer then maps that representation into token IDs.</p><p><strong>Using the wrong chat template can cause incorrect or unexpected model behavior, even if the weights are loaded properly.</strong></p><h3>Special Tokens</h3><p>Our tokenizer inspection found these Qwen special tokens:</p><p>Special tokenToken ID`&lt;endoftext&gt;`151643`&lt;im_start&gt;`151644`&lt;im_end&gt;`151645</p><p>These tokens help represent message boundaries and stopping behavior.</p><h3>Vocabulary Size vs Tokenizer Vocabulary Entries</h3><p>One interesting observation from our experiment was:</p><pre>Model vocabulary dimension: 151936<br>Tokenizer BPE vocabulary entries: 151643</pre><p>Why don’t these numbers match?</p><p>Because the model’s configured vocabulary capacity and the serialized tokenizer’s base vocabulary entry count are not necessarily identical.</p><p>There may be additional special tokens, reserved token IDs, or padding in the model’s embedding dimension.</p><p>The difference should not automatically be interpreted as an exact count of special tokens.</p><h3>generation_config.json</h3><p>This file contains default generation settings.</p><p>Examples include:</p><ul><li>Temperature</li><li>Top-k</li><li>Top-p</li><li>Repetition penalty</li><li>End-of-sequence token IDs</li><li>Whether to use sampling</li></ul><p>Our inspected model’s generation configuration includes:</p><pre>{<br>  &quot;eos_token_id&quot;: [151645, 151643],<br>  &quot;temperature&quot;: 0.7,<br>  &quot;top_k&quot;: 20,<br>  &quot;top_p&quot;: 0.8<br>}</pre><p>These are selected fields.</p><p>An important observation is that the configuration lists two possible end-of-sequence token IDs.</p><p>When honored by the generation runtime, either can signal a stopping condition.</p><p>Generation defaults are not the same as architecture parameters. A runtime or API request may override them.</p><h3>12. What Happens When a Model Is Loaded Into Memory?</h3><p>Now we can connect everything.</p><p>We have:</p><ul><li>Model configuration</li><li>Tokenizer files</li><li>Trained weight tensors</li><li>An inference runtime</li><li>A CPU and GPU</li></ul><p>How do these components come together?</p><p>A simplified loading sequence is:</p><pre>SSD / Storage<br>                   |<br>                   v<br>        Read model configuration<br>                   |<br>                   v<br>        Construct model structure<br>                   |<br>                   v<br>         Load checkpoint tensors<br>                   |<br>                   v<br>          CPU / Host Memory<br>          (implementation-dependent)<br>                   |<br>                   | PCIe / Device transfer<br>                   v<br>              GPU / VRAM<br>                   |<br>          +--------+---------+<br>          |                  |<br>          v                  v<br>      Model Weights      Runtime Buffers<br>                             |<br>                             v<br>                        KV Cache Pool<br>                             |<br>                             v<br>                    Model Ready to Serve</pre><p>Actual implementations can differ.</p><p>For example, some loaders use memory mapping, streaming, or direct placement strategies rather than holding an entire additional checkpoint copy in ordinary CPU memory.</p><p>The key point is that the runtime must make the model’s parameters available to the device executing the mathematical operations.</p><h3>Why GPU Memory Usage Is Larger Than Model Weight Size</h3><p>A simplified GPU memory budget is:</p><p><strong>GPU memory ≈ Model weights + KV-cache allocation + Runtime overhead + Execution buffers</strong></p><p>The inference engine may also allocate resources for optimized execution, such as CUDA Graphs.</p><p>For example, suppose a model’s weights occupy approximately 1 GiB.</p><p>After starting an inference server, we might observe considerably more than 1 GiB of GPU memory allocated.</p><p>That does not necessarily indicate a problem.</p><p>The engine may have already allocated a KV-cache pool and other resources in preparation for handling requests.</p><h3>Allocated KV Cache vs Active KV Data</h3><p>This distinction is particularly important.</p><p>An inference engine may allocate several gigabytes for KV caching before receiving any user requests.</p><p>At that moment:</p><ul><li>The memory is allocated.</li><li>The engine can reuse it for future requests.</li><li>It does not necessarily contain Keys and Values belonging to active user requests.</li></ul><p>Therefore:</p><p><strong>Allocated GPU memory is not the same as actively utilized KV-cache memory.</strong></p><p>This is why nvidia-smi alone cannot explain how many tokens are currently cached.</p><p>For that, we need metrics from the inference engine itself.</p><p>When we later investigate vLLM, we’ll examine GPU memory allocation, cache capacity, request scheduling, and concurrency together.</p><h3>13. Safetensors vs GGUF vs GPTQ vs AWQ</h3><p>Before choosing a model for deployment, we will often encounter terms such as:</p><ul><li>Safetensors</li><li>GGUF</li><li>GPTQ</li><li>AWQ</li><li>bitsandbytes</li></ul><p>These are related to model storage and execution, but they do not all describe the same thing.</p><p>TermWhat it representsSafetensorsTensor serialization formatGGUFModel file/container format commonly associated with llama.cppFP16 / BF16Floating-point numerical representationsINT8 / INT4Reduced-width integer representationsGPTQPost-training weight quantization methodAWQActivation-aware weight quantization methodbitsandbytesLibrary providing quantized model loading and operations</p><p>For example, a safetensors file can store BF16 weights or data associated with a quantization scheme.</p><p>Likewise, GGUF supports multiple tensor representation types.</p><h3>Why Do We Quantize Models?</h3><p>Suppose a dense model contains 14 billion parameters.</p><p>At FP16:</p><p>14B × 2 bytes = 28 GB.</p><p>At an idealized 4-bit representation:</p><p>14B × 0.5 bytes = 7 GB.</p><p>Quantization can significantly reduce the amount of memory needed to store weights.</p><p>However, actual quantized models may require additional metadata, scaling factors, and higher-precision tensors.</p><p>Also, smaller weights do not automatically guarantee faster inference.</p><p>Performance depends on hardware support, available kernels, quantization implementation, and the workload.</p><p>We’ll study these trade-offs through actual experiments in a later article.</p><p>For now, remember:</p><p><strong>The checkpoint format, numerical precision, and quantization method are separate concepts.</strong></p><h3>14. Hands-On Experiment: Inspect a Model Without Downloading Its Weights</h3><p>Let’s turn the theory into a reproducible experiment.</p><p>Our objective is to answer three questions:</p><ol><li>Can we understand a model’s architecture using only its configuration?</li><li>Can we inspect the checkpoint’s tensor metadata without downloading the entire model?</li><li>Can we identify its tokenizer and generation settings separately?</li></ol><p>For this experiment, we’ll use:</p><p><a href="https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct">Qwen2.5–0.5B-Instruct on Hugging Face</a></p><p>We only need Python 3 and standard-library modules.</p><p>No PyTorch, CUDA installation, or GPU is required for this metadata analysis.</p><h3>Experiment A — Read the Architecture</h3><pre>import json<br>import urllib.request<br>MODEL = (<br>    &quot;https://huggingface.co/Qwen/&quot;<br>    &quot;Qwen2.5-0.5B-Instruct/resolve/main/&quot;<br>)<br>with urllib.request.urlopen(<br>    MODEL + &quot;config.json&quot;, timeout=30<br>) as response:<br>    config = json.load(response)<br>for field in [<br>    &quot;architectures&quot;,<br>    &quot;hidden_size&quot;,<br>    &quot;num_hidden_layers&quot;,<br>    &quot;num_attention_heads&quot;,<br>    &quot;num_key_value_heads&quot;,<br>    &quot;intermediate_size&quot;,<br>    &quot;vocab_size&quot;<br>]:<br>    print(field, &quot;:&quot;, config.get(field))</pre><p>This allows us to inspect the model’s dimensions without downloading any trained weights.</p><p>From these values, we can calculate its attention-head dimension and estimate KV-cache requirements.</p><h3>Experiment B — Inspect Safetensors Metadata</h3><p>A safetensors file begins with an eight-byte header-length field followed by metadata describing the stored tensors.</p><p>If the server supports HTTP byte-range requests, we can retrieve only the header rather than the checkpoint payload.</p><pre>import json<br>import math<br>import struct<br>import urllib.request<br>URL = (<br>    &quot;https://huggingface.co/Qwen/&quot;<br>    &quot;Qwen2.5-0.5B-Instruct/resolve/main/&quot;<br>    &quot;model.safetensors&quot;<br>)<br>def read_range(start, end):<br>    req = urllib.request.Request(<br>        URL,<br>        headers={<br>            &quot;Range&quot;: f&quot;bytes={start}-{end}&quot;,<br>            &quot;Accept-Encoding&quot;: &quot;identity&quot;<br>        }<br>    )<br>    with urllib.request.urlopen(<br>        req, timeout=30<br>    ) as response:<br>        if response.status != 206:<br>            raise RuntimeError(<br>                &quot;Byte ranges not supported&quot;<br>            )<br>        data = response.read(end - start + 1)<br>    if len(data) != end - start + 1:<br>        raise ValueError(&quot;Incomplete response&quot;)<br>    return data<br># First eight bytes contain header length.<br>header_size = struct.unpack(<br>    &quot;&lt;Q&quot;, read_range(0, 7)<br>)[0]<br>if not 0 &lt; header_size &lt;= 1_000_000:<br>    raise ValueError(&quot;Unexpected header size&quot;)<br># Read only the JSON metadata.<br>header = json.loads(<br>    read_range(8, 7 + header_size)<br>)<br>tensors = {<br>    name: info<br>    for name, info in header.items()<br>    if name != &quot;__metadata__&quot;<br>}<br>parameters = sum(<br>    math.prod(info[&quot;shape&quot;])<br>    for info in tensors.values()<br>)<br>print(&quot;Tensor count:&quot;, len(tensors))<br>print(&quot;Parameters:&quot;, parameters)<br>print(&quot;BF16 size (MiB):&quot;,<br>      parameters * 2 / (1024 ** 2))</pre><p>This script checks for a partial-content response instead of blindly downloading the complete checkpoint if the server ignores the range request.</p><h3>Results</h3><p>The inspected checkpoint metadata contained:</p><pre>Tensor count: 290<br>Parameters: 494032768<br>BF16 size (MiB): 942.29</pre><p>The checkpoint’s stored tensors were BF16.</p><p>This confirms that we can calculate parameter storage directly from the actual checkpoint metadata.</p><p>The experiment does <strong>not</strong> measure GPU memory usage, because the model has not been loaded for inference.</p><h3>Experiment C — Inspect Tokenizer Metadata</h3><p>We can separately inspect the tokenizer configuration:</p><pre>import json<br>import urllib.request<br>URL = (<br>    &quot;https://huggingface.co/Qwen/&quot;<br>    &quot;Qwen2.5-0.5B-Instruct/resolve/main/&quot;<br>    &quot;tokenizer_config.json&quot;<br>)<br>with urllib.request.urlopen(<br>    URL, timeout=30<br>) as response:<br>    tokenizer_config = json.load(response)<br>print(<br>    &quot;Tokenizer class:&quot;,<br>    tokenizer_config.get(&quot;tokenizer_class&quot;)<br>)<br>print(<br>    &quot;Chat template available:&quot;,<br>    bool(tokenizer_config.get(&quot;chat_template&quot;))<br>)<br>tokens = tokenizer_config.get(<br>    &quot;added_tokens_decoder&quot;, {}<br>)<br>for token_id in [<br>    &quot;151643&quot;, &quot;151644&quot;, &quot;151645&quot;<br>]:<br>    print(token_id, tokens[token_id][&quot;content&quot;])</pre><p>This confirms that tokenizer metadata can be inspected independently of the model weights.</p><p>Our inspection also identified a BPE tokenizer model and the presence of a chat template.</p><p>The exercise demonstrates an important point:</p><p><strong>We can learn a great deal about a model’s architecture, weights, and expected inputs before allocating a single byte of GPU memory to it.</strong></p><p>For repeatable research, pin the repository revision so that future changes to the files don’t silently alter the experiment.</p><h3>15. Common Misconceptions</h3><h3>Misconception 1: The config.json File Contains the Model’s Knowledge</h3><p>It doesn’t.</p><p>The configuration describes the architecture. The trained weights contain the learned numerical parameters.</p><h3>Misconception 2: A 7B Model Always Requires Exactly 14 GB</h3><p>That’s only an approximate raw-weight calculation for 7 billion parameters stored at 2 bytes each.</p><p>Actual inference requirements include caches, buffers, runtime overhead, and sometimes mixed-precision data.</p><h3>Misconception 3: Query Heads and KV Heads Are Related to Tokenization</h3><p>They are not.</p><p>Tokenization converts text to token IDs.</p><p>Attention heads operate on the representations of those tokens inside the transformer.</p><h3>Misconception 4: Model Weight Tensors and KV-Cache Tensors Are the Same</h3><p>They are different.</p><p>Weights are trained parameters used to compute Key and Value representations. The KV cache stores computed attention states for specific token sequences.</p><h3>Misconception 5: Sharding a Model Reduces Its Total Weight Memory</h3><p>Sharding changes how weights are distributed across files.</p><p>It does not reduce the total amount of parameter data.</p><h3>Misconception 6: If nvidia-smi Shows High Memory Usage, the KV Cache Must Be Full</h3><p>Not necessarily.</p><p>Some inference engines preallocate cache storage and other execution resources.</p><p>Allocated memory may be reserved for future work rather than currently holding active token data.</p><h3>16. Quick Revision Notes</h3><p>This section is designed for revisiting the concepts later without reading the entire article.</p><h3>Important Files</h3><p>FileRememberconfig.jsonModel architecturemodel.safetensorsLearned weight tensorsmodel.safetensors.index.jsonTensor-to-shard mappingtokenizer.jsonTokenization vocabulary and rulestokenizer_config.jsonTokenizer settings and potentially chat templategeneration_config.jsonGeneration defaults</p><h3>Important Architecture Parameters</h3><p>ParameterMeaningHidden sizeDimension of token representationsNumber of layersTransformer depthQuery headsAttention Query projectionsKV headsKey/Value projections used by attentionHead dimensionComponents per attention headIntermediate sizeMLP intermediate widthVocabulary sizeConfigured token vocabulary dimension</p><h3>Important Formulas</h3><p><strong>Tensor parameter count</strong></p><p>Product of tensor dimensions.</p><p><strong>Raw weight memory</strong></p><p>Parameters × Bytes per parameter.</p><p><strong>Attention head dimension</strong></p><p>Hidden size / Query heads, for architectures where Query heads evenly divide the hidden dimension.</p><p><strong>KV-cache storage</strong></p><p>2 × Layers × KV heads × Head dimension × Bytes per element × Cached token positions.</p><p>For independent sequences, sum the cached token positions across sequences.</p><p><strong>Approximate GPU inference memory</strong></p><p>Model weights + KV-cache allocations + Runtime memory + Execution buffers.</p><h3>Five Things Worth Remembering</h3><p><strong>1. Model configuration and model weights are different.</strong></p><p>One describes the computation; the other stores the learned numerical values.</p><p><strong>2. Tensor shape and dtype determine raw parameter storage.</strong></p><p>You can estimate checkpoint memory directly from this metadata.</p><p><strong>3. Attention architecture influences inference memory.</strong></p><p>Fewer KV heads can significantly reduce KV-cache requirements.</p><p><strong>4. Tokenizer artifacts must match the model.</strong></p><p>Special tokens and chat templates are part of correct inference behavior.</p><p><strong>5. Checkpoint size is not total GPU memory usage.</strong></p><p>The execution runtime needs additional memory for caches, kernels, and buffers.</p><h3>17. What’s Next?</h3><p>We now understand what an LLM repository contains, how trained weights are organized, what model configuration tells us, and how to estimate memory requirements.</p><p>But understanding the checkpoint is only one part of understanding inference.</p><p>The next question is:</p><p><strong>How does the GPU actually execute these computations?</strong></p><p>For example:</p><ul><li>Why are GPUs better suited to large matrix multiplications?</li><li>What exactly is a CUDA kernel?</li><li>How do GPU cores, Tensor Cores, and memory bandwidth interact?</li><li>Why can prefill and decode have different performance bottlenecks?</li><li>Why can an inference workload become memory-bandwidth-bound even when the GPU has substantial compute capacity?</li></ul><p>These are the questions we’ll explore next.</p><p>Because selecting an LLM is not only about whether it fits into memory.</p><p>It is also about understanding <strong>how efficiently the hardware can execute it</strong>.</p><p>And that is where GPU architecture and CUDA enter the picture.</p><h3>Further Reading</h3><ul><li><a href="https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct">Hugging Face — Qwen2.5–0.5B-Instruct</a></li><li><a href="https://huggingface.co/docs/transformers/main/models">Hugging Face — Loading Models</a></li><li><a href="https://huggingface.co/docs/safetensors/metadata_parsing">Hugging Face — Safetensors Metadata</a></li><li><a href="https://huggingface.co/docs/transformers/chat_templating">Hugging Face — Chat Templates</a></li><li><a href="https://github.com/huggingface/safetensors">Safetensors — File Format and Implementation</a></li><li><a href="https://docs.vllm.ai/">vLLM Documentation</a></li></ul><p><em>Part 2 of LLM Inference Engineering — a practical series exploring model architecture, GPU hardware, memory, CUDA, LLM serving, and performance engineering from first principles.</em></p><p><strong>The goal isn’t just to run an LLM. It’s to understand the system well enough to predict its behavior before running it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=488fb1d22aea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Actually Happens When an LLM Generates a Token?]]></title>
            <link>https://medium.com/@ankushwork21/what-actually-happens-when-an-llm-generates-a-token-25b73d73cf4a?source=rss-6027130df4cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/25b73d73cf4a</guid>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Ankush Dhanda]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 12:53:52 GMT</pubDate>
            <atom:updated>2026-10-19T12:53:52.092Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 1 of LLM Inference Engineering — Understanding tokenization, transformer execution, autoregressive generation, prefill, decode, and KV caching from first principles.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1muN6r-ME5TRAdQQI4dUw.png" /></figure><h3>Introduction</h3><p>We interact with Large Language Models almost every day.</p><p>We enter a prompt, and within seconds, the model starts generating a response.</p><p>But what exactly happens between entering a prompt and receiving the first word?</p><p>Consider a simple example:</p><p><strong>Input:</strong> “The capital of France is”</p><p><strong>Output:</strong> “Paris.”</p><p>To us, this looks like a straightforward question-and-answer interaction.</p><p>But underneath, the system is executing a sequence of mathematical operations involving token IDs, numerical representations, transformer layers, and GPU computation.</p><p>The interesting part is that an autoregressive LLM doesn’t normally generate the entire response in one operation.</p><p>It predicts the next token, incorporates that token into its context, and repeats the process.</p><p>This raises some important questions:</p><ul><li>How does text become something a GPU can process?</li><li>What exactly does the transformer calculate?</li><li>How is the next token selected?</li><li>Why can’t we generate all output tokens simultaneously?</li><li>What is the difference between prefill and decode?</li><li>Why do we need a KV cache?</li><li>Why does generating a long response take time even on a powerful GPU?</li></ul><p>Let’s follow a prompt through the complete inference lifecycle and understand the reasoning behind each stage.</p><h3>1. The Big Picture: From Text to Generated Tokens</h3><p>Before going into the individual components, let’s look at the complete process.</p><pre>USER PROMPT<br>            &quot;The capital of France is&quot;<br>                       |<br>                       v<br>                  TOKENIZER<br>                 Text → Token IDs<br>                       |<br>                       v<br>                  EMBEDDINGS<br>            Token IDs → Vectors<br>                       |<br>                       v<br>               TRANSFORMER MODEL<br>                 +-----------+<br>                 | Attention |<br>                 | MLP       |<br>                 | Layers    |<br>                 +-----------+<br>                       |<br>                       v<br>                     LOGITS<br>            Scores for next tokens<br>                       |<br>                       v<br>                TOKEN SELECTION<br>             Greedy / Sampling<br>                       |<br>                       v<br>               NEXT TOKEN ID<br>                       |<br>              +--------+--------+<br>              |                 |<br>              v                 v<br>       Add to context       Decode to text<br>              |                 |<br>              |                 v<br>              |            &quot; Paris&quot;<br>              |<br>              +----&gt; Repeat generation</pre><p>There are two important things to notice here.</p><p><strong>First:</strong> The model fundamentally works with numerical representations, not human-readable strings.</p><p><strong>Second:</strong> A generated token is fed into subsequent generation steps. The model does not need to convert each token back to text and tokenize it again internally.</p><p>Let’s understand every stage.</p><h3>2. Tokenization: How Text Becomes Numbers</h3><p>A GPU cannot directly perform matrix multiplication on the string:</p><p>“The capital of France is”</p><p>We first need to represent the text as numbers.</p><p>This is the job of a <strong>tokenizer</strong>.</p><p>A tokenizer breaks text into units called tokens and maps them to integer identifiers known as token IDs.</p><p>For example, a tokenizer might conceptually produce:</p><p>TokenToken IDThe101 capital205 of87 France412 is56</p><p>These IDs are completely illustrative. Real IDs and token boundaries depend on the model’s tokenizer.</p><p>The final representation might resemble:</p><pre>input_ids = [101, 205, 87, 412, 56]</pre><h3>Is a Token the Same as a Word?</h3><p>Not necessarily.</p><p>A token might represent:</p><ul><li>A complete word</li><li>Part of a word</li><li>Punctuation</li><li>Spaces combined with text</li><li>Special symbols or control tokens</li></ul><p>For example, a rare word may be divided into multiple subword tokens, while a common word may correspond to a single token.</p><p>Different models may use different vocabularies and tokenization algorithms.</p><p>This means <strong>1,000 words and 1,000 tokens are not the same thing</strong>.</p><p>Why is this important?</p><p>Because inference workloads, model context limits, KV-cache requirements, and performance metrics are generally expressed in tokens rather than words.</p><h3>What Is a Vocabulary?</h3><p>A tokenizer has a vocabulary containing tokens that it can represent.</p><p>Suppose a model has a vocabulary containing 50,000 token IDs.</p><p>When predicting the next token, the model can produce a score for each possible token in that vocabulary.</p><p>We’ll see how that happens shortly.</p><p><strong>Key takeaway:</strong> Tokenization converts human-readable text into token IDs understood by the model. Token boundaries and IDs are model-specific.</p><h3>3. Embeddings: Turning Token IDs Into Vectors</h3><p>After tokenization, we have a list of integers.</p><p>But there’s a problem.</p><p>A token ID such as 205 is just an identifier.</p><p>The integer itself does not encode the meaning of the token.</p><p>The model needs a numerical representation that can participate in meaningful mathematical operations.</p><p>This is where <strong>embeddings</strong> come in.</p><p>An embedding layer maps each token ID to a learned vector.</p><p>For example:</p><pre>Token ID: 205<br>           Embedding lookup<br>                  |<br>                  v<br>[0.12, -0.34, 0.87, 0.06, ...]</pre><p>The values are illustrative.</p><p>A model might use an embedding dimension of 4,096, meaning each token initially maps to a vector with 4,096 components.</p><p>For five input tokens, the resulting embedding tensor would have a conceptual shape of:</p><pre>Sequence length × Hidden dimension<br>5 × 4096</pre><p>In a batched system, there is an additional batch dimension.</p><h3>Why Do We Need Embeddings?</h3><p>Neural networks perform operations on numerical tensors.</p><p>Embeddings provide learned numerical representations that can be transformed by subsequent layers.</p><p>The model also incorporates positional information so it can distinguish the order of tokens.</p><p>This matters because:</p><p>“Dog bites man”</p><p>and</p><p>“Man bites dog”</p><p>contain many of the same words but express very different meanings.</p><p>By combining token representations with positional information, the transformer can reason over the ordered sequence.</p><p><strong>Key takeaway:</strong> Embeddings convert token IDs into learned numerical vectors that the transformer can process.</p><h3>4. What Happens Inside the Transformer?</h3><p>This is where most of the model’s computation happens.</p><p>A transformer-based language model contains multiple layers that repeatedly transform the representations of the input tokens.</p><p>For our purposes, two important building blocks are:</p><p><strong>Attention</strong></p><p>Allows a token representation to incorporate relevant information from earlier tokens in the context.</p><p><strong>Feed-forward network (MLP)</strong></p><p>Applies learned nonlinear transformations to token representations.</p><p>Transformer layers also use mechanisms such as normalization and residual connections.</p><h3>Understanding Attention Intuitively</h3><p>Consider:</p><p>“The animal was tired because it had been running.”</p><p>When the model processes the token representing “it”, earlier information about “the animal” may be useful.</p><p>Attention provides a mechanism for combining information from different token positions.</p><p>In a typical transformer attention operation, the model computes three kinds of representations:</p><ul><li>Query (Q)</li><li>Key (K)</li><li>Value (V)</li></ul><p>A simplified attention expression is:</p><p><strong>Attention(Q, K, V) = softmax(QKᵀ / √dₖ)V</strong></p><p>Let’s interpret it.</p><p>The Query and Key vectors determine how strongly token positions attend to one another.</p><p>The resulting attention weights are then used to combine the corresponding Value vectors.</p><p>In a decoder-only causal language model, attention also uses a causal mask.</p><p>This prevents a token position from attending to future token positions.</p><h3>Why Is the Causal Mask Important?</h3><p>Suppose the model is processing:</p><p>“The capital of France is”</p><p>When predicting what comes next, the model must not depend on future output tokens that haven’t been generated yet.</p><p>The causal mask enforces that restriction.</p><p>This is fundamental to autoregressive language generation.</p><p>The transformer processes token representations through its layers, eventually producing a final representation from which next-token scores can be calculated.</p><p><strong>Key takeaway:</strong> Attention lets token representations incorporate preceding context, while the transformer’s learned weights determine how those representations are processed.</p><h3>5. Logits: How the Model Predicts the Next Token</h3><p>After the transformer finishes processing the current context, the model produces scores over its vocabulary.</p><p>These scores are called <strong>logits</strong>.</p><p>Suppose our prompt is:</p><p>“The capital of France is”</p><p>The model might produce next-token logits like the following:</p><p>Candidate token:Illustrative logit Paris8.2 London3.1 Berlin2.8 Rome1.5</p><p>These are hypothetical scores, and only four candidates are shown.</p><p>The complete logits vector has an entry for every token in the model’s vocabulary.</p><h3>Are Logits Probabilities?</h3><p>No.</p><p>Logits are raw scores.</p><p>They can be converted into a probability distribution using a function called <strong>softmax</strong>:</p><p>P(token i) = exp(logit i) / sum(exp(all logits))</p><p>The probability of each token depends on its score relative to the scores of the other tokens.</p><h3>How Does the Model Choose a Token?</h3><p>That depends on the decoding strategy.</p><p><strong>Greedy decoding:</strong> Choose the token with the highest logit.</p><p><strong>Sampling:</strong> Select a token from a probability distribution, potentially adjusted by temperature, top-k, or top-p sampling.</p><p>For our example, greedy decoding might select:</p><p>Paris</p><p>But our generation process isn’t necessarily finished.</p><p>The model has selected only the next token.</p><p><strong>Key takeaway:</strong> The model produces logits for possible next tokens. A decoding strategy selects which token to generate.</p><h3>6. Autoregressive Generation: Why Tokens Are Generated Sequentially</h3><p>This is one of the most important concepts in LLM inference.</p><p>An autoregressive language model predicts each new token conditioned on the original prompt and the preceding generated tokens.</p><p>Consider:</p><p><strong>Prompt:</strong> “The RTX 3090”</p><p>The generation process might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*5JvgC4s8PeSw5g776GH3bA.png" /></figure><p>This is an illustrative sequence; token boundaries depend on the tokenizer.</p><p>Notice that at step 4, the model depends on the original prompt and all three previously generated tokens.</p><p>Mathematically, we can express generation as:</p><p><strong>P(t₄ | prompt, t₁, t₂, t₃)</strong></p><p>For an entire output sequence, the probability is factorized into successive next-token probabilities.</p><p>This means each output token depends on the previously selected outputs.</p><h3>Why Can’t the GPU Generate All 500 Tokens at Once?</h3><p>Suppose we request 500 output tokens.</p><p>With conventional autoregressive decoding, token 2 depends on token 1, token 3 depends on tokens 1 and 2, and so on.</p><p>We don’t know token 500 until the preceding generation decisions have been made.</p><p>Therefore, generation has a sequential dependency across output-token positions.</p><p>However, an important distinction is:</p><p><strong>Sequential token generation does not mean the GPU is doing only one small operation at a time.</strong></p><p>Within each generation step, the GPU can execute large numbers of mathematical operations in parallel.</p><p>This distinction between sequential generation steps and parallel work within each step is fundamental to understanding LLM performance.</p><p>There are advanced techniques, such as speculative decoding, that can change how token generation is executed and verified. But standard autoregressive decoding is our starting point.</p><h3>7. Prefill vs Decode: Two Very Different Phases</h3><p>Now we reach one of the most important systems concepts.</p><p>LLM inference is commonly divided into two phases:</p><p><strong>Prefill</strong> and <strong>Decode</strong>.</p><p>Although both involve executing the transformer, they have different workload characteristics.</p><h3>Prefill — Processing the Input Prompt</h3><p>Suppose a user submits a prompt containing 2,000 tokens.</p><p>During prefill, the model processes the input sequence, computes the relevant attention information, and prepares the state needed for generation.</p><p>The transformer can process many prompt positions in parallel.</p><p>This makes prefill comparatively efficient at utilizing parallel GPU computation, although long input sequences can still require substantial work.</p><p>Prefill also produces the logits used to select the first output token.</p><h3>Decode — Generating Additional Tokens</h3><p>After the initial prompt is processed, the model generates subsequent tokens autoregressively.</p><p>In standard decoding, each step incorporates the latest generated token and produces another token prediction.</p><p>This continues until the model reaches a stopping condition, such as an end-of-sequence token or a configured generation limit.</p><h3>Why Are Their Performance Characteristics Different?</h3><p>Prefill processes many input positions together and often involves large matrix multiplications.</p><p>Decode typically processes one new position per active sequence per step, repeatedly reading model weights and relevant cached attention data.</p><p>For many common dense-model workloads:</p><ul><li>Prefill tends to be more compute-intensive.</li><li>Single-request decode tends to be more sensitive to memory bandwidth.</li></ul><p>The exact bottleneck depends on the model, hardware, batching, context length, and inference implementation.</p><h3>A Thought Experiment</h3><p>Consider two users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*QWn5ak5Zt4ot79uw6KI_EQ.png" /></figure><p>Which request will take longer?</p><p>A reasonable initial prediction is that <strong>User A may have higher total latency</strong>, because it requires many more sequential generation steps.</p><p>However, User B may take longer to produce its first token because its initial prompt is much longer.</p><p>This gives us two different performance concerns:</p><ul><li>How quickly can the model start responding?</li><li>How quickly can it finish responding?</li></ul><p>There is no guaranteed winner without considering the model, runtime, and workload.</p><p>This distinction becomes especially important when benchmarking LLM inference.</p><h3>8. The KV Cache: Avoiding Repeated Computation</h3><p>Autoregressive generation creates another problem.</p><p>Suppose the model has processed 1,000 tokens.</p><p>When generating the next token, it needs information from the preceding context.</p><p>A naive implementation without caching might repeatedly recompute information for all previous positions.</p><p>This creates unnecessary computation.</p><h3>The Naive Approach</h3><p>Conceptually:</p><pre>Generate token 1:<br>Process the prompt<br>Generate token 2:<br>Process prompt + token 1<br>Generate token 3:<br>Process prompt + tokens 1, 2<br>Generate token 4:<br>Process prompt + tokens 1, 2, 3</pre><p>As the generated sequence grows, the model repeatedly processes more of the same context.</p><h3>The Solution: KV Caching</h3><p>Recall that attention uses Queries, Keys, and Values.</p><p>For causal attention, the previously computed Key and Value representations for earlier token positions can be reused during subsequent decoding steps.</p><p>So instead of recomputing them repeatedly, the inference runtime stores them in a <strong>Key-Value cache</strong>, usually called the KV cache.</p><p>During decoding:</p><ol><li>Previously computed Keys and Values are retrieved from the cache.</li><li>The model computes new representations for the current token.</li><li>Attention uses the new Query and the relevant cached Keys and Values.</li><li>The newly computed Key and Value entries are added to the cache.</li></ol><p>The model still performs computation at every generation step, and attention still needs to access the relevant preceding context.</p><p>But it avoids substantial redundant work.</p><h3>The Trade-off</h3><p>KV caching improves computational efficiency by using additional memory.</p><p>This introduces a new systems problem.</p><p>The cache occupies GPU memory that could otherwise be available for model weights, temporary buffers, or additional requests.</p><p><strong>KV caching trades memory capacity and bandwidth for reduced recomputation.</strong></p><h3>9. How Much GPU Memory Does the KV Cache Need?</h3><p>Let’s estimate the memory requirement for a conventional full-context KV cache.</p><p>A useful simplified formula is:</p><p><strong>KV cache bytes = 2 × Layers × KV heads × Head dimension × Bytes per element × Cached tokens</strong></p><p>The factor of 2 accounts for storing both Keys and Values.</p><p>For multiple independent requests, we calculate the cache memory across their cached token counts.</p><h3>Example: A Hypothetical Transformer</h3><p>Assume:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*BBlXj3yCFvvhq8A6tedbFA.png" /></figure><p>The memory required per cached token is:</p><p>2 × 32 × 8 × 128 × 2</p><p>= 131,072 bytes</p><p>= <strong>128 KiB per token</strong></p><p>Now consider different context lengths and request counts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*ReSnSRahEz9vb2238pZv3g.png" /></figure><p>These values assume independent requests of equal cached length, and exclude cache allocator overhead and optimizations such as prefix sharing.</p><p>Two important relationships emerge:</p><p><strong>1. Increasing cached context length increases KV-cache memory approximately linearly.</strong></p><p><strong>2. Increasing the number of active independent requests increases total KV-cache memory.</strong></p><h3>What Happens When We Run Out of KV-Cache Capacity?</h3><p>Suppose our GPU has only 7 GiB available for KV-cache storage.</p><p>But 16 requests, each requiring 4,096 cached tokens, collectively need 8 GiB.</p><p>We cannot keep the entire required working set resident simultaneously within that 7 GiB budget.</p><p>An inference engine may respond by queuing requests, limiting the number of active sequences, preempting work and recomputing state where supported, or using other configured memory-management strategies.</p><p>It cannot simply discard the Keys and Values required for correct attention and continue as though they were available.</p><p>This is one reason inference engines such as vLLM need schedulers and KV-cache management.</p><h3>Why Does This Matter?</h3><p>We often think that if a model fits into GPU memory, it can run any workload supported by its architecture.</p><p>That is incorrect.</p><p>Model weights, KV-cache storage, and execution buffers compete for GPU memory.</p><p>A model might work well for one short request but experience memory pressure when serving many long-context requests simultaneously.</p><p>This is the foundation of capacity planning for LLM inference servers.</p><h3>10. How Do We Measure LLM Inference Performance?</h3><p>Now that we understand prefill and decode, we can introduce several performance metrics.</p><h4>Time to First Token (TTFT)</h4><p>TTFT measures how long it takes for the first generated token to become available.</p><p>In an end-to-end benchmark, this is often measured from sending a request until receiving its first streamed output.</p><p>It can be influenced by request queuing, preprocessing, prefill computation, and response delivery.</p><p>Longer input prompts can increase TTFT because there is more prompt processing to perform.</p><h4>Time Per Output Token (TPOT)</h4><p>TPOT measures the average time spent generating subsequent output tokens after the first token.</p><p>A common per-request definition is:</p><p><strong>TPOT = (Total latency − TTFT) / (Output tokens − 1)</strong></p><p>This applies when more than one output token is generated.</p><h4>Inter-Token Latency (ITL)</h4><p>ITL measures the time between successive streamed outputs.</p><p>This helps us understand whether tokens arrive smoothly or whether generation has irregular pauses.</p><h4>Throughput</h4><p>Throughput measures how much work the system completes per unit of time.</p><p>Depending on the workload, we may measure:</p><ul><li>Output tokens per second</li><li>Prompt tokens per second</li><li>Completed requests per second</li></ul><p>An important distinction is that <strong>tokens per second for one request</strong> and <strong>aggregate tokens per second across many requests</strong> describe different aspects of performance.</p><p>For example, an inference server may improve total token throughput through batching while increasing the latency experienced by some individual requests.</p><p>This is why performance engineering requires more than a single benchmark number.</p><h3>11. Where Do CPU, RAM, GPU, and VRAM Participate?</h3><p>Let’s connect what we’ve learned to the hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*MgH4uVAaIOcdJzzl1zDTlQ.png" /></figure><p>A simplified request lifecycle looks like this:</p><pre>USER REQUEST<br>                      |<br>                      v<br>                API / Server<br>                      |<br>                      v<br>               CPU Tokenization<br>                      |<br>                      v<br>                  Token IDs<br>                      |<br>                      v<br>                GPU Execution<br>                      |<br>             +--------+--------+<br>             |                 |<br>             v                 v<br>        Model Weights       KV Cache<br>             |                 |<br>             +--------+--------+<br>                      |<br>                      v<br>                 Next Token<br>                      |<br>                      v<br>             Token ID → Output Text<br>                      |<br>                      v<br>                API Response</pre><p>Not every operation happens on the GPU.</p><p>Tokenization, request handling, and other host-side work can influence latency.</p><p>Likewise, the GPU’s memory capacity, compute capability, and memory bandwidth influence how efficiently model calculations execute.</p><p>Understanding the entire system is essential when diagnosing inference bottlenecks.</p><h3>12. Hands-On Exercise: Reasoning About Generation and KV Memory</h3><p>Before running a real language model, we can demonstrate two concepts using ordinary Python.</p><p>These exercises do not require a GPU, PyTorch, or an inference engine.</p><p>They are conceptual exercises, not actual LLM benchmarks.</p><h3>Experiment A — Simulating Autoregressive Token Selection</h3><pre>prompt = &quot;The RTX 3090&quot;<br># Hypothetical next-token logits for each generation step.<br>scores_per_step = [<br>    {&quot; has&quot;: 3.0, &quot; uses&quot;: 1.0},<br>    {&quot; 24&quot;: 4.0, &quot; 16&quot;: 1.0},<br>    {&quot; GB&quot;: 3.0, &quot; cores&quot;: 1.0},<br>    {&quot; VRAM.&quot;: 4.0, &quot; RAM.&quot;: 2.0},<br>]<br>context = prompt<br>for step, scores in enumerate(scores_per_step, 1):<br>    next_token = max(scores, key=scores.get)<br>    print(f&quot;Step {step}: {next_token!r}&quot;)<br>    context += next_token<br>    print(&quot;Context:&quot;, context)<br>print(&quot;Final:&quot;, context)</pre><p>The final text is:</p><pre>The RTX 3090 has 24 GB VRAM.</pre><p>Notice that tokens are selected one after another and appended to the sequence.</p><p>The important limitation is that the scores here are manually predefined rather than calculated from the context.</p><p>A real transformer computes new logits conditioned on the preceding token sequence.</p><p>This program only demonstrates the generation loop.</p><h3>Experiment B — Estimating KV-Cache Memory</h3><p>Let’s calculate KV-cache memory requirements for our hypothetical transformer.</p><pre>layers = 32<br>kv_heads = 8<br>head_dim = 128<br>bytes_per_element = 2<br>bytes_per_token = (<br>    2<br>    * layers<br>    * kv_heads<br>    * head_dim<br>    * bytes_per_element<br>)<br>context_length = 4096<br>for concurrent_requests in [1, 4, 8, 16]:<br>    total_bytes = (<br>        concurrent_requests<br>        * context_length<br>        * bytes_per_token<br>    )<br>    memory_gib = total_bytes / (1024 ** 3)<br>    print(<br>        f&quot;{concurrent_requests} requests: &quot;<br>        f&quot;{memory_gib:.2f} GiB&quot;<br>    )</pre><p>Expected calculated results:</p><pre>1 requests: 0.50 GiB<br>4 requests: 2.00 GiB<br>8 requests: 4.00 GiB<br>16 requests: 8.00 GiB</pre><p>These values represent theoretical KV tensor storage, not measured GPU allocation.</p><p>The main lesson is that context length, cache architecture, cache precision, and concurrency determine KV-cache requirements.</p><p>Later, when we host a real model, we’ll compare memory estimates against actual GPU observations.</p><h3>13. Common Misconceptions</h3><h3>Misconception 1: An LLM Generates Entire Sentences at Once</h3><p>Standard autoregressive models generate tokens sequentially.</p><p>A token isn’t necessarily a word, and a single sentence may require many generation steps.</p><h3>Misconception 2: A Longer Prompt Always Takes Longer Than a Longer Response</h3><p>Not necessarily.</p><p>Prefill can process many input positions in parallel, while decoding has sequential dependencies.</p><p>Prompt length and output length affect latency differently.</p><h3>Misconception 3: KV Caching Eliminates All Repeated Work</h3><p>KV caching avoids recomputing previously calculated attention Keys and Values.</p><p>However, the model still executes computations for each new token, including attention over relevant cached context.</p><h3>Misconception 4: A Model That Fits in VRAM Can Handle Unlimited Concurrency</h3><p>Model weights are only part of GPU memory consumption.</p><p>KV-cache requirements increase with the number and length of active sequences.</p><h3>Misconception 5: High GPU Utilization Automatically Means Good Inference Performance</h3><p>GPU utilization alone doesn’t explain response latency, token throughput, batching efficiency, or memory pressure.</p><p>We must measure the entire inference workload.</p><h3>14. Quick Revision Notes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*B0OSEMqn3ReOfSwArQYdug.png" /></figure><h3>Five Principles to Remember</h3><p><strong>1. An LLM fundamentally predicts tokens.</strong></p><p>Text generation is built from successive token predictions, not the direct generation of complete responses.</p><p><strong>2. Standard autoregressive generation has sequential dependencies.</strong></p><p>The next generated token depends on preceding tokens.</p><p><strong>3. Prefill and decode are different workloads.</strong></p><p>They exercise GPU compute and memory resources differently.</p><p><strong>4. KV caching saves computation by consuming memory.</strong></p><p>This trade-off becomes important with long contexts and concurrent requests.</p><p><strong>5. Inference performance is a systems problem.</strong></p><p>The GPU, model architecture, memory capacity, memory bandwidth, inference engine, and workload all influence the final behavior.</p><h3>15. What’s Next?</h3><p>We now understand the high-level journey from a text prompt to generated tokens.</p><p>But an important question remains:</p><p><strong>What exactly are the model files that an inference engine loads before any of this computation can begin?</strong></p><p>When we download an LLM, we may encounter files such as:</p><ul><li>config.json</li><li>tokenizer.json</li><li>tokenizer_config.json</li><li>model.safetensors</li><li>Weight shards and index files</li></ul><p>What does each file contain?</p><p>How does the inference engine reconstruct a model from them?</p><p>Which data stays in system RAM, and which data moves into GPU memory?</p><p>And how can we predict the memory requirements before downloading a model?</p><p>These are the questions we’ll investigate next.</p><p>Understanding model artifacts and loading behavior will connect the mathematical execution pipeline with the actual software and memory layout of an LLM inference system.</p><p>Our guiding principle remains:</p><p><strong>Don’t just run an LLM. Understand what happens inside the system, why it behaves that way, and how to measure it.</strong></p><h3>Further Reading</h3><ul><li><a href="https://huggingface.co/docs/transformers/main_classes/tokenizer">Hugging Face — Tokenizers</a></li><li><a href="https://github.com/huggingface/transformers/blob/main/docs/source/en/llm_tutorial_optimization.md">Hugging Face — Optimizing LLM Inference</a></li><li><a href="https://developer.nvidia.com/blog/?p=73739">NVIDIA — Mastering LLM Techniques: Inference Optimization</a></li><li><a href="https://docs.vllm.ai/en/stable/benchmarking/cli/">vLLM — Benchmarking and Latency Metrics</a></li></ul><p><em>Part 1 of LLM Inference Engineering — A hands-on series about GPUs, CUDA, model architecture, memory, quantization, inference serving, and performance engineering.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25b73d73cf4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Before Hosting an LLM: Understanding the Hardware and Software Stack]]></title>
            <link>https://medium.com/@ankushwork21/before-hosting-an-llm-understanding-the-hardware-and-software-stack-0bf10c337188?source=rss-6027130df4cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bf10c337188</guid>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gpu-computing]]></category>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ankush Dhanda]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 12:27:53 GMT</pubDate>
            <atom:updated>2026-10-19T12:27:53.890Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 0 of LLM Inference Engineering — A beginner-friendly, hands-on journey through GPUs, CUDA, model memory, Python environments, and LLM serving.</em></p><h3>Introduction</h3><p>Today, running a Large Language Model (LLM) locally can be as simple as downloading a model and executing a few commands.</p><p>But running an LLM and understanding how it runs are two different things.</p><p>Before hosting my first model, I wanted to answer some fundamental questions:</p><ul><li>What hardware is actually required to run an LLM?</li><li>What is the difference between a GPU, CUDA, PyTorch, and vLLM?</li><li>Why is GPU memory (VRAM) so important?</li><li>How can we estimate whether a model will fit on our GPU?</li><li>What happens when we load a model?</li><li>How do we prepare a reliable environment for LLM experiments?</li></ul><p>These questions are important because successful LLM inference is not just about selecting a powerful model. It is about understanding how hardware resources, model architecture, numerical precision, and inference software interact.</p><p>In this article, we’ll build the foundational understanding required to start experimenting with LLM inference.</p><p>Our long-term learning approach will be:</p><p><strong>Predict → Experiment → Measure → Understand</strong></p><p>Let’s start with the machine itself.</p><h3>1. What Hardware Is Required to Run an LLM?</h3><p>An LLM inference system typically involves five important hardware components:</p><ol><li>CPU</li><li>System RAM</li><li>Storage (SSD/HDD)</li><li>GPU</li><li>GPU memory (VRAM)</li></ol><p>All five contribute to the inference process, but they have different responsibilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ySlkfb4aaLuitu3-Dt9p9g.png" /><figcaption>Inside an LLM inference system: how CPU, GPU, memory, CUDA, and model-serving software work together.</figcaption></figure><h3>CPU — The General-Purpose Processor</h3><p>The CPU is responsible for coordinating many of the operations around inference.</p><p>Examples include:</p><ul><li>Handling incoming application requests</li><li>Preparing and tokenizing input text</li><li>Managing host-side application logic</li><li>Coordinating work submitted to the GPU</li><li>Performing some parts of model loading</li></ul><p>Although LLM inference is often GPU-intensive, the CPU remains essential.</p><p>For example, an inference server handling hundreds of requests still needs sufficient CPU resources to process network traffic, tokenize inputs, and perform other host-side operations.</p><h3>RAM — The System’s Working Memory</h3><p>System RAM holds data needed by the operating system and applications.</p><p>During LLM inference, RAM may contain:</p><ul><li>Model files or intermediate loading buffers</li><li>Tokenizer data</li><li>Application and Python objects</li><li>Request queues and other host-side data</li></ul><p>Some configurations also support keeping portions of a model in system memory and transferring data when needed.</p><p>However, accessing data across CPU and GPU memory can be considerably slower than accessing GPU-local memory.</p><h3>Storage — Where Model Files Live</h3><p>An LLM is usually distributed as files that we download and store on disk.</p><p>These files may include:</p><ul><li>Model weights</li><li>Model configuration</li><li>Tokenizer configuration</li><li>Vocabulary data</li><li>Generation settings</li></ul><p>A model can occupy several gigabytes or even hundreds of gigabytes of storage.</p><p>When the model is loaded for GPU inference, its weights are transferred into the memory used by the execution device, often GPU VRAM.</p><p>A fast SSD can help with loading large model files, although storage speed is usually not the primary bottleneck once a model is fully loaded and generating tokens.</p><h3>GPU — The Parallel Computing Engine</h3><p>The GPU is designed to execute large numbers of mathematical operations in parallel.</p><p>LLMs perform many matrix multiplications and tensor operations.</p><p>These operations are well suited to GPU execution.</p><p>Compared with a CPU, a modern GPU typically offers much higher parallel arithmetic throughput and memory bandwidth for these workloads.</p><p>This is one reason GPUs are widely used for both training and inference.</p><h3>VRAM — The GPU’s Memory</h3><p>VRAM is memory directly accessible to the GPU.</p><p>It stores data needed during GPU execution, including:</p><ul><li>Model weights</li><li>KV cache</li><li>Intermediate tensors</li><li>Temporary computation buffers</li><li>Runtime allocations</li></ul><p><strong>For local LLM inference, VRAM capacity is often the first constraint to evaluate.</strong></p><p>A GPU may have significant computational power but still be unable to load a model because it lacks sufficient memory.</p><h3>Putting the Hardware Together</h3><pre>HOST MACHINE<br>+---------------------------------------------+<br>|                                             |<br>|    Storage (SSD)                            |<br>|    Model files                              |<br>|          |                                  |<br>|          v                                  |<br>|    System RAM                               |<br>|    Loading buffers / application data       |<br>|          |                                  |<br>|          v                                  |<br>|    CPU                                      |<br>|    Requests / tokenization / coordination   |<br>|          |                                  |<br>+----------|----------------------------------+<br>           |<br>           | PCIe (typical discrete GPU)<br>           v<br>+---------------------------------------------+<br>|                  GPU                        |<br>|                                             |<br>|     GPU Compute Units / Tensor Cores        |<br>|                  |                          |<br>|                  v                          |<br>|                VRAM                         |<br>|                                             |<br>|     +-------------------------------+       |<br>|     | Model Weights                 |       |<br>|     | KV Cache                      |       |<br>|     | Temporary Buffers             |       |<br>|     | Runtime Allocations           |       |<br>|     +-------------------------------+       |<br>|                                             |<br>+---------------------------------------------+</pre><p>This is a conceptual diagram. Real implementations use overlapping CPU/GPU operations and more complex data movement.</p><p><strong>Key takeaway:</strong> The CPU coordinates much of the system, storage holds model artifacts, system RAM supports host operations, and the GPU performs most of the heavy tensor computation in a GPU-based inference setup.</p><h3>2. Why Does GPU Memory Determine Which LLM We Can Run?</h3><p>Every LLM has learned parameters, commonly called <strong>model weights</strong>.</p><p>These parameters are represented as numerical values.</p><p>For a dense model, a useful first approximation for weight storage is:</p><p><strong>Model weight memory ≈ Number of parameters × Bytes per parameter</strong></p><p>The number of bytes depends on how the parameters are represented.</p><p>PrecisionApproximate bytes per parameterFP324 bytesFP162 bytesBF162 bytesINT81 byteINT40.5 bytes</p><p>These are simplified storage estimates. Real quantized formats may require additional metadata, and not every model tensor must use the same precision.</p><h3>Example 1 — A 7B Model in FP16</h3><p>Suppose we want to run a model containing 7 billion parameters.</p><p>FP16 uses approximately 2 bytes per parameter.</p><p>Therefore:</p><p>7 billion × 2 bytes = 14 GB</p><p>This is approximately 13 GiB.</p><p>If our GPU has 24 GiB of VRAM, the raw model weights should fit, leaving memory for other runtime requirements.</p><p>But that doesn’t mean the remaining memory is entirely available for generating tokens.</p><h3>Example 2 — A 14B Model in FP16</h3><p>For a 14-billion-parameter model:</p><p>14 billion × 2 bytes = 28 GB</p><p>The weights alone exceed the capacity of a 24 GiB GPU.</p><p>So this model cannot be fully loaded onto that GPU in the assumed FP16 representation.</p><h3>Example 3 — The Same 14B Model in INT4</h3><p>Now suppose we use a compatible 4-bit quantized representation.</p><p>14 billion × 0.5 bytes = 7 GB</p><p>The theoretical weight memory becomes much smaller.</p><p>This is where <strong>quantization</strong> becomes useful.</p><p>Quantization reduces the numerical precision used to represent model parameters, often with the goal of reducing storage and memory requirements.</p><p>However, it may introduce trade-offs involving model quality, execution performance, and hardware compatibility.</p><p>We will explore these trade-offs experimentally in a dedicated article.</p><h3>Does This Mean a Model Fits If Its Weights Fit?</h3><p>Not necessarily.</p><p>Consider an illustrative 24 GiB GPU memory budget:</p><p>ComponentMemoryModel weights15 GiBRuntime and temporary buffers2 GiBKV cache4 GiBRemaining headroom3 GiBTotal24 GiB</p><p>These numbers are hypothetical, not measurements from a particular model.</p><p>An inference engine requires memory beyond the model weights.</p><p>One particularly important component is the <strong>KV cache</strong>, which stores previously computed attention information to avoid unnecessary repeated computation during autoregressive token generation.</p><p>KV-cache requirements depend on factors such as:</p><ul><li>Model architecture</li><li>Input context length</li><li>Generated tokens</li><li>Number of active requests</li><li>KV-cache precision</li></ul><p>That leads to an important distinction:</p><p><strong>A model fitting into VRAM does not guarantee that it can serve our desired context length or number of concurrent users.</strong></p><h3>Rough Model-Size Categories</h3><p>For illustration, consider an NVIDIA RTX 3090 with 24 GiB VRAM.</p><p>Model sizeInitial feasibility1B–4BComfortable starting point7B–8BUsually practical at FP16/BF16 with suitable settings12B–14BOften requires quantization20B–32BMay be feasible with supported 4-bit quantization and constraints70BToo large to fit entirely in VRAM, even at simple 4-bit weight estimates</p><p>These are approximate guidelines for conventional dense models, not universal compatibility guarantees.</p><p>Different architectures and serving configurations can behave differently.</p><p>Before downloading a model, we should evaluate both its weight memory and the resources required by our intended workload.</p><h3>3. GPU vs CUDA vs PyTorch vs LLM vs vLLM</h3><p>This is one of the most important distinctions to understand before working with LLMs.</p><p>These terms are related, but they represent different layers of the system.</p><h3>GPU — The Hardware</h3><p>The GPU is the physical device performing parallel computations.</p><p>Examples include NVIDIA RTX and data-center GPUs.</p><h3>CUDA — The GPU Computing Platform</h3><p>CUDA is NVIDIA’s parallel computing platform and programming model.</p><p>It includes programming interfaces, tools, and libraries for executing workloads on supported NVIDIA GPUs.</p><p>A CUDA kernel is a function that executes on the GPU.</p><p>CUDA makes it possible for software to use the GPU for general-purpose computation instead of only graphics rendering.</p><h3>PyTorch — The Machine Learning Framework</h3><p>PyTorch provides high-level abstractions for tensor operations and machine learning.</p><p>Instead of manually implementing every mathematical operation using CUDA, developers can use PyTorch operations that execute on the GPU.</p><p>For example:</p><pre>import torch<br>a = torch.tensor([1, 2, 3], device=&quot;cuda&quot;)<br>b = torch.tensor([4, 5, 6], device=&quot;cuda&quot;)<br>print(a + b)</pre><p>Here, PyTorch manages tensors and dispatches the relevant GPU operations.</p><p>This example requires a compatible CUDA-enabled PyTorch installation and NVIDIA GPU environment.</p><h3>LLM — The Model</h3><p>An LLM is the learned model itself.</p><p>A model includes an architecture and a set of parameters that determine how it processes input tokens and predicts subsequent tokens.</p><p>An LLM is not the same thing as the software that serves it.</p><h3>Inference Engine — Executes the Model</h3><p>An inference engine is responsible for executing model computations and managing inference-related resources.</p><p>Different inference systems emphasize different execution strategies and optimizations.</p><h3>vLLM — An LLM Inference and Serving Engine</h3><p>vLLM is an inference and serving engine designed for efficient LLM execution.</p><p>It provides capabilities such as:</p><ul><li>Model loading and execution</li><li>Request scheduling</li><li>KV-cache management</li><li>Efficient batching</li><li>Model-serving APIs</li><li>Streaming generation</li></ul><p>Its job is not to train the model or determine what an application should do.</p><p>Its job is to execute and serve models efficiently.</p><h3>What About Hugging Face?</h3><p>Hugging Face provides a model ecosystem and tools for working with models.</p><p>For example:</p><ul><li>The Hugging Face Hub hosts model repositories and artifacts.</li><li>Transformers provides model architectures, tokenizers, and APIs for loading and executing supported models.</li></ul><p>We can use Transformers for baseline inference experiments and vLLM for experiments focused on efficient serving.</p><h3>How Everything Fits Together</h3><pre>User / Application<br>                   |<br>                   v<br>             HTTP Request<br>                   |<br>                   v<br>            vLLM API Server<br>                   |<br>                   v<br>         Tokenizer / Scheduler<br>                   |<br>                   v<br>          Model Execution Engine<br>                   |<br>                   v<br>       PyTorch / Optimized GPU Kernels<br>                   |<br>                   v<br>          CUDA Libraries / Driver<br>                   |<br>                   v<br>               NVIDIA GPU<br>                   |<br>                   v<br>          Model Weights + KV Cache</pre><p>The diagram is intentionally simplified. vLLM can use multiple execution backends and specialized kernels, and several operations run on the CPU.</p><p>The key separation is:</p><p><strong>Model = What gets executed</strong></p><p><strong>Inference engine = How model execution is managed</strong></p><p><strong>CUDA and frameworks = Software mechanisms used for computation</strong></p><p><strong>GPU = Hardware performing the computation</strong></p><h3>4. Understanding the CUDA Driver and CUDA Toolkit</h3><p>A common source of confusion is seeing different CUDA versions on the same machine.</p><p>For example:</p><pre>nvidia-smi</pre><p>may show:</p><pre>Driver Version: 550.x<br>CUDA Version: 12.4</pre><p>While:</p><pre>nvcc --version</pre><p>might show:</p><pre>CUDA compilation tools, release 11.5</pre><p>Why?</p><p>Because these commands report different components.</p><h3>NVIDIA Driver</h3><p>The NVIDIA driver allows the operating system and GPU applications to communicate with the device.</p><p>The CUDA version shown by nvidia-smi represents the maximum CUDA version supported by the installed driver.</p><p>It does not identify the installed CUDA Toolkit.</p><h3>CUDA Toolkit</h3><p>The CUDA Toolkit provides development tools, including the CUDA compiler (nvcc), libraries, and supporting components.</p><p>The version shown by nvcc --version identifies the toolkit compiler being invoked.</p><h3>CUDA Runtime Libraries</h3><p>GPU software also depends on runtime libraries.</p><p>Framework distributions may bundle compatible CUDA runtime components and libraries.</p><p>Therefore, using prebuilt PyTorch or inference-engine packages does not necessarily require manually installing a complete CUDA Toolkit with nvcc.</p><p>However, a compatible NVIDIA driver is still necessary.</p><p>The exact compatibility requirements depend on the framework and package versions.</p><p><strong>Practical takeaway:</strong> Check the driver, compiler, and framework requirements separately. Do not upgrade CUDA simply because two version numbers differ.</p><h3>5. Preparing a Linux Machine for LLM Experiments</h3><p>Before installing frameworks, we should establish the actual machine configuration.</p><p>These commands work as a useful starting point on many Linux systems.</p><h3>Check the Operating System</h3><pre>cat /etc/os-release<br>uname -r<br>uname -m</pre><p>These commands show the distribution, kernel version, and machine architecture.</p><h3>Inspect the CPU</h3><pre>lscpu</pre><p>Useful information includes the CPU model, architecture, physical cores, and logical CPUs.</p><h3>Inspect the GPU</h3><p>For a supported NVIDIA setup:</p><pre>nvidia-smi</pre><p>To list GPUs:</p><pre>nvidia-smi -L</pre><p>To inspect VRAM:</p><pre>nvidia-smi --query-gpu=\<br>name,memory.total,memory.used,memory.free \<br>--format=csv</pre><p>Record the GPU model, available VRAM, driver version, and baseline utilization.</p><h3>Inspect CUDA</h3><pre>command -v nvcc</pre><p>If the CUDA compiler is available:</p><pre>nvcc --version</pre><p>An absent nvcc does not automatically mean CUDA-enabled Python inference is impossible.</p><h3>Inspect System Memory</h3><pre>free -h</pre><p>Pay attention to both free and available memory.</p><p>Linux uses spare RAM for caches, so low free memory does not necessarily indicate memory pressure.</p><h3>Inspect Storage</h3><pre>df -hT</pre><p>Ensure there is enough available storage for model weights, framework packages, logs, and experiment artifacts.</p><h3>Inspect Python</h3><pre>python3 --version<br>command -v python3</pre><p>The executable path matters, especially on machines with multiple Python installations.</p><p>At this stage, the goal is not to install everything. It is to understand what already exists.</p><h3>6. Why We Should Use a Python Virtual Environment</h3><p>Python-based ML tools can have complex dependency requirements.</p><p>PyTorch, Transformers, vLLM, and other libraries may require particular Python versions or compatible packages.</p><p>Installing everything directly into a system Python environment can create conflicts with unrelated projects.</p><p>A Python virtual environment (venv) provides a separate location for project-specific Python packages.</p><h3>Creating a Virtual Environment</h3><p>First choose a Python interpreter version supported by the packages you intend to install.</p><p>For example, if Python 3.11 is installed and appropriate for your selected framework versions:</p><pre>python3.11 -m venv ~/llm-lab/.venv</pre><p>Activate it:</p><pre>source ~/llm-lab/.venv/bin/activate</pre><p>Verify the interpreter:</p><pre>which python<br>python --version<br>python -m pip --version</pre><p>The Python executable should now point inside the virtual environment.</p><h3>What Does venv Actually Isolate?</h3><p>A virtual environment isolates Python package installations and interpreter-level configuration.</p><p>It does not isolate:</p><ul><li>The NVIDIA driver</li><li>The operating system</li><li>The physical GPU</li><li>System-wide CUDA installations</li><li>Environment variables already inherited from the shell</li></ul><p>For complete operating-system or application-container isolation, technologies like Docker can be useful.</p><p>For learning and controlled Python experiments, venv is often a simple starting choice.</p><p>One practical recommendation: explicitly select the Python interpreter rather than assuming the default python3 always points to the intended version.</p><h3>7. Organizing an LLM Inference Lab</h3><p>Experiments quickly become difficult to reproduce if model files, scripts, logs, and results are scattered across directories.</p><p>A simple directory structure helps.</p><pre>llm-lab/<br>│<br>├── .venv/<br>│<br>├── models/<br>│<br>├── experiments/<br>│   ├── EXP-001/<br>│   ├── EXP-002/<br>│   └── ...<br>│<br>├── benchmarks/<br>│<br>├── logs/<br>│<br>├── scripts/<br>│<br>└── notes/</pre><p>The directories serve different purposes.</p><p><strong>Models:</strong> Downloaded model artifacts and weights.</p><p><strong>Experiments:</strong> Individual experiment configurations and observations.</p><p><strong>Benchmarks:</strong> Performance measurements such as latency and throughput.</p><p><strong>Logs:</strong> Runtime and inference engine logs.</p><p><strong>Scripts:</strong> Reproducible Python scripts and shell commands.</p><p><strong>Notes:</strong> Explanations, hypotheses, and conclusions.</p><p>When possible, use a dedicated storage location with sufficient disk capacity and appropriate permissions.</p><p>Avoid making unnecessary system-wide permission changes merely to create project directories.</p><h3>What Should We Record for Every Experiment?</h3><p>A useful experiment record contains:</p><p>FieldPurposeExperiment IDUnique identifierQuestionWhat are we investigating?HypothesisWhat do we expect?HardwareGPU, CPU, RAMModelModel identifier and versionPrecisionFP16, BF16, INT4, etc.RuntimeFramework and configurationWorkloadInput/output tokens, concurrencyVRAM usageGPU memory consumptionLatencyTime taken to respondThroughputAmount of work completed per secondObservationsWhat actually happened?ConclusionWhat did we learn?</p><p>These details allow us to compare experiments scientifically instead of relying on impressions such as “this model feels faster.”</p><h3>8. Common Mistakes to Avoid</h3><p>Before hosting an LLM, there are several mistakes worth avoiding.</p><p><strong>Mistake 1: Assuming model-weight size equals total VRAM requirement.</strong></p><p>Model weights are only one component of inference memory usage.</p><p><strong>Mistake 2: Assuming more GPU utilization always means better performance.</strong></p><p>GPU utilization alone does not tell us how efficiently the server is handling requests.</p><p><strong>Mistake 3: Confusing the CUDA driver version with the CUDA Toolkit version.</strong></p><p>They represent different components and must be checked separately.</p><p><strong>Mistake 4: Installing ML packages directly into an existing development environment without checking dependencies.</strong></p><p>An isolated environment makes experiments easier to reproduce and debug.</p><p><strong>Mistake 5: Downloading large models before estimating memory requirements.</strong></p><p>A few calculations can prevent unnecessary downloads and failed loading attempts.</p><p><strong>Mistake 6: Measuring performance without recording the workload.</strong></p><p>Tokens per second is difficult to interpret without knowing the model, precision, input size, concurrency, and runtime settings.</p><h3>9. Quick Revision — Important Concepts</h3><p>ConceptWhat to rememberCPUCoordinates host-side operationsRAMStores host-side application data and buffersGPUExecutes parallel mathematical operationsVRAMHolds GPU-resident weights and runtime dataCUDANVIDIA’s GPU computing platformNVIDIA driverEnables software communication with the GPUCUDA ToolkitProvides compiler and development toolsPyTorchTensor and machine-learning frameworkLLMModel architecture and trained parametersTokenizerConverts text into token IDs and backInference engineExecutes models and manages inferencevLLMOptimized LLM inference and serving engineQuantizationUses reduced-precision numerical representationsKV cacheStores reusable attention keys and valuesContext lengthDetermines how many tokens the model can considervenvIsolates Python environments and dependencies</p><h3>Three Rules Worth Remembering</h3><p><strong>Rule 1 — Estimate before downloading.</strong></p><p>Start by estimating model-weight memory, then account for cache and runtime overhead.</p><p><strong>Rule 2 — Inspect before installing.</strong></p><p>Understand the current GPU, driver, Python, CUDA, memory, and storage environment.</p><p><strong>Rule 3 — Measure before optimizing.</strong></p><p>Do not randomly tune runtime settings without identifying which resource or performance metric is limiting the workload.</p><h3>10. What’s Next?</h3><p>We now understand the major hardware and software components required for LLM inference.</p><p>But an important question remains:</p><p><strong>What actually happens inside the system when we send a prompt to an LLM?</strong></p><p>For example, consider:</p><p>“The capital of France is…”</p><p>How does that text become tokens? How does a transformer process them? How are the next-token scores calculated? And why does generating a long response take time even on a powerful GPU?</p><p>In the next article, we’ll follow the complete lifecycle:</p><p><strong>Text → Tokens → Embeddings → Transformer → Logits → Next Token</strong></p><p>We’ll also introduce autoregressive generation, prefill, decode, and the motivation for KV caching.</p><p>Understanding this lifecycle will make it much easier to reason about GPU performance, memory usage, batching, and inference optimization later.</p><p>The goal of this series is simple:</p><p><strong>Don’t just learn how to host an LLM. Learn how the entire inference system works.</strong></p><p><em>Part 0 of the LLM Inference Engineering series — exploring GPU fundamentals, model memory, CUDA, inference runtimes, vLLM, and performance engineering from first principles.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bf10c337188" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Inference Engineering: From GPU Fundamentals to Production Serving]]></title>
            <link>https://medium.com/@ankushwork21/llm-inference-engineering-from-gpu-fundamentals-to-production-serving-668242d808a4?source=rss-6027130df4cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/668242d808a4</guid>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Ankush Dhanda]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 05:33:46 GMT</pubDate>
            <atom:updated>2026-10-25T13:46:03.178Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A hands-on journey through GPU architecture, CUDA, model execution, memory management, vLLM, quantization, and performance engineering.</em></p><h3>Why I’m Building This Lab</h3><p>Running a large language model locally is relatively straightforward. Understanding why it fits in memory, how it generates tokens, what limits its performance, and how to serve multiple users efficiently is a much deeper engineering problem.</p><p>This series documents my practical exploration of LLM inference systems.</p><p>Instead of treating an LLM as a black box, I want to understand the hardware, software stack, execution lifecycle, and performance trade-offs involved in serving one.</p><p>My approach is simple:</p><p><strong>Predict → Experiment → Measure → Explain</strong></p><p>Each technical article will combine first-principles explanations, reproducible experiments, measurements, and lessons learned.</p><h3>My Experimental Hardware</h3><ul><li>GPU: NVIDIA GeForce RTX 3090</li><li>GPU memory: 24 GB GDDR6X</li><li>Host RAM: Approximately 62 GB</li><li>Operating system: Linux</li><li>Storage: Approximately 916 GB root filesystem and 1.8 TB separate data filesystem</li><li>Primary inference engine: vLLM</li></ul><p>The machine will be used to investigate what can run efficiently, what requires optimization, and where the hardware limits appear.</p><h3>Phase 1 — Understanding the Hardware and Model</h3><p><strong>Part 0 — Building My LLM Inference Lab</strong></p><p>Hardware analysis, software environment, drivers, CUDA compatibility, storage planning, and benchmarking methodology.</p><p><em>Article link: </em><a href="https://medium.com/@ankushwork21/before-hosting-an-llm-understanding-the-hardware-and-software-stack-0bf10c337188?sharedUserId=ankushwork21"><em>Part 0 — Building My LLM Inference Lab.</em></a></p><p><strong>Part 1 — What Actually Happens When an LLM Generates a Token?</strong></p><p>Tokens, tokenization, transformer inference, autoregressive generation, and a walkthrough of the execution path.</p><p><em>Article link: </em><a href="https://medium.com/@ankushwork21/what-actually-happens-when-an-llm-generates-a-token-25b73d73cf4a?sharedUserId=ankushwork21"><em>Part 1 — What actually happens when an LLM Generates a Token</em></a><em>.</em></p><p><strong>Part 2 — Understanding LLM Model Files and Loading</strong></p><p>Model configuration, tokenizers, safetensors, weight shards, checkpoints, CPU memory, and GPU loading.</p><p><em>Article link: </em><a href="https://medium.com/@ankushwork21/inside-an-llm-model-what-are-we-actually-downloading-488fb1d22aea?sharedUserId=ankushwork21"><em>Part 2 — Understanding LLM Model Files and Loading.</em></a></p><p><strong>Part 3 — GPU Architecture and CUDA for LLM Inference</strong></p><p>CPU versus GPU execution, CUDA kernels, tensor cores, memory hierarchy, PCIe, and the role of PyTorch.</p><p><em>Article link: </em><a href="https://medium.com/@ankushwork21/how-gpus-actually-run-llms-cuda-tensor-cores-and-the-memory-bandwidth-bottleneck-50bb093c3137"><em>GPU Architecture and CUDA for LLM Inference</em></a></p><h3>Phase 2 — Memory, Precision, and Inference Fundamentals</h3><p><strong>Part 4 — How Much GPU Memory Does an LLM Really Need?</strong></p><p>Model-weight calculations, runtime overhead, activation buffers, KV cache, and realistic VRAM estimation.</p><p><em>Article link: To be added</em></p><p><strong>Part 5 — FP32, FP16, BF16, INT8, and INT4 Explained Through Experiments</strong></p><p>Numerical precision, quantization, memory savings, performance, accuracy, and hardware support.</p><p><em>Article link: To be added</em></p><p><strong>Part 6 — Prefill, Decode, Attention, and the KV Cache</strong></p><p>Why inference has different execution phases, why KV caching exists, and how context length changes resource requirements.</p><p><em>Article link: To be added</em></p><p><strong>Part 7 — Compute-Bound vs Memory-Bound LLM Inference</strong></p><p>Memory bandwidth, arithmetic intensity, GPU utilization, and the bottlenecks that govern token generation.</p><p><em>Article link: To be added</em></p><h3>Phase 3 — Running and Serving LLMs</h3><p><strong>Part 8 — Running My First LLM with Hugging Face Transformers</strong></p><p>A baseline local inference implementation, its request lifecycle, memory behavior, and performance limitations.</p><p><em>Article link: To be added</em></p><p><strong>Part 9 — Hosting My First LLM with vLLM</strong></p><p>Installing a compatible runtime, loading a model, starting an API server, sending requests, streaming responses, and inspecting GPU activity.</p><p><em>Article link: To be added</em></p><p><strong>Part 10 — Inside vLLM: Scheduling, PagedAttention, and KV-Cache Management</strong></p><p>How vLLM manages requests and GPU memory, and why efficient serving differs from simple single-request inference.</p><p><em>Article link: To be added</em></p><p><strong>Part 11 — Static, Dynamic, and Continuous Batching</strong></p><p>How batching changes GPU utilization, request latency, and total throughput.</p><p><em>Article link: To be added</em></p><h3>Phase 4 — Benchmarking and Performance Engineering</h3><p><strong>Part 12 — How to Benchmark an LLM Inference Server</strong></p><p>Time to first token, inter-token latency, tokens per second, requests per second, latency percentiles, and repeatable experiments.</p><p><em>Article link: To be added</em></p><p><strong>Part 13 — The Cost of Context Length and Concurrent Users</strong></p><p>Controlled context-length and concurrency experiments, KV-cache pressure, scheduling effects, and saturation.</p><p><em>Article link: To be added</em></p><p><strong>Part 14 — Transformers vs vLLM: A Performance Investigation</strong></p><p>Controlled comparisons, measurement methodology, throughput differences, and explanations grounded in observations.</p><p><em>Article link: To be added</em></p><p><strong>Part 15 — Profiling and Optimizing LLM Inference</strong></p><p>GPU profiling, bottleneck identification, batch tuning, prefix caching, prefill optimization, and CUDA kernel behavior.</p><p><em>Article link: To be added</em></p><h3>Phase 5 — Advanced Serving and Production Engineering</h3><p><strong>Part 16 — Running Larger Models on Limited GPU Memory</strong></p><p>Quantization formats, CPU offloading, memory trade-offs, and experiments with models that exceed native FP16 capacity.</p><p><em>Article link: To be added</em></p><p><strong>Part 17 — Multi-GPU LLM Inference: Parallelism and Scaling</strong></p><p>Tensor parallelism, pipeline parallelism, data parallelism, communication costs, and scaling limitations.</p><p><em>Article link: To be added</em></p><p><strong>Part 18 — From a Local LLM Server to Production-Ready Inference</strong></p><p>Serving architecture, APIs, monitoring, logging, concurrency controls, reliability, model versions, security, and capacity planning.</p><p><em>Article link: To be added</em></p><p><strong>Part 19 — Building Applications on Top of My LLM Server</strong></p><p>How RAG, tool calling, MCP, and agent orchestration fit above the inference layer.</p><p><em>Article link: To be added</em></p><h3>What Makes This Series Different?</h3><p>Each completed technical article will contain:</p><ol><li>The engineering problem being investigated</li><li>The necessary concepts and architecture</li><li>A prediction or hypothesis</li><li>A reproducible experiment</li><li>Commands and configurations</li><li>Measured results</li><li>Unexpected observations</li><li>An explanation of the results</li><li>Practical engineering lessons</li><li>Recommendations and trade-offs</li></ol><p>Some related parts may be combined as the experiments progress. The aim is to publish substantial engineering articles rather than short notes after every lesson.</p><h3>The Final Goal</h3><p>By the end of this series, I want to be able to evaluate a GPU machine, select a suitable model, estimate its memory requirements, deploy an inference server, benchmark its performance, diagnose bottlenecks, and explain the complete execution stack.</p><p>Most importantly, I want the conclusions to come from experiments rather than assumptions.</p><p><em>This index will be updated as new articles and experimental results are published.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=668242d808a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lesson 6: Read-Only vs Read-Write Root Filesystems in Embedded Linux]]></title>
            <link>https://medium.com/@ankushwork21/lesson-6-read-only-vs-read-write-root-filesystems-in-embedded-linux-f8d9510608ba?source=rss-6027130df4cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8d9510608ba</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[yoctoproject]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <dc:creator><![CDATA[Ankush Dhanda]]></dc:creator>
            <pubDate>Sun, 18 Oct 2026 14:33:09 GMT</pubDate>
            <atom:updated>2026-10-18T14:33:09.429Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine this scenario — You compile a new version of IDS, connect to your board, and try to replace the existing executable:</p><pre>cp ids-daemon /usr/bin/</pre><p>But Linux responds:</p><pre>cp: cannot create regular file<br>&#39;/usr/bin/ids-daemon&#39;:<br>Read-only file system</pre><p>Why?</p><p>You are logged in as root. You have administrative privileges. Yet Linux refuses to modify the file.</p><p>Meanwhile, IDS is still writing logs successfully.</p><p>How can Linux prevent you from modifying /usr/bin but allow your application to create log files?</p><p>That’s exactly what we’ll understand today.</p><h4>What we’ll learn</h4><ol><li>What ro and rw actually mean.</li><li>How different directories can have different write permissions.</li><li>How read-only systems store logs and persistent data.</li><li>What OverlayFS is and how it works.</li><li>How development builds differ from production builds.</li><li>How Yocto creates read-only root filesystems.</li><li>How to safely investigate your physical Qualcomm board.</li></ol><h4><strong>Part 1: What is a read-only root filesystem?</strong></h4><h4>6.1 First, remember what a root filesystem is</h4><p>In Lesson 1, we discussed the Linux filesystem hierarchy:</p><pre>/<br>├── bin/<br>├── etc/<br>├── lib/<br>├── usr/<br>│   ├── bin/<br>│   └── lib/<br>├── var/<br>├── tmp/<br>├── dev/<br>├── proc/<br>└── sys/</pre><p>The / directory is the starting point of the Linux filesystem hierarchy.</p><p>Your IDS application might be installed at:</p><pre>/usr/bin/ids-daemon</pre><p>Its configuration might be:</p><pre>/etc/ids/config.json</pre><p>And its logs might be:</p><pre>/var/log/ids.log</pre><p>Although these paths appear to belong to one directory tree, they do not necessarily live on the same physical partition or filesystem.</p><p>That distinction is very important.</p><h4>6.2 Read-only (RO) vs read-write (RW)</h4><p>Think of two different types of notebooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*UCc2kAZRqvumzZDedV_MUw.png" /></figure><p>In Linux, filesystem mount options control whether writes are allowed.</p><p>For example, this is an illustrative entry from /proc/mounts:</p><pre>/dev/mmcblk0p3 / ext4 ro,relatime 0 0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*CVr7BCXDE_pRwWw2WMN1uQ.png" /></figure><p>Now compare:</p><pre>/dev/mmcblk0p3 / ext4 rw,relatime 0 0</pre><p>Here rw means that the filesystem is mounted read-write.</p><p><strong>Important: RW does not mean everyone can modify everything</strong></p><p>Even if the filesystem is mounted rw, a normal user may not have permission to modify /usr/bin.</p><p>So two different mechanisms can prevent a write:</p><ul><li>Filesystem mounted read-only: even root generally cannot write through that mount.</li><li>File permissions: the filesystem is writable, but a particular user lacks permission.</li></ul><p>Also, read-only mounting and cryptographically verified images are different concepts. A read-only mount alone does not guarantee that nobody can change the underlying flash using privileged or offline tools.</p><h4>6.3 Why do production devices use RO?</h4><p>Consider a vehicle telematics unit.</p><p>It needs to run reliably for years, and users shouldn’t be able to accidentally damage core system files.</p><p>A read-only system partition helps because it reduces unintended filesystem changes, limits some forms of persistent modification, and supports predictable system-image updates.</p><p>It can also reduce routine writes to flash.</p><p>However, a read-only root filesystem is not sufficient by itself to guarantee security, integrity, or recovery from power failures. Those goals may require additional mechanisms such as verified boot, flash integrity checking, and robust update design.</p><h4>Part 2: How can a read-only Linux system write logs?</h4><p>Here’s the key idea:</p><p>A read-only root filesystem does not imply that every mounted filesystem is read-only.</p><p>Linux can combine several mounted filesystems into one directory hierarchy.</p><h4>6.4 One Linux filesystem tree, multiple storage areas</h4><p>Imagine your board has persistent flash divided into two main regions:</p><ul><li>rootfs — Contains the installed Linux system.</li><li>userdata — Stores information that changes while the device runs.</li></ul><p>The device could mount them like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*WnVPcT4uvujbk6WBJnpMiA.png" /></figure><p>For example, a hypothetical board could report:</p><pre>/dev/mmcblk0p3  /         ext4   ro<br>/dev/mmcblk0p4  /data     ext4   rw<br>tmpfs           /tmp      tmpfs  rw<br>tmpfs           /run      tmpfs  rw</pre><p>Although / is read-only, /data and /tmp can still accept writes.</p><p>Why? Because they are different mounted filesystems.</p><p>The kernel decides where to route a file operation based on the path and mount hierarchy.</p><h4>6.5 What exactly is tmpfs?</h4><p>tmpfs is a temporary filesystem whose contents are held in memory, with possible swap backing on systems that support it.</p><p>In an embedded system, /tmp and /run are often backed by tmpfs.</p><p>For example:</p><pre>echo &quot;IDS started&quot; &gt; /tmp/ids-test.log</pre><p>On a system where /tmp is writable, this succeeds even when / is read-only.</p><p>But what happens after reboot?</p><p>The contents of tmpfs are lost.</p><p>So we should distinguish:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*SePtef_v0s9vbSNZ_9J-Pg.png" /></figure><p>The distinction matters especially for logs.</p><p>Suppose IDS detects suspicious activity and writes important diagnostic information.</p><p>If the logs are stored only in tmpfs, a power loss could erase them.</p><p>For critical diagnostic data, the product may need persistent logging, remote log collection, or another suitable design.</p><h4>6.6 Why /var/log can be confusing</h4><p>You might see:</p><pre>/var/log/ids.log</pre><p>and assume it must be stored on the same flash partition as /.</p><p>But /var/log could be:</p><ul><li>A separate writable mount.</li><li>A symbolic link to /data/logs.</li><li>Backed by tmpfs.</li><li>Part of a writable overlay.</li></ul><p>Therefore, the directory name alone doesn’t tell you where the data is physically stored.</p><p>On your board, inspect the mount configuration rather than guessing from the path.</p><h4>Part 3: OverlayFS — Making a read-only system appear writable</h4><p>This is an interesting mechanism used in many embedded Linux systems.</p><h4>6.7 The problem OverlayFS solves</h4><p>Imagine your product uses a read-only root filesystem.</p><p>You want to keep the original system files protected, but developers still need to change configuration files or test some modifications.</p><p>How can you allow changes without rewriting the underlying rootfs?</p><p>One approach is OverlayFS.</p><p>Think of a textbook covered by a transparent sheet.</p><p>The textbook is the original, unmodified content.</p><p>You can write notes on the transparent sheet without changing the book itself.</p><p>When you look through the sheet, you see the original content plus your changes.</p><p>That’s the basic idea behind OverlayFS.</p><h4>6.8 How OverlayFS works</h4><p>OverlayFS combines two directory trees:</p><ul><li>Lower layer: Original files, often read-only.</li><li>Upper layer: Writable location for changes.</li></ul><p>Linux presents a merged view to applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*fTkFK75cCgZgCK3sgL8ZTA.png" /></figure><p>The application sees mode = B, because the upper layer takes priority over the lower layer.</p><p>But the original config.json in the lower layer remains unchanged.</p><p>When an existing lower-layer file needs modification, OverlayFS typically copies it to the upper layer and modifies that copy. This is called copy-up.</p><h4>6.9 What happens when you reboot?</h4><p>This depends on where the upper layer is stored.</p><p><strong><em>Upper layer in RAM:</em></strong>Changes are temporary. They disappear after reboot, and the original files are visible again.</p><p><strong><em>Upper layer in persistent flash:</em></strong>Changes can survive reboot, provided the filesystem is properly configured and mounted again.</p><p>Now imagine you’ve copied an updated IDS binary to an OverlayFS-backed /usr/bin.</p><p>It appears to work.</p><p>But if that overlay uses a temporary upper layer, your change disappears after reboot.</p><p>This is one reason you must understand the mount layout before trusting that a manual update is permanent.</p><h4>Does OverlayFS always mean the complete rootfs is writable?</h4><p>No.</p><p>OverlayFS can be mounted over a specific directory such as /etc or an application directory.</p><p>The rest of the root filesystem may remain read-only.</p><p>Also, the merged OverlayFS view may report rw while its underlying lower filesystem is still read-only.</p><h4>Part 4: How Yocto creates read-only images</h4><p>Now let’s connect everything back to Yocto.</p><h4>6.10 Read-only is a system design choice</h4><p>Remember that Yocto builds the root filesystem.</p><p>During image creation, it installs the selected packages, binaries, configurations, and services.</p><p>You can configure the Yocto image to support a read-only root filesystem.</p><p>For example, an image recipe can contain:</p><pre>IMAGE_FEATURES += &quot;read-only-rootfs&quot;</pre><p>This enables Yocto’s read-only-rootfs image feature.</p><p>Yocto also checks that required package post-installation steps can be completed during image creation rather than depending on writes to the read-only rootfs during the board’s first boot.</p><p>This is a build configuration example, not a command to run on your Qualcomm board.</p><p>Enabling the feature doesn’t automatically make every application compatible with a read-only system.</p><h4>6.11 What changes when an image becomes RO?</h4><p>Suppose your IDS application contains this code:</p><pre>#include &lt;fstream&gt;<br>int main() {<br>    std::ofstream log(&quot;/var/log/ids.log&quot;);<br>    log &lt;&lt; &quot;IDS started\n&quot;;<br>}</pre><p>In a development image, /var/log might be writable.</p><p>So the program works.</p><p>But in a new read-only production image, perhaps /var/log is not backed by writable storage.</p><p>Then the file open fails.</p><p>The application needs to detect and handle that error rather than silently assuming the log was written.</p><p>The correct solution isn’t simply to disable read-only mode.</p><p>Instead, the platform and application teams should agree on writable locations.</p><p>For example:</p><pre>/usr/bin/ids-daemon       Program (RO)<br>/usr/lib/libids.so        Library (RO)<br>/etc/ids/config.json      Default config (RO)</pre><pre>/data/ids/                Persistent IDS data (RW)<br>/run/ids/                 Temporary state (RW)<br>/var/log/ids/             Logs, if writable storage is configured</pre><p>If you want to modify IDS runtime behavior, one approach is to keep the default configuration under /etc but allow user-specific or persistent overrides under /data.</p><p>Yocto’s documentation discusses these runtime write requirements because applications designed for ordinary writable Linux distributions may not work unchanged on an RO rootfs.</p><h4>6.12 Where do filesystem formats fit in?</h4><p>Remember Lesson 1, where we learned about ext4, UBI and UBIFS.</p><p>Here’s how they relate to read-only and read-write behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*sLouAaN3VQvISeuH9QaO2Q.png" /></figure><p>SquashFS and EROFS are specifically designed as read-only filesystem formats.</p><p>A crucial distinction:<strong>A read-only image is not the same thing as read-only flash hardware.</strong></p><p>The physical flash can still support writes even though the Linux filesystem mounted from it is read-only.</p><p>This matters when updating a device. An approved updater or flashing tool may replace an entire RO filesystem image without modifying individual files through the mounted filesystem.</p><h4>6.13 A real-world deployment example</h4><p>Suppose your Qualcomm board uses this conceptual flash layout:</p><pre>eMMC Flash<br>│<br>├── Boot Firmware<br>├── Kernel / Boot Partition<br>├── Rootfs A     (Read-only)<br>├── Rootfs B     (Read-only)<br>└── Userdata     (Read-write)</pre><p>The board currently boots from Rootfs A.</p><p>You want to release a new version of IDS.</p><p>A possible A/B update flow is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*6q-hpuNfizhV5Trvdmv9Zw.png" /></figure><p>If the new system fails health checks, a properly designed A/B updater may roll back to the previous slot.</p><p>Not every Qualcomm board uses this design. It is a common embedded update pattern, not a guarantee about your specific device.</p><p>Notice that we didn’t need to make Rootfs A writable.</p><p>The updater installs a complete replacement into the inactive location.</p><p>This gives us an important distinction between updating the contents of a mounted filesystem and writing a replacement filesystem image into a partition.</p><h4>Part 5: Hands-on investigation of your Qualcomm board</h4><p>Now we’ll examine the actual Linux storage configuration.</p><p>For this exercise, we will only read information. We won’t remount partitions, erase flash, install packages, or restart services.</p><h4>Step 1: Identify your root filesystem</h4><p>On the Qualcomm board:</p><pre>cat /proc/mounts | grep &#39; / &#39;</pre><p>You might see something like:</p><pre>/dev/mmcblk0p3 / ext4 ro,relatime 0 0</pre><p>This tells you that / is an ext4 filesystem mounted read-only.</p><p>Alternatively:</p><pre>ubi0:rootfs / ubifs ro,relatime 0 0</pre><p>Here Linux is using UBIFS, which would suggest a UBI-managed flash volume.</p><p>Or:</p><pre>overlay / overlay rw,relatime,... 0 0</pre><p>This indicates an OverlayFS root view. You would need to investigate the upper and lower layers to understand which parts are genuinely writable and persistent.</p><h4>Step 2: Inspect all mounted filesystems</h4><pre>cat /proc/mounts</pre><p>Look especially for mounts at:</p><pre>/<br>/data<br>/tmp<br>/var<br>/var/log<br>/run</pre><p>If your system provides findmnt, these commands are also useful:</p><pre>findmnt -T /<br>findmnt -T /tmp<br>findmnt -T /var/log</pre><p>findmnt -T helps identify the filesystem responsible for a given path, even when it is not itself a mount point.</p><h4>Step 3: Identify where storage is available</h4><pre>df -h</pre><p>And, if supported:</p><pre>lsblk -f</pre><p>df -h reports filesystem space, while lsblk -f can identify filesystem types on block devices.</p><p>For raw NAND systems, also inspect:</p><pre>cat /proc/mtd</pre><p>The command may fail if no MTD device is exposed.</p><h4>Step 4: Inspect important directories</h4><pre>ls -ld /usr/bin<br>ls -ld /etc<br>ls -ld /tmp<br>ls -ld /var/log<br>ls -ld /data</pre><p>These commands show directory permissions and existence, but they don’t prove the filesystem is writable. Combine them with the mount information.</p><p>Check whether /var/log is a symbolic link:</p><pre>ls -ld /var/log</pre><p>If it points somewhere else, inspect that destination’s mount as well.</p><h4>Lesson 6: Final summary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*NM2b-_ruo9JnbREDMfbvvw.png" /></figure><p>The complete picture so far:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*UjuhxJ-0gKPtoN-kAG_8lw.png" /></figure><p>The most important takeaway is:</p><p><strong>A Linux board can have a protected read-only operating system and still run applications that create writable logs, state files, and persistent data. What matters is the filesystem mounted at each path.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8d9510608ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lesson 5: SDK, Toolchain, Public APIs, and Shared Libraries]]></title>
            <link>https://medium.com/@ankushwork21/lesson-5-sdk-toolchain-public-apis-and-shared-libraries-8066f5837fcd?source=rss-6027130df4cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/8066f5837fcd</guid>
            <category><![CDATA[toolchain]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[yoctoproject]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ankush Dhanda]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 11:21:41 GMT</pubDate>
            <atom:updated>2026-10-17T11:21:41.262Z</atom:updated>
            <content:encoded><![CDATA[<p>How can two different teams develop applications for the same Qualcomm board without sharing all their source code?</p><p>Imagine this situation:</p><ul><li>The LCM team develops a library that provides platform functionality.</li><li>The IDS team needs to call functions from that library.</li><li>Both applications must run on the same Qualcomm Linux board.</li><li>The IDS team doesn’t have the LCM implementation’s source code.</li></ul><p>How can the IDS team compile, link, and run its application?</p><p>That’s exactly where the SDK, toolchain, headers, and shared libraries come into the picture.</p><h3>Part 1: Understanding the toolchain and SDK</h3><h4>5.1 What happens when you compile a C++ program?</h4><p>Let’s start with something familiar.</p><p>You write:</p><pre>#include &lt;iostream&gt;<br>int main() {<br>    std::cout &lt;&lt; &quot;Hello Qualcomm Board!\n&quot;;<br>    return 0;<br>}</pre><p>On a normal Linux laptop, you might compile it using:</p><pre>g++ hello.cpp -o hello</pre><p>The compiler creates an executable for the laptop’s architecture.</p><p>But here’s the problem.</p><p>Your laptop may be x86–64, while your Qualcomm board may use a 32-bit ARM or 64-bit ARM Linux environment.</p><p>The executable produced for your laptop will not normally run on the Qualcomm board.</p><p>That’s why we need cross-compilation.</p><h4>5.2 What is a cross-compiler?</h4><p>A cross-compiler runs on one system but generates software for another system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*OX3e5OysDI9jB5AX3cCgsA.png" /></figure><p>The compiler must match your board’s userspace ABI, not just the processor family.</p><h4>5.3 What is a toolchain?</h4><p>A toolchain is a collection of tools required to turn source code into a working program.</p><p>Think of a carpenter’s toolbox. A hammer alone isn’t enough to build furniture.</p><p>Similarly, a compiler alone isn’t the complete software-building environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*LA5Zuqt4O94Cd2nfTEIvsQ.png" /></figure><p>The cross-toolchain targets the architecture and ABI expected by your device.</p><h4>5.4 What is an SDK?</h4><p>SDK stands for Software Development Kit.</p><p>An SDK is a prepared development environment for building software for a particular platform.</p><p>A Yocto-generated SDK typically contains:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*_a2YdCl9rnw8u3SNJssAKA.png" /></figure><p>Three pieces are particularly important:</p><ol><li>Cross-toolchain: Builds executables for your target.</li><li>Target sysroot: Provides the target’s development headers and libraries.</li><li>Environment setup script: Configures the compiler and paths used during development.</li></ol><p>A sysroot is like a miniature view of the target Linux development environment, stored on the build machine.</p><p>It’s not a complete running copy of your board. It contains the files needed by the compiler and linker.</p><p>This is also the structure described in Yocto’s official SDK documentation.</p><h4>5.5 Why can’t we just use the laptop’s libraries?</h4><p>Suppose IDS depends on OpenSSL.</p><p>Your laptop might have one version of libcrypto, while the board has another.</p><p>They may differ in:</p><ul><li>CPU architecture.</li><li>Library version and exported functions.</li><li>C library implementation.</li><li>Binary compatibility rules, called the ABI.</li></ul><p>If you compile with the wrong headers or link against incompatible libraries, your program may fail at build time or runtime.</p><p>The SDK helps align the software you build with the Linux system you intend to run it on.</p><p>An SDK should ideally come from the same platform build or release as your target image.</p><h3>Part 2: Public APIs, headers, and shared libraries</h3><p>This is where things become particularly relevant to LCM and IDS.</p><h4>5.6 What is a public API?</h4><p>Imagine the LCM team provides this functionality:</p><pre>bool isPlatformReady();</pre><p>The IDS team needs to know whether the platform is ready before starting event processing.</p><p>But IDS shouldn’t need to understand LCM’s internal implementation.</p><p>LCM might internally check processes, IPC connections, configuration, or some other system state.</p><p>The IDS team only needs a clearly defined interface.</p><p>That interface is called a public API.</p><p>Think of an ATM.</p><p>You can use the ATM to withdraw money without knowing the bank’s internal transaction-processing code.</p><p>Similarly, IDS should be able to call a stable platform API without knowing its implementation details.</p><h4>5.7 What is a header file?</h4><p>A header tells the compiler which declarations are available.</p><p>For example, the LCM team provides:</p><p>lcm_api.hpp</p><pre>#pragma once<br>namespace lcm {<br>    bool isPlatformReady();<br>}</pre><p>This header tells the IDS compiler:</p><ul><li>There is a namespace named lcm.</li><li>There is a function named isPlatformReady.</li><li>It returns a bool.</li><li>It takes no arguments.</li></ul><p>But the header doesn’t contain the implementation.</p><p>Now suppose the LCM team implements the function:</p><p>lcm_api.cpp</p><pre>#include &quot;lcm_api.hpp&quot;<br>namespace lcm {<br>bool isPlatformReady() {<br>    return true;<br>}<br>}</pre><p>For now, we’ll return true to keep the example simple.</p><p>The LCM implementation can be compiled into a shared library.</p><h4>5.8 What is a shared library?</h4><p>A shared library is a compiled collection of functions or other code that multiple programs can use.</p><p>On Linux, shared libraries commonly have filenames ending with .so, meaning shared object.</p><p>For example:</p><pre>liblcmapi.so.1</pre><p>The LCM team can distribute:</p><pre>Public development files:<br>    lcm_api.hpp<br>    liblcmapi.so<br>Runtime files:<br>    liblcmapi.so.1<br>    liblcmapi.so.1.0</pre><p>The unversioned .so name is typically used during development for linking. The numbered .so names are commonly used at runtime.</p><p>We will learn more about that distinction shortly.</p><h4>5.9 How does IDS consume the LCM API?</h4><p>Now the IDS team writes:</p><p>ids_demo.cpp</p><pre>#include &lt;iostream&gt;<br>#include &quot;lcm_api.hpp&quot;<br>int main() {<br>    if (lcm::isPlatformReady()) {<br>        std::cout &lt;&lt; &quot;Platform ready. Start IDS.\n&quot;;<br>    } else {<br>        std::cout &lt;&lt; &quot;Platform not ready.\n&quot;;<br>    }    return 0;<br>}</pre><p>Notice something important.</p><p>The IDS source includes the public header, but does not include lcm_api.cpp.</p><p>That’s because IDS can link against the compiled LCM library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*JbVJxfrXUk0d1g9DQpmNTA.png" /></figure><h4>5.10 Important distinction: calling a library vs calling another service</h4><p>Suppose LCM is a separate daemon process.</p><p>Linking liblcmapi.so does not automatically execute code inside that daemon.</p><p>When IDS calls a function in the shared library, that function normally executes inside the IDS process.</p><p>If the function must communicate with the LCM daemon, the library needs to implement a communication mechanism such as a Unix domain socket, D-Bus, or another IPC protocol.</p><p>For example:</p><pre>IDS Process<br>  |<br>  | Calls lcm::isPlatformReady()<br>  v<br>LCM Client Library<br>  |<br>  | Sends IPC request<br>  v<br>LCM Daemon Process<br>  |<br>  | Sends response<br>  v<br>LCM Client Library<br>  |<br>  v<br>IDS receives result</pre><p>This separation is fundamental in embedded Linux.</p><p>The public header defines what IDS can call, the client library implements the client-side behaviour, and the daemon may be responsible for the actual platform functionality.</p><p>Our small C++ example is only a direct shared-library call; it doesn’t implement IPC.</p><h4>5.11 What happens if a header or library is missing?</h4><p>There are three different failure points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*-2lfISnIXgm-m7MqZYh95w.png" /></figure><p>This gives you a powerful debugging technique.</p><p>Before fixing an error, identify which stage failed.</p><p>For example:</p><pre>fatal error: lcm_api.hpp: No such file or directoryThis is a compiler error.</pre><pre>undefined reference to lcm::isPlatformReady()</pre><p>This is typically a linker error.</p><pre>error while loading shared libraries:<br>liblcmapi.so.1: cannot open shared object file</pre><p>This is a runtime loader error.</p><p>Each requires a different investigation.</p><h3>Part 3: Practical C++ example — Build LCM and IDS</h3><p>We’ll first build the example on your Linux development machine, then see how the same source code can be cross-compiled using a Yocto SDK.</p><h4>5.12 Create the project</h4><p>Our project will contain these files:</p><pre>platform-demo/<br>├── include/<br>│   └── lcm_api.hpp<br>├── src/<br>│   ├── lcm_api.cpp<br>│   └── ids_demo.cpp<br>└── build/</pre><p>Use the three C++ files from Part 2.</p><p>Open a terminal in the platform-demo directory.</p><h4>Step 1: Compile the LCM shared library</h4><pre>mkdir -p build<br>g++ -std=c++17 -fPIC -shared \<br>    -Iinclude \<br>    src/lcm_api.cpp \<br>    -Wl,-soname,liblcmapi.so.1 \<br>    -o build/liblcmapi.so.1.0</pre><p>Next, create the library links:</p><pre>cd build<br>ln -s liblcmapi.so.1.0 liblcmapi.so.1<br>ln -s liblcmapi.so.1 liblcmapi.so<br>cd ..</pre><p>Your build directory now contains:</p><pre>build/<br>├── liblcmapi.so<br>│     -&gt; liblcmapi.so.1<br>├── liblcmapi.so.1<br>│     -&gt; liblcmapi.so.1.0<br>└── liblcmapi.so.1.0</pre><p>The actual implementation is stored in liblcmapi.so.1.0.</p><p>The other names are symbolic links.</p><h4>Step 2: Compile IDS using that library</h4><pre>g++ -std=c++17 \<br>    -Iinclude \<br>    src/ids_demo.cpp \<br>    -Lbuild \<br>    -llcmapi \<br>    -o build/ids-demo</pre><p>Here:</p><ul><li>-Iinclude helps the compiler find the public header.</li><li>-Lbuild tells the linker where to look for libraries.</li><li>-llcmapi tells it to link against the library named liblcmapi.so.</li></ul><p>Notice that we did not compile lcm_api.cpp together with IDS.</p><p>The implementation was already compiled into the shared library.</p><h4>Step 3: Run IDS</h4><pre>LD_LIBRARY_PATH=&quot;$PWD/build&quot; ./build/ids-demo</pre><p>Expected output:</p><pre>Platform ready. Start IDS.</pre><p>Why did we set LD_LIBRARY_PATH?</p><p>Because our library lives in a custom development directory rather than a normal system library directory.</p><p>We temporarily told the runtime loader where to find it.</p><p>This is suitable for the local demonstration. Production applications should use the platform’s controlled library installation and loader configuration.</p><h4>Step 4: Inspect the executable</h4><pre>readelf -d build/ids-demo | grep NEEDED</pre><p>You should see a dependency resembling:</p><pre>Shared library: [liblcmapi.so.1]</pre><p>You may also see dependencies on libstdc++, the C runtime, and other libraries.</p><p>This tells you that the executable references shared libraries which must be available in a compatible form at runtime.</p><h4>What did we actually achieve?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*OUfHL56dqdsTsARKU1kLUg.png" /></figure><p>This is the central idea behind a shared-library-based platform API.</p><p>The IDS team needs the public header and suitable linkable library during development. On the target board, IDS needs the compatible runtime library.</p><p>It doesn’t necessarily need the LCM source code.</p><h3>Part 4: How Yocto creates and distributes the SDK</h3><p>Now we’ll connect our example to your Qualcomm project.</p><h4>5.13 Building a Yocto SDK</h4><p>On the Yocto build host, after selecting the correct machine, distro, and image configuration, you can request an SDK:</p><pre>bitbake &lt;your-image-name&gt; -c populate_sdk</pre><p>This generates an SDK installer, normally under:</p><pre>build/tmp/deploy/sdk/</pre><p>The SDK corresponds to the configured image and build environment.</p><p>A platform or CI team can generate the SDK and distribute it to application developers.</p><p>This means the IDS developer does not need to perform a complete Yocto image build every time they change an application.</p><h4>5.14 How does the SDK include LCM public headers?</h4><p>Remember that Yocto builds recipes into packages.</p><p>Suppose the LCM library recipe is named lcm-api.</p><p>Its output may be split into:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*aep-Ivq1Hls5wy9oD3GL6g.png" /></figure><p>Yocto has default packaging rules that separate development files from runtime shared libraries.</p><p>The platform team needs to ensure the recipe actually installs the public header and libraries, then includes the development package in the SDK.</p><p>For example, in an appropriate SDK configuration:</p><pre>TOOLCHAIN_TARGET_TASK:append = &quot; lcm-api-dev&quot;</pre><p>That tells the SDK generation process to include the development package in the target portion of the SDK.</p><p>The TOOLCHAIN_TARGET_TASK variable is one supported way of customizing a standard Yocto SDK.</p><p>Now the SDK can provide files resembling:</p><pre>target-sysroot/<br>└── usr/<br>    ├── include/<br>    │   └── lcm_api.hpp<br>    │<br>    └── lib/<br>        ├── liblcmapi.so<br>        ├── liblcmapi.so.1<br>        └── liblcmapi.so.1.0</pre><p>This is why installing the header as part of a recipe matters. Simply keeping the header in the LCM Git repository does not automatically make it available to other teams.</p><h4>5.15 How does the IDS Yocto recipe declare its dependency?</h4><p>Suppose IDS needs the LCM API.</p><p>A simplified IDS recipe would declare:</p><pre>DEPENDS = &quot;lcm-api&quot;</pre><p>This tells BitBake that the LCM API must be prepared as a build dependency before compiling IDS.</p><p>The required headers and libraries become available through Yocto’s recipe-specific sysroot.</p><p>At runtime, IDS also needs the LCM shared library.</p><p>Yocto can automatically identify and add runtime package dependencies for correctly packaged ELF shared-library references. Non-library runtime requirements, such as a separate daemon or configuration package, may require explicit dependency declarations.</p><p>This gives us an important distinction:</p><p>DEPENDS is about build-time availability. RDEPENDS is about runtime package requirements.</p><h4>5.16 Using the generated SDK outside Yocto</h4><p>Suppose your platform team has installed a matching SDK on your development machine.</p><p>It provides an environment setup script.</p><p>For example:</p><pre>source /opt/platform-sdk/environment-setup-&lt;target&gt;</pre><p>The exact filename will depend on your SDK.</p><p>After sourcing it, inspect the environment:</p><pre>echo &quot;$CXX&quot;<br>echo &quot;$SDKTARGETSYSROOT&quot;</pre><p>CXX identifies the target C++ compiler command, including any configured options.</p><p>SDKTARGETSYSROOT points to the target development sysroot.</p><p>Using our existing C++ example, and assuming its LCM headers and library are available in the SDK, the IDS program can be cross-compiled with:</p><pre>mkdir -p build-target<br>${CXX} ${CXXFLAGS} \<br>    -std=c++17 \<br>    src/ids_demo.cpp \<br>    -llcmapi \<br>    ${LDFLAGS} \<br>    -o build-target/ids-demo</pre><p>This assumes the SDK exposes lcm_api.hpp at a standard include location and the linker can find liblcmapi.so.</p><p>If your SDK places the public API in a custom subdirectory, you may need an additional include path.</p><p>Now inspect the resulting executable on the development machine:</p><pre>file build-target/ids-demo<br>readelf -h build-target/ids-demo<br>readelf -d build-target/ids-demo | grep NEEDED</pre><p>If configured for 32-bit ARM, the executable’s architecture should reflect that target. If configured for AArch64, it should reflect a 64-bit ARM target.</p><p>This demonstrates that you can create an ARM executable on your x86–64 development machine without building or flashing an entire Linux image.</p><h4>5.17 What if the SDK and board versions don’t match?</h4><p>Imagine two platform releases:</p><pre>Platform Release 1<br>    liblcmapi.so.1<br>    lcm_api.hpp version 1<br>Platform Release 2<br>    liblcmapi.so.2<br>    lcm_api.hpp version 2</pre><p>Your IDS application was compiled against release 2, but the Qualcomm board still runs release 1.</p><p>The application may fail because the required library is missing, the ABI changed, or some expected functionality is unavailable.</p><p>The ABI is the Application Binary Interface: the rules that let compiled pieces of software work together.</p><p>A source-level API can look similar across versions while its compiled binary interface differs.</p><p>For C++ libraries, changes to class layout, virtual functions, parameter types, symbol names, or compiler ABI settings can break compatibility.</p><p>That is why production platform teams should version their public APIs and SDKs carefully.</p><p>It is also why changing a shared library often requires more validation than changing one independent executable.</p><h3>Part 5: Practical checks on your Qualcomm board</h3><p>You already have physical hardware, so let’s use it to connect the theory to reality.</p><p>We will perform only read-only inspection.</p><h4>Step 1: Check board architecture</h4><p>On your Qualcomm board:</p><pre>uname -m<br>getconf LONG_BIT</pre><p>Typical results might include armv7l or aarch64, with a 32-bit or 64-bit userspace. These commands are useful clues, although complete ABI compatibility requires more than just these values.</p><h4>Step 2: Identify an executable and its dependencies</h4><p>If you know the path to an IDS executable:</p><pre>file /usr/bin/ids-daemon</pre><p>If readelf is installed:</p><pre>readelf -d /usr/bin/ids-daemon | grep NEEDED</pre><p>This helps identify the dynamic libraries required by the application.</p><h4>Step 3: Inspect the library files</h4><pre>ls -l /usr/lib/liblcm*</pre><p>The library may be stored in a different directory or have a different name. An empty result does not mean the platform provides no LCM API.</p><p>Use a known library path from your board if possible.</p><h4>Step 4: Understand the difference between SDK files and board files</h4><p><strong>Development machine SDK</strong></p><pre>include/<br>  lcm_api.hpp<br>lib/<br>  liblcmapi.so<br>  liblcmapi.so.1</pre><p>Headers and linker inputs used while building software.</p><p><strong>Production target rootfs</strong></p><pre>usr/bin/<br>  ids-daemon<br>usr/lib/<br>  liblcmapi.so.1</pre><p>Runtime files required to execute installed software.</p><p>Production devices often omit development headers, compiler tools, and the unversioned library linker symlink.</p><p>This is normal.</p><p>The board needs to run the application, not necessarily compile it.</p><h4>Part 3–5 recap</h4><p>We’ve now connected the complete development flow:</p><pre>Platform team writes LCM library<br>             |<br>             v<br>     Public header + .so<br>             |<br>             v<br>       Yocto recipes<br>             |<br>             v<br>     Platform SDK generated<br>             |<br>             v<br>      IDS developer gets SDK<br>             |<br>             v<br>   Cross-compiles IDS application<br>             |<br>             v<br>   ARM-compatible IDS executable<br>             |<br>             v<br>     Deploy to Qualcomm board<br>             |<br>             v<br>  Loader finds matching LCM library<br>             |<br>             v</pre><h3><strong>Test yourself — Lesson 5</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*Aaiq37XSNy2XTmbBeA0MAA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8066f5837fcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lesson 4: Full Yocto Builds vs Development Builds]]></title>
            <link>https://medium.com/@ankushwork21/lesson-4-full-yocto-builds-vs-development-builds-3be688d73ece?source=rss-6027130df4cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/3be688d73ece</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[yoctoproject]]></category>
            <category><![CDATA[embedded-linux]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ankush Dhanda]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 17:53:33 GMT</pubDate>
            <atom:updated>2026-10-12T17:53:33.653Z</atom:updated>
            <content:encoded><![CDATA[<p>Understand why engineers don’t rebuild and flash an entire Linux system every time they modify a C++ application.</p><p>We’ll use your physical Qualcomm board and an IDS service as our running example.</p><h3>4.1 Let’s start with a real engineering problem</h3><p>Imagine your Qualcomm board is already running Linux.</p><p>The board has the following software installed:</p><pre>Qualcomm Embedded Linux Board<br>│<br>├── Linux Kernel<br>│<br>├── Root Filesystem<br>│   ├── System Libraries<br>│   ├── Configuration Files<br>│   └── Linux Commands<br>│<br>├── LCM Service<br>│<br>└── IDS Service<br>    ├── ids-daemon<br>    ├── libids.so<br>    └── ids-config.json</pre><p>You discover a bug in ids-daemon.cpp.</p><pre>void processEvent() {<br>    // Old buggy implementation<br>}</pre><p>You fix it:</p><pre>void processEvent() {<br>    // Fixed implementation<br>}</pre><p>Now you want to test your change on the board.</p><p>There are two main approaches:</p><ol><li>Build a new Linux image containing your updated IDS application and flash it.</li><li>Build only the updated application or package and deploy it to the existing Linux system.</li></ol><p>Both approaches are useful, but for different purposes.</p><h3>4.2 Approach 1: Full image build and flashing</h3><p>Think of a full image as preparing an entire operating system installation.</p><p>Your Yocto image contains the selected Linux components, libraries, services, configuration files and applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*6-sVj_ATn8IKkIhWcFkAcw.png" /></figure><h4>What command builds a complete image?</h4><p>On your Yocto build host:</p><pre>bitbake &lt;image-recipe-name&gt;</pre><p>For example, with the generic Yocto image:</p><pre>bitbake core-image-minimal</pre><p>Your Qualcomm project might instead use a custom image recipe such as product-image, but we must identify its actual name rather than assume one.</p><p>BitBake determines the necessary dependencies and builds an image containing the requested packages.</p><p>Important distinction: Building an image does not automatically mean recompiling everything from scratch. If previous build results are valid, BitBake reuses them.</p><h4>What happens after the build?</h4><p>The image and related artifacts are typically found under:</p><pre>build/tmp/deploy/images/&lt;machine&gt;/</pre><p>There might be an ext4 image, UBI image, kernel or boot image, device trees, and vendor-specific flashing artifacts.</p><p>You then use the flashing procedure supported by your board.</p><p>For example:</p><pre>Yocto output: rootfs.ext4<br>          ↓<br>Vendor flashing tool<br>          ↓<br>Board&#39;s eMMC partition<br>          ↓<br>Reboot<br>          ↓<br>Updated root filesystem</pre><p>This is only an example. A raw NAND board may instead use a UBI artifact, and some Qualcomm platforms require multiple signed firmware components.</p><h3>When do we prefer this?</h3><p>A full image build and controlled image deployment are useful when:</p><ul><li>Updating the Linux kernel or boot components.</li><li>Modifying base system libraries.</li><li>Changing rootfs organization or system configuration.</li><li>Testing a complete software release.</li><li>Ensuring the delivered system contains the correct versions of all components.</li></ul><p>A full-image update may not require overwriting every flash partition. A product’s updater might replace only a rootfs partition or an inactive A/B slot.</p><h4>Mini recap</h4><p>A full image represents a prepared Linux system. You build it to validate the complete combination of components, not just your modified application.</p><h3>4.3 Approach 2: Build only IDS and deploy it</h3><p>Now suppose the existing Linux system is fine.</p><p>Only ids-daemon.cpp has changed.</p><p>Why rebuild and flash an operating system when you only need to test one application?</p><p>Instead, you can build the IDS recipe separately.</p><p>On the Yocto build host:</p><pre>bitbake ids-daemon</pre><p>This builds the IDS recipe and whatever prerequisite work is necessary.</p><p>It does not automatically rebuild the final root filesystem image or flash the board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*krxo6kmNRSutAyI8UCigMw.png" /></figure><h4>What files might the build produce?</h4><p>Depending on the recipe, you could have:</p><pre>ids-daemon<br>libids.so.1<br>ids-daemon.service<br>ids-config.json</pre><p>Yocto can also produce an installable package:</p><pre>ids-daemon_1.1_arm.ipk</pre><p>This filename is illustrative; real package names include the target package architecture and version information.</p><p>Common package formats include:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*MhR4d_A3Qdnft2TUf0RpIQ.png" /></figure><p>Your project chooses its package format through Yocto configuration.</p><h4>Binary vs package</h4><p>A binary might be only one executable file:</p><pre>/usr/bin/ids-daemon</pre><p>A package can contain multiple files and metadata:</p><pre>IDS Package<br>│<br>├── /usr/bin/ids-daemon<br>├── /etc/ids/config.json<br>├── /usr/lib/systemd/system/ids-daemon.service<br>└── Package metadata<br>    ├── Version<br>    └── Dependencies</pre><p>A package manager can track versions, installed files, and dependencies. Simply copying a binary does not provide all those benefits.</p><p>In Yocto, recipe building, installation staging, packaging, and final image generation are separate stages.</p><h3>4.4 Why are full Yocto builds slow?</h3><p>Imagine your image requires hundreds of components.</p><p>It might involve compiling a cross-toolchain, system libraries, Linux kernel, utilities, and proprietary software.</p><p>A clean build can take considerable time because it performs a lot of work.</p><p>What makes a build expensive?</p><ol><li>Downloading and preparing source code</li><li>Compiling large C/C++ codebases and the Linux kernel</li><li>Packaging programs, libraries, and their dependencies</li><li>Assembling filesystem and image artifacts</li></ol><p>However, Yocto has an important optimization: shared state cache (sstate).</p><h4>How sstate works</h4><p>Let’s say you successfully built these components yesterday:</p><pre>Linux Kernel     ✓ Built<br>OpenSSL          ✓ Built<br>BusyBox          ✓ Built<br>LCM              ✓ Built<br>IDS              ✓ Built</pre><p>Today you modify IDS.</p><p>BitBake can reuse unaffected task results while rebuilding work whose inputs changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*8iNVUjqHOkYnbpxJ27eU5A.png" /></figure><p>Conceptual illustration, not measured build times. Whether work is reused depends on task inputs, dependencies, and cache validity.</p><p>Yocto uses task signatures to decide whether cached results can be reused. It doesn’t merely compare the names of recipes.</p><p>Another important distinction:</p><p>bitbake &lt;image-name&gt; after a small application change may also be relatively fast, because much of the previous work can be reused. The remaining image assembly and validation work still takes time, which is why developers often use smaller deployment workflows.</p><h3>4.5 The three common ways to test your IDS change</h3><p>This is how I’d think about development on your Qualcomm board.</p><p>Method A: Copy the compiled binary</p><p>Compile ids-daemon, transfer it to a writable development location, and execute it.</p><p>Fast for isolated changes, but you must handle libraries, configuration, permissions, and any running service yourself.</p><p>Method B: Install an application package</p><p>Build an IPK, RPM or DEB package and install it using the target’s compatible package manager.</p><p>Better for tracking files and dependencies, provided package management is available and configured.</p><p>Method C: Use Yocto devtool</p><p>Use Yocto’s development tooling to modify, build and deploy a recipe to a running target.</p><p>Useful for the edit-build-test cycle when the target supports development deployment.</p><h4>Example using devtool</h4><p>Yocto provides a useful development workflow:</p><pre># On the Yocto development host<br>devtool modify ids-daemon</pre><pre># Edit files in the workspace</pre><pre>devtool build ids-daemon</pre><pre># Development board only, after verifying<br># compatibility, SSH and writable target paths:<br>devtool deploy-target ids-daemon root@BOARD_IP</pre><p>The deploy-target command copies the files installed by the recipe onto the target. It bypasses package management and does not automatically install missing runtime dependencies.</p><p>Yocto explicitly recommends this for development, not production deployment.</p><p>You can use devtool undeploy-target to restore previously overwritten files from that development deployment, subject to the target and deployment state.</p><p>Don’t run these deployment commands yet on your Qualcomm device. First, we’ll verify its filesystem mode and whether IDS is safe to stop or update.</p><h3>4.6 What if the new binary doesn’t work?</h3><p>This is where embedded Linux becomes interesting.</p><p>Suppose IDS works on Board A but not on Board B.</p><p>Both boards have the same processor architecture.</p><p>You compile the IDS binary and copy it to both.</p><p>Board A:</p><pre>IDS started successfully</pre><p>Board B:</p><pre>error while loading shared libraries:<br>libids.so.1: cannot open shared object file</pre><p>Why?</p><p>Because compiling your application doesn’t guarantee that every required runtime library is available on the target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*00qiWkqFhTcvAI-oLroflA.png" /></figure><p>If a necessary library is missing or incompatible, the application may fail before entering main().</p><p>There are several other compatibility requirements:</p><ul><li>Correct CPU architecture and ABI.</li><li>Compatible C/C++ runtime libraries.</li><li>Compatible shared-library versions.</li><li>Required configuration files.</li><li>Correct permissions and runtime environment.</li><li>Necessary kernel features, interfaces or drivers.</li></ul><h4>Practical commands to diagnose this</h4><p>On your development machine:</p><pre>file ids-daemon<br>readelf -h ids-daemon<br>readelf -d ids-daemon | grep NEEDED</pre><p>The first command identifies the file type and architecture.</p><p>The second shows ELF information, including its machine type.</p><p>The third shows declared dynamic-library dependencies.</p><p>On the board:</p><pre>uname -m<br>ls /usr/lib<br>cat /proc/mounts</pre><p>You can also inspect the dynamic loader’s error message when launching the application, provided doing so is safe for the device.</p><p>This is why an SDK matched to the target matters. It helps build applications against the intended target headers, libraries and ABI. We’ll cover that in Lesson 5.</p><h3>4.8 Hands-on exercise using your physical board</h3><p>We’ll start entirely with read-only inspection.</p><p>Safe observation exercise</p><p>No flashing, service stopping, package installation, or filesystem changes are required.</p><h4>Step 1: Check the running architecture</h4><p>On the Qualcomm board:</p><pre>uname -m<br>uname -r</pre><p>This tells you the userspace-reported machine architecture and running kernel version.</p><h4>Step 2: Is the rootfs writable?</h4><pre>cat /proc/mounts | grep &#39; / &#39;</pre><p>Example output might contain:</p><pre>/dev/mmcblk0p3 / ext4 ro,relatime 0 0</pre><p>The ro means this mount is read-only.</p><p>Or:</p><pre>/dev/mmcblk0p3 / ext4 rw,relatime 0 0</pre><p>Here rw means this mount is read-write.</p><p>The backing device and filesystem are only examples; your board might show ubifs, overlay, or a different device.</p><p>If the root is an overlay filesystem, the output needs more careful interpretation because the underlying system files may still be read-only.</p><h4>Step 3: Identify the IDS executable and dependencies</h4><p>If IDS is installed:</p><pre>command -v ids-daemon</pre><p>Or search selected conventional directories:</p><pre>ls /usr/bin | grep -i ids<br>ls /usr/lib | grep -i ids</pre><p>If your board uses systemd:</p><pre>systemctl status ids-daemon</pre><p>The unit may have another name, so a service-not-found response doesn’t necessarily mean IDS is absent.</p><h4>Step 4: Check for package-management support</h4><pre>command -v opkg<br>command -v rpm<br>command -v dpkg</pre><p>One or more may be present, or none.</p><p>If there is no package manager, that doesn’t prevent updating the device through an image-update mechanism or a controlled developer deployment method.</p><h4>Step 5: Understand the actual update decision</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*O65nik1cxs2kBCbSFjoKYg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3be688d73ece" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lesson 3: Understanding Yocto — From Source Code to a Linux Image]]></title>
            <link>https://medium.com/@ankushwork21/lesson-3-understanding-yocto-from-source-code-to-a-linux-image-20a0df0bbe92?source=rss-6027130df4cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/20a0df0bbe92</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[yoctoproject]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ankush Dhanda]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 09:36:41 GMT</pubDate>
            <atom:updated>2026-10-12T09:36:41.398Z</atom:updated>
            <content:encoded><![CDATA[<h3>3.1 First, why do we need Yocto?</h3><p>Imagine you’re developing software for your Qualcomm board.</p><p>You need:</p><ul><li>A Linux kernel compatible with the processor and board hardware.</li><li>Basic Linux commands and libraries.</li><li>Your own applications, such as IDS and LCM.</li><li>Configuration files and startup services.</li><li>A root filesystem containing all the necessary software.</li><li>A final image that can be deployed to the board.</li></ul><p>You could theoretically assemble everything yourself.</p><p>You would download Linux, compile it, download each library, compile your applications, arrange the filesystem directories, handle dependencies, and construct the final image.</p><p>But imagine repeating this for every release, every developer, and every board variant.</p><p>It becomes difficult to manage.</p><p>Yocto helps automate and organize that entire build process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*N3_VbwLIjmZzBXNlV4Y4gg.png" /></figure><p>One important correction: Yocto is not itself a Linux distribution, and it isn’t the software running on your board.</p><p>It is a project providing tools, build metadata, and methods for creating customized embedded Linux distributions.</p><p>Your board runs the Linux system produced by the build process, not the Yocto build tools themselves.</p><h3>3.2 Yocto, BitBake, OpenEmbedded and Poky — what’s the difference?</h3><p>You’ll frequently hear these four names together.</p><p>Think of a restaurant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*_sRp4wv_7F5uoeW85PU_pw.png" /></figure><p>BitBake is especially important. It reads the available build instructions, works out which jobs depend on others, and executes the necessary tasks.</p><p>For example, imagine your IDS executable needs libcrypto.</p><p>BitBake can determine that the library must be available when IDS is built, provided the recipe declares the correct dependencies.</p><p>You don’t have to manually compile every prerequisite in the right order.</p><h3>3.3 What are layers?</h3><p>This is one of the most important Yocto concepts.</p><p>A layer is simply a directory containing build instructions, configurations, and related files.</p><p>It helps keep different parts of a project organized.</p><p>Imagine your company has three teams:</p><ul><li>Platform team: Maintains board support and the Linux kernel.</li><li>IDS team: Builds intrusion-detection software.</li><li>LCM team: Builds lifecycle-management software.</li></ul><p>It would be messy if every team edited the same central build configuration for everything.</p><p>Instead, teams can organize their software into separate layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*OP0yFNzo1SNNMN-v6-71bw.png" /></figure><p>The name meta- is a convention you&#39;ll see in many Yocto projects.</p><p><strong>A real Qualcomm example — </strong>Qualcomm maintains an OpenEmbedded/Yocto BSP layer called <a href="https://github.com/qualcomm-linux/meta-qcom">meta-qcom</a>. It provides recipes and hardware-related configuration for supported Qualcomm platforms.</p><p>Qualcomm Linux also has distribution-related layers, such as meta-qcom-distro, in its published Yocto environments.</p><p>Your particular automotive board may use a separate vendor or company BSP. Don’t assume that the publicly available meta-qcom layer supports your exact hardware.</p><h3>So how does Yocto know which layers to use?</h3><p>Through a configuration file named:</p><p>build/conf/bblayers.conf</p><p>A simplified example:</p><pre>BBLAYERS = &quot; \<br>    /work/poky/meta \<br>    /work/meta-qcom \<br>    /work/meta-platform \<br>    /work/meta-ids \<br>    /work/meta-lcm \<br>&quot;</pre><p>These paths are illustrative.</p><p>It tells the build system which layers are enabled. It doesn’t automatically mean every recipe in those layers will be included in the final image.</p><p>That’s the next distinction.</p><h3>3.4 What is a recipe?</h3><p>A recipe is a file that tells BitBake how to build a particular piece of software.</p><p>Recipe filenames usually end in .bb.</p><p>For example:</p><pre>ids-daemon_1.0.bb</pre><p>The typical filename has two parts:</p><ul><li>ids-daemon: The recipe&#39;s software name.</li><li>1.0: Its version.</li></ul><p>Think of a recipe as instructions for preparing a meal.</p><p>A recipe might describe:</p><ol><li>Where to obtain the source code.</li><li>Which libraries are needed during compilation.</li><li>Which compiler/build method to use.</li><li>How to install the finished files into a temporary directory.</li><li>Which packages those installed files should belong to.</li></ol><p>For example, your IDS layer might look like:</p><pre>meta-ids/<br>├── conf/<br>│   └── layer.conf<br>└── recipes-security/<br>    └── ids-daemon/<br>        ├── ids-daemon_1.0.bb<br>        └── files/<br>            ├── ids-daemon.cpp<br>            ├── ids-config.json<br>            └── ids-daemon.service</pre><p>The recipe is responsible for describing how these files are built and prepared for inclusion in packages.</p><h4>Important: recipe vs layer vs image</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*p0dDlNM43GF89EcpmBNThA.png" /></figure><p>A single layer can contain many recipes.</p><p>One recipe can generate multiple packages, such as a runtime package, a development package with headers, and a debugging package.</p><p>An image recipe chooses which packages and features belong in the final Linux image.</p><p>This distinction will help you understand why building IDS alone is different from building the complete operating system.</p><h3>3.5 What does a real Yocto recipe look like?</h3><p>We’ll create a tiny program that prints a message.</p><p>Start with a C example because it has no external library dependencies. The same principles apply to C++ services.</p><p>File 1: ids-demo.c</p><pre>#include &lt;stdio.h&gt;<br>int main(void) {<br>    printf(&quot;IDS demo running on embedded Linux!\n&quot;);<br>    return 0;<br>}</pre><p>Now we want Yocto to compile this for our target board and install it under /usr/bin.</p><p>File 2: ids-demo_1.0.bb</p><pre>SUMMARY = &quot;Simple IDS demonstration&quot;<br>LICENSE = &quot;MIT&quot;<br>LIC_FILES_CHKSUM = &quot;file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302&quot;<br>SRC_URI = &quot;file://ids-demo.c&quot;<br>S = &quot;${UNPACKDIR}&quot;<br>do_compile() {<br>    ${CC} ${CFLAGS} ${LDFLAGS} ids-demo.c -o ids-demo<br>}<br>do_install() {<br>    install -d ${D}${bindir}<br>    install -m 0755 ids-demo ${D}${bindir}<br>}</pre><p>This follows the single-C-file recipe pattern documented by Yocto. The UNPACKDIR approach shown here applies to newer Yocto releases; older projects may use a different source-directory layout.</p><p>Let’s understand it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*KqG4VS2SqtrhHKsa6YXn1w.png" /></figure><p>There is one subtle but important point.</p><p>When do_install() runs, it does not install the application directly onto your Qualcomm board.</p><p>It places files into a temporary destination on the build machine. Yocto then packages those files for use in the image or for separate deployment.</p><p>That’s how a package is created.</p><h3>3.6 How does a package become part of the image?</h3><p>Suppose the recipe has successfully produced an ids-demo package.</p><p>That does not necessarily mean the package is included in your Linux image.</p><p>You must explicitly include it through image configuration or another dependency mechanism.</p><p>For example, during development, you could add this to the build’s conf/local.conf:</p><pre>IMAGE_INSTALL:append = &quot; ids-demo&quot;</pre><p>The leading space inside the quotes is intentional.</p><p>This tells the build system to add the ids-demo package to the image&#39;s installed package set.</p><p>For a maintained product, you would normally express this in a proper image recipe, packagegroup, or product layer rather than leaving it as a developer-only override.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*97tZkltlX4YvcQsi-gaqEg.png" /></figure><p>The resulting image could contain:</p><pre>/<br>├── usr/<br>│   ├── bin/<br>│   │   └── ids-demo<br>│   └── lib/<br>│       └── ...<br>├── etc/<br>├── var/<br>└── ...</pre><p>After that image is flashed and the board boots, you could run:</p><pre>/usr/bin/ids-demo</pre><p>Expected output:</p><pre>IDS demo running on embedded Linux!</pre><p>For the real IDS service, we’d also account for shared libraries, configuration files, runtime dependencies, and a systemd service unit.</p><h3>3.7 What happens internally when BitBake builds software?</h3><p>Let’s say you execute the following on a properly configured Yocto build host:</p><pre>bitbake ids-demo</pre><p>BitBake performs a series of tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*s-bSgkbSaoMFvfXse_LtmA.png" /></figure><p>Some recipes require additional steps, and certain tasks may do very little depending on how the software is built. BitBake also handles dependencies and numerous quality checks along the way.</p><p>Now, notice the difference between these two commands:</p><pre>bitbake ids-demo</pre><p>Builds the application recipe and the work needed for it.</p><pre>bitbake core-image-minimal</pre><p>Builds a minimal Linux image according to the selected machine and distribution configuration.</p><p>core-image-minimal is a generic Yocto example target, not necessarily the image target for your Qualcomm board.</p><p>For your board, we’ll need to identify the image name supplied by its BSP or project.</p><h3>3.8 What does Yocto generate after a build?</h3><p>You might have seen a large directory called tmp inside a Yocto workspace.</p><p>A typical build output structure looks something like:</p><pre>build/<br>├── conf/<br>│   ├── local.conf<br>│   └── bblayers.conf<br>│<br>├── downloads/<br>│<br>├── sstate-cache/<br>│<br>└── tmp/<br>    ├── work/<br>    │   └── ...<br>    │<br>    └── deploy/<br>        ├── images/<br>        │   └── &lt;machine&gt;/<br>        │       ├── rootfs.ext4<br>        │       ├── rootfs.tar.gz<br>        │       ├── kernel-image<br>        │       └── ...<br>        │<br>        ├── rpm/<br>        ├── ipk/<br>        ├── deb/<br>        └── sdk/</pre><p>This is illustrative. The actual files depend on your build configuration, and a project may generate only one package format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*gNl_yv1ZAC_hnYChJKGCMA.png" /></figure><h3>Why is sstate-cache important?</h3><p>Imagine your Yocto image contains 500 software components.</p><p>You modify only IDS.</p><p>Should BitBake compile all 500 components again?</p><p>Usually no.</p><p>If cached results are still valid and the dependencies haven’t changed, BitBake can reuse previous work.</p><p>That’s one reason incremental builds can be much faster than a clean build.</p><p>A first-time build may still need to download, compile, and package a large number of components.</p><h3>3.9 Where do the toolchain and SDK fit?</h3><p>Remember our example: your development laptop may have an x86–64 processor, but the Qualcomm board may run ARM.</p><p>A program compiled normally for your laptop is not automatically compatible with that board.</p><p>We need a cross-compiler that runs on the build machine but creates binaries for the target.</p><p>An SDK packages development tools and target-compatible development files so you can build applications outside a full Yocto image build.</p><p>For example:</p><pre>Yocto image build<br>       |<br>       +----&gt; Linux image<br>       |<br>       +----&gt; SDK (when requested)<br>                  |<br>                  +--&gt; Cross-compiler<br>                  +--&gt; Headers<br>                  +--&gt; Target libraries<br>                  +--&gt; Build environment setup</pre><p>Yocto can generate an SDK with a command such as:</p><pre>bitbake &lt;image-name&gt; -c populate_sdk</pre><p>The output normally appears in tmp/deploy/sdk/.</p><p>This is particularly useful for teams building IDS or LCM without running an entire image build for every code change.</p><p>We’ll explore SDKs, public headers, linking, and shared APIs in detail in Lesson 5.</p><h3>3.10 Hands-on with your Qualcomm board</h3><p>For now, we won’t flash or modify anything.</p><p>Our first goal is to understand the environment you already have.</p><p>There are two places you may need to work:</p><p><strong>Build host</strong></p><p>Linux workstation or CI build server where Yocto and BitBake execute.</p><p><strong>Qualcomm board</strong></p><p>The target device running the Linux system produced by the build.</p><h4>Exercise A: Identify the Linux system on your board</h4><p>Connect through SSH or its serial console, then execute:</p><pre>uname -a<br>uname -m<br>cat /etc/os-release<br>cat /proc/cmdline</pre><p>You’ll learn the kernel version, CPU architecture, system identification information, and boot arguments.</p><p>Next:</p><pre>findmnt /<br>df -h<br>cat /proc/mtd</pre><p>These can help identify the root filesystem, available storage, and raw MTD flash devices. Some minimal images lack findmnt, and /proc/mtd may be absent.</p><p>The presence of particular files in /etc/os-release does not, by itself, prove a specific Yocto build was used.</p><h4>Exercise B: Inspect a Yocto environment on your development machine</h4><p>If you have access to the actual Yocto source/build workspace used for your board, initialize its build environment using the project’s documented setup script.</p><p>In a conventional Poky checkout, you might run:</p><pre>source oe-init-build-env</pre><p>Then:</p><pre># Show enabled layers<br>bitbake-layers show-layers</pre><pre># Show available machine configurations<br>bitbake-layers show-machines</pre><pre># Inspect the current machine and distro<br>bitbake -e | grep -E &#39;^(MACHINE|DISTRO)=&#39;</pre><p>These commands are for the Yocto build host, not normally for the board.</p><p>You may discover layers such as meta-qcom, an automotive BSP, and company-specific platform layers.</p><p>Do not change the MACHINE setting merely because another Qualcomm board uses it. It must match your supported hardware configuration.</p><p>If you only have the board and not the company’s Yocto workspace, Exercise A is enough for today.</p><h3>Lesson 3 recap</h3><p>The biggest concept is that Yocto is a build system for producing a complete embedded Linux software environment, rather than an application that runs on the board.</p><ul><li>Layer organizes build configuration and recipes.</li><li>Recipe explains how to build a software component.</li><li>BitBake coordinates tasks and dependencies.</li><li>Package contains built software and associated files.</li><li>Image recipe chooses what belongs in the system image.</li><li>Image artifact is what eventually gets deployed to storage.</li><li>SDK helps developers compile applications for the target.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20a0df0bbe92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lesson 2: How flashing and booting work]]></title>
            <link>https://medium.com/@ankushwork21/lesson-2-how-flashing-and-booting-work-3ec5da905bf6?source=rss-6027130df4cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ec5da905bf6</guid>
            <category><![CDATA[yoctoproject]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ankush Dhanda]]></dc:creator>
            <pubDate>Mon, 12 Oct 2026 04:37:11 GMT</pubDate>
            <atom:updated>2026-10-12T04:37:11.723Z</atom:updated>
            <content:encoded><![CDATA[<p>Now suppose you have received a completely new Qualcomm development board.</p><p>It has a processor, RAM, flash, USB ports, and power supply. But how do you install Linux on it?</p><p>That is where flashing comes in.</p><h3>2.1 First, what is an image?</h3><p>An image is a file containing prepared software or filesystem data in a format intended for a particular purpose.</p><p>Think of buying a laptop with Windows already installed. The manufacturer prepares the operating system and its components before putting them on your machine.</p><p>Embedded systems work similarly.</p><p>A build pipeline might generate files such as:</p><pre>build-output/<br>├── boot.img<br>├── kernel.fit<br>├── board.dtb<br>├── rootfs.ext4<br>├── rootfs.ubi<br>└── flash-manifest.xml</pre><p>These are examples of possible artifacts, not files every Qualcomm board needs. Some platforms combine components, and others produce many more firmware files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*MwQ6-vzjaCTYqtUo4YOaFA.png" /></figure><h3>2.2 How does the board get the image from your laptop?</h3><p>This is a common source of confusion.</p><p>The board doesn’t automatically know where the image is on your laptop.</p><p>The flashing process requires a communication path and software that understands how to transfer and write the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*KMNDAhTzfy0ubRjmVDJlTg.png" /></figure><p>For example, some Qualcomm platforms support Fastboot. Others use Emergency Download Mode (EDL), dedicated flashing utilities, or vendor-specific tooling. Support depends on the exact hardware and firmware.</p><p>A typical workflow looks like this:</p><ol><li>The build finishes and produces flash artifacts.</li><li>An engineer puts the board into the required flashing mode.</li><li>A tool running on the host establishes a connection with the board.</li><li>The tool transfers the required image data.</li><li>Board-side firmware or a programmer writes that data to flash.</li><li>The board is restarted and begins booting from its updated storage.</li></ol><p>What about CI?</p><p>A CI server normally builds and publishes artifacts. A workstation or a connected flashing station then retrieves those artifacts and flashes the board. The board doesn’t directly read a CI server merely because the pipeline built an image.</p><h3>2.3 What happens when the board powers on?</h3><p>This is the most important sequence to understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*jNoP-56fIO6orjWseJAgnQ.png" /></figure><p>Let’s use a simple example.</p><p>Your board has an application-1 service installed at /usr/bin/app1-daemon.</p><p>When you press the power button, the processor does not directly jump to app1-daemon.</p><p>It first performs the boot process. Once Linux is running and the appropriate service manager starts application-1, the program is loaded and executed.</p><p>The device can also have a bootloader that loads the kernel from flash into RAM while leaving the root filesystem on flash. Linux then reads rootfs files as needed.</p><h3>2.4 Full flashing vs updating one application</h3><p>Now imagine your board is already booting Linux correctly. You change only one function in the IDS application.</p><p>Do you need to flash the whole board again?</p><p>Not necessarily.</p><p>Let’s compare.</p><p><strong>Full image flash</strong></p><p>Writes an entire image or the selected full set of firmware/system partitions.</p><p>Useful when changing the kernel, boot components, root filesystem, or testing a release image.</p><p><strong>Application update</strong></p><p>Replaces the selected program, library, or package.</p><p>Useful during development when only the service changes and the running system supports the update.</p><h3>2.5 Read-only vs read-write — a preview</h3><p>Two boards may run the same software but behave differently when you try to modify files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*WYbRDNbWfyWiamyOPP7kJQ.png" /></figure><p>A read-only rootfs does not mean absolutely nothing on the device can be written. Many embedded systems keep separate writable data partitions or use overlays.</p><p>We’ll explore this properly in Lesson 6.</p><h3>2.6 Practical exercise: recognize flashing and image artifacts</h3><p>Before flashing real hardware, start with identification.</p><p>On your build machine, inspect the files:</p><pre>ls -lh<br>file rootfs.ext4<br>sha256sum rootfs.ext4</pre><p>On your target, after it has booted:</p><pre>uname -a<br>cat /proc/cmdline<br>df -h<br>cat /proc/mounts</pre><p>The first group helps identify the artifact being prepared. The second helps inspect the running operating system and mounted filesystems.</p><p>For actual flashing, you must first confirm the board model, storage type, partition mapping, flashing protocol, and recovery method. A generic flash command can erase important boot or calibration data if used against the wrong partition.</p><h3>Lesson 2 recap</h3><p>An image is prepared software or filesystem data. Flashing writes that data to the board’s persistent storage. During boot, the processor runs initial firmware, the bootloader prepares Linux, the kernel starts, the rootfs is mounted, and services run. A small application change often needs only an application update rather than full flashing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ec5da905bf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>