<?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"><channel><title><![CDATA[AI Bytes]]></title><description><![CDATA[AI Bytes]]></description><link>https://ok-vidit.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 28 Nov 2026 00:35:36 GMT</lastBuildDate><atom:link href="https://ok-vidit.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How LLM Inference Works: From Your Prompt to the Next Token]]></title><description><![CDATA[You hit Send. There is a pause. Then an answer starts appearing, a few characters at a time. That small interaction hides two different jobs. A neural…]]></description><link>https://ok-vidit.hashnode.dev/how-llm-inference-works-from-your-prompt-to-the-next-token</link><guid isPermaLink="true">https://ok-vidit.hashnode.dev/how-llm-inference-works-from-your-prompt-to-the-next-token</guid><category><![CDATA[LLM's ]]></category><category><![CDATA[#llmops]]></category><category><![CDATA[inference]]></category><category><![CDATA[inference engine]]></category><dc:creator><![CDATA[Vidit Maheshwari]]></dc:creator><pubDate>Thu, 26 Nov 2026 20:13:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b088eb4bd92c1ad73ac26a9/3c345bb3-7912-4e61-b989-e5e2088a353a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You hit Send. There is a pause. Then an answer starts appearing, a few characters at a time.</p>
<p>That small interaction hides two different jobs. A neural network has to calculate what should come next. A serving system has to make that calculation happen quickly while other people are asking their own questions.</p>
<p>Understanding both explains a lot: why long prompts delay the first token, why long answers keep a GPU busy, and why fitting model weights into memory is only the beginning.</p>
<p>Let's follow one request all the way through.</p>
<blockquote>
<p><strong>Scope:</strong> We'll use a decoder-only, autoregressive transformer with full causal attention as our baseline. Modern models can use grouped-query attention, mixture-of-experts layers, sliding windows, latent attention, or hybrid state-space layers; these change parts of the computation and memory layout. The serving example is vLLM V1, checked against current documentation and source on November 27, 2026.</p>
</blockquote>
<h2>1. What is the model actually generating?</h2>
<p>Suppose the prompt is:</p>
<pre><code class="language-text">The best thing about weekends is
</code></pre>
<p>The model computes scores for possible next <strong>tokens</strong>. A token might represent a word, a word fragment, punctuation, or bytes. A tokenizer converts the prompt into integer token IDs; a chat application also uses a model-specific template to encode message roles and conversation boundaries.</p>
<p>One possible next token might decode to <code>sleeping</code>. Another might decode to <code>spending</code>.</p>
<p>The selected token is appended to the context. The model then predicts the token after that, conditioning on the prompt <strong>and</strong> what it has already generated. This repeats until a stop condition, such as an end-of-sequence token or output limit. Hugging Face's <a href="https://huggingface.co/docs/transformers/main/en/llm_tutorial">text-generation guide</a> describes this autoregressive loop.</p>
<p>During ordinary inference, the model's learned weights stay fixed. There is no backward pass or optimizer update. The changing state is the request: its tokens, cached attention state, and generation settings.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b088eb4bd92c1ad73ac26a9/f75062ad-07ac-4949-b4f5-90166ff8f1b6.png" alt="Token IDs flow through embeddings, transformer layers, and an output head; the selected token returns to the input." style="display:block;margin:0 auto" />

<p><em>Figure 1. A forward pass produces next-token scores. Selecting a token extends the sequence and creates the next iteration.</em></p>
<h2>2. Inside one forward pass</h2>
<p>A token ID first becomes a vector through an embedding lookup. Position information is incorporated according to the model's design. The vectors then pass through a stack of transformer layers.</p>
<p>Two operations do much of the work:</p>
<ul>
<li><strong>Attention</strong> combines information from allowed positions in the context.</li>
<li><strong>A feed-forward network</strong> transforms each position's representation. In a mixture-of-experts model, a router selects experts for this work.</li>
</ul>
<p>Normalization and residual connections also form part of the layer. Exact ordering varies by architecture.</p>
<p>In attention, learned projections create queries, keys, and values. A query is compared with keys to determine how much to weight the corresponding values. A causal mask prevents a position from using future positions. These mechanisms build on the <a href="https://arxiv.org/abs/1706.03762">Transformer paper</a>.</p>
<p>After the final layer, the output head maps a hidden state to vocabulary-sized scores called <strong>logits</strong>. For ordinary continuation, the final processed position supplies the distribution for the next token.</p>
<p><strong>Greedy decoding</strong> picks the highest-scoring token. <strong>Sampling</strong> chooses from a distribution: temperature changes its sharpness, and top-p can restrict selection to a set carrying a chosen cumulative probability. These settings change token selection, rather than retraining the network. See the <a href="https://huggingface.co/docs/transformers/main/en/generation_strategies">generation strategies documentation</a>.</p>
<p>The model produces scores; the decoding policy determines how to turn them into a continuation.</p>
<h2>3. Why there is a pause, then a stream: prefill and decode</h2>
<p>Generation has two computational stages.</p>
<p><strong>Prefill processes the prompt.</strong> All input tokens are already known, so their positions can be processed in parallel within each layer, subject to causal masking. The model still traverses the layer stack in order. The final prompt position's logits let us select the first output token.</p>
<p><strong>Decode extends the sequence.</strong> In the basic cached loop, the newly selected token is fed through the model to obtain the distribution for the following token. Future output tokens are unknown, so this introduces a sequential dependency.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b088eb4bd92c1ad73ac26a9/4e5af6f8-7677-4030-b995-8c24420519d4.png" alt="Prefill processes known prompt tokens and selects the first output; successive decode steps feed each selected token back into the model." style="display:block;margin:0 auto" />

<p><em>Figure 2. Prefill already gives us the first output token. Each subsequent basic decode step processes the latest token to predict the next one.</em></p>
<p>That distinction also affects hardware use. A substantial prefill can keep matrix multiplication units busy. Decode at low batch sizes often spends much of its time moving weights and cached state through GPU memory. Context length, batching, kernels, and hardware can change which bottleneck dominates; “prefill is compute-bound, decode is bandwidth-bound” is a useful tendency, not a universal rule. These trade-offs appear in vLLM's <a href="https://docs.vllm.ai/en/stable/configuration/optimization/">optimization guide</a>.</p>
<h2>4. The KV cache: keep work that is still valid</h2>
<p>Reprocessing the entire growing sequence at every generation step would repeat a great deal of work.</p>
<p>With causal attention, adding a future token does not change the earlier positions' keys and values. We can retain those <strong>K</strong> and <strong>V</strong> tensors separately for every attention layer.</p>
<p>During decode, the model computes the new position's query, key, and value. Its query attends over cached keys plus the new key, and combines the corresponding values. The new key and value join the cache for later steps. This is the <a href="https://huggingface.co/docs/transformers/main/en/cache_explanation">KV-cache mechanism</a>.</p>
<p>The cache saves recomputation. Full attention still has to access the relevant cached history, so longer contexts can increase decode work and memory traffic.</p>
<p>Here is an illustrative memory calculation for a conventional, uncompressed KV cache:</p>
<pre><code class="language-text">KV bytes = 2 × layers × cached tokens × KV heads × head dimension × bytes/value
</code></pre>
<p>The factor of two represents keys and values. Assume 32 layers, 8 KV heads, a head dimension of 128, and two-byte values:</p>
<pre><code class="language-text">Per token:   2 × 32 × 8 × 128 × 2 = 131,072 bytes = 128 KiB
8,192 tokens:                         1 GiB per sequence
32 such sequences:                  32 GiB
</code></pre>
<p>That is cached state alone, before model weights, temporary buffers, and allocation overhead. This is a worked example, not a measurement of a specific deployment. Grouped-query attention uses the number of <strong>KV heads</strong>, which can be smaller than the query-head count; latent and hybrid architectures need different accounting.</p>
<h2>5. PagedAttention: give a growing cache room to grow</h2>
<p>A serving engine cannot know exactly how long every answer will be. Reserving each request's maximum possible cache size wastes memory. Requiring one contiguous allocation also makes it harder to use free space efficiently.</p>
<p>PagedAttention divides the cache into fixed-size blocks. A request has a logical sequence of blocks, while a block table maps them to physical locations in GPU memory. Those locations need not be adjacent. Attention kernels use the mapping to access the correct state. This is the idea introduced in the <a href="https://arxiv.org/abs/2309.06180">PagedAttention paper</a>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b088eb4bd92c1ad73ac26a9/bf1f93e2-6e5c-4807-bf02-56ed440f6910.png" alt="A request's logical KV blocks map to scattered physical GPU blocks through a block table." style="display:block;margin:0 auto" />

<p><em>Figure 3. Four-token blocks are used only to make this example readable. Actual block sizes depend on the engine and backend.</em></p>
<p>Paging improves allocation and sharing; it does not change what causal attention means. The partially filled final block can still have unused slots.</p>
<p><strong>FlashAttention addresses a different problem.</strong> It organizes attention computation in tiles to reduce expensive reads and writes between GPU high-bandwidth memory and on-chip memory. It avoids materializing the full attention-score matrix in HBM. Paging concerns cache placement; FlashAttention concerns efficient attention computation. See the <a href="https://arxiv.org/abs/2205.14135">FlashAttention paper</a>.</p>
<h2>6. The GPU serves a changing crowd</h2>
<p>Imagine three requests arriving together. A needs two decode steps, B needs four, and C needs three.</p>
<p>If their batch membership stays fixed until everyone finishes, A's completion leaves capacity that a new request D cannot immediately use.</p>
<p><strong>Continuous batching</strong> revisits membership at iteration boundaries. Completed requests leave, and waiting requests can enter as token and memory budgets permit. This builds on iteration-level scheduling, described in <a href="https://www.usenix.org/conference/osdi22/presentation/yu">Orca</a>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b088eb4bd92c1ad73ac26a9/cc40e499-21ca-4d02-a54f-3f568559c054.png" alt="A changing batch replaces completed requests with newly admitted work at each iteration boundary." style="display:block;margin:0 auto" />

<p><em>Figure 4. A simplified decode schedule. D has already completed prefill when admitted here; real engines also schedule prompt work.</em></p>
<p>The interesting scheduling unit becomes the work for the next iteration, rather than a whole conversation.</p>
<p>Long prompts complicate this. A large prefill can hold up requests that are already streaming. <strong>Chunked prefill</strong> splits prompt processing across iterations so the scheduler can mix it with decode work. Chunk size and token budget trade prompt-processing speed against responsiveness for existing requests. It does not shorten the prompt or remove its dependencies. See vLLM's <a href="https://docs.vllm.ai/en/stable/configuration/optimization/#chunked-prefill">chunked-prefill discussion</a>.</p>
<h2>7. Where this lives in a current inference server</h2>
<p>Let's put the pieces into a serving architecture.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b088eb4bd92c1ad73ac26a9/c13d2916-b671-40ee-b430-72777c87fb7e.png" alt="The API frontend sends requests to an engine core, which schedules GPU workers and manages KV allocations; results stream back to the client." style="display:block;margin:0 auto" />

<p><em>Figure 5. A simplified vLLM V1 deployment with one engine core. Each worker owns the weights or weight shard and KV tensors on its GPU.</em></p>
<p>The <strong>API frontend</strong> handles HTTP requests, input preparation, and response streaming. The <strong>engine core</strong> coordinates scheduling and cache allocation. <strong>GPU workers</strong> execute the model using their local weights, buffers, and KV tensors.</p>
<p>For a typical four-GPU tensor-parallel deployment, current vLLM documentation describes one API server, one engine core, and four GPU worker processes.</p>
<p>The V1 scheduler assigns a token budget across requests. Prefill and decode remain useful computational concepts, but the scheduler handles them through a unified account of tokens needing computation. With asynchronous scheduling, CPU scheduling can overlap GPU execution. See the <a href="https://docs.vllm.ai/en/stable/design/arch_overview/">current architecture overview</a>.</p>
<p>Here is a conceptual version of the loop:</p>
<pre><code class="language-python"># Teaching pseudocode: omits distributed and asynchronous details.
while engine_has_work():
    accept_arrivals_and_cancellations()
    batch = schedule_with_token_and_cache_budgets()
    result = execute_model_and_select_tokens(batch)
    update_requests_and_stream_ready_text(result)
    release_unreferenced_resources_for_finished_requests()
</code></pre>
<p>I also checked the <a href="https://github.com/vllm-project/vllm/blob/aae69ee9c3f498e765d61195874bd1a0e24f78cd/vllm/v1/engine/core.py">engine core</a> and <a href="https://github.com/vllm-project/vllm/blob/aae69ee9c3f498e765d61195874bd1a0e24f78cd/vllm/v1/core/sched/scheduler.py">scheduler</a> at commit <code>aae69ee9c3f4</code> for this walkthrough. The simplified loop follows their schedule, execute, sample, and update responsibilities; it is not a literal implementation.</p>
<h2>8. Three ways to avoid paying the same cost</h2>
<h3>Reuse a shared prefix</h3>
<p>Suppose every request begins with the same long system instruction and reference document. <strong>Prefix caching</strong> can reuse compatible cached KV state for that exact prefix, avoiding repeated prefill computation.</p>
<p>It caches intermediate computation, not a previously written answer. The new suffix still needs processing, and generating the answer still requires decode. Reuse depends on matching tokens, compatible model/cache settings, and the cache still being available. Moving variable content before otherwise shared text can reduce the reusable prefix. See <a href="https://docs.vllm.ai/en/stable/features/automatic_prefix_caching/">automatic prefix caching</a>.</p>
<h3>Propose several tokens, then verify</h3>
<p><strong>Speculative decoding</strong> uses a cheaper mechanism to propose a continuation. The target model verifies multiple proposed positions together. Correct verification can accept several tokens per target-model pass; a rejection discards the dependent proposed suffix.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b088eb4bd92c1ad73ac26a9/9ba35fec-87e8-47a3-a3cc-8036f25c5699.png" alt="A drafter proposes four tokens; target verification accepts the first two and replaces the rejected third, discarding the dependent fourth." style="display:block;margin:0 auto" />

<p><em>Figure 6. Proposal and verification preserve the causal dependency while potentially reducing expensive target-model iterations.</em></p>
<p>The exact algorithm includes acceptance and correction sampling that preserve the target distribution. Simply keeping tokens that look plausible does not provide that guarantee. The <a href="https://arxiv.org/abs/2211.17192">original speculative-decoding paper</a> explains why the corrected algorithm works.</p>
<p>Current vLLM documentation lists methods including separate draft models, EAGLE, multi-token prediction, and n-gram proposals. Speedups depend on acceptance rate and verification overhead. Exact methods preserve the target distribution; explicitly lossy verification options require different expectations. See the <a href="https://docs.vllm.ai/en/stable/features/speculative_decoding/">current feature documentation</a>.</p>
<h3>Reduce the bytes moved</h3>
<p>Lower-precision weights can reduce model memory and bandwidth needs. Quantizing the KV cache targets a different, context-dependent allocation. Neither guarantees a proportional speedup: kernels, conversion overhead, hardware support, and acceptable quality loss matter. Weight precision and cache precision are separate choices; evaluate each against the workload. Hugging Face's <a href="https://huggingface.co/docs/transformers/main/en/llm_tutorial">generation guide</a> includes a weight-quantization example.</p>
<h2>9. What happens when one GPU is not enough?</h2>
<p>Different forms of parallelism solve different capacity problems:</p>
<table>
<thead>
<tr>
<th>Approach</th>
<th>What is distributed?</th>
<th>Main cost to watch</th>
</tr>
</thead>
<tbody><tr>
<td>Tensor parallelism</td>
<td>Tensor operations within layers</td>
<td>Frequent communication between GPUs</td>
</tr>
<tr>
<td>Pipeline parallelism</td>
<td>Groups of layers</td>
<td>Transfers between stages and pipeline idle time</td>
</tr>
<tr>
<td>Data parallelism</td>
<td>Model replicas serving different requests</td>
<td>Another copy of weights and cache capacity</td>
</tr>
<tr>
<td>Expert parallelism</td>
<td>Experts in mixture-of-experts layers</td>
<td>Routing and exchanging token activations</td>
</tr>
</tbody></table>
<p>A replica can itself span several GPUs. Adding replicas raises serving capacity; splitting one model helps it fit and can change its execution speed. The interconnect and request mix determine useful combinations. See vLLM's <a href="https://docs.vllm.ai/en/stable/serving/parallelism_scaling/">parallelism and scaling guide</a>.</p>
<p>Another option is <strong>prefill/decode disaggregation</strong>: run those stages in separate instances and transfer the resulting KV state between them. This allows separate capacity and latency tuning, but introduces transfer and coordination costs. It is an architectural trade-off, not an automatic throughput improvement. vLLM currently documents it as <a href="https://docs.vllm.ai/en/stable/features/disagg_prefill/">experimental</a>.</p>
<h2>10. Measure what the person waiting actually feels</h2>
<p>“Tokens per second” can hide very different experiences.</p>
<table>
<thead>
<tr>
<th>Metric</th>
<th>What it tells you</th>
</tr>
</thead>
<tbody><tr>
<td>Time to first token, TTFT</td>
<td>How long the user waits for output to begin</td>
</tr>
<tr>
<td>Inter-token latency, ITL</td>
<td>Gaps between successive output tokens</td>
</tr>
<tr>
<td>End-to-end latency</td>
<td>Time from submitting the request to receiving the final output</td>
</tr>
<tr>
<td>Output throughput</td>
<td>Generated output tokens per second across a stated workload</td>
</tr>
</tbody></table>
<p>For an illustrative response of 101 output tokens, a 0.6-second TTFT followed by 100 intervals averaging 20 milliseconds gives:</p>
<pre><code class="language-text">End-to-end time = 0.6 + (100 × 0.020) = 2.6 seconds
</code></pre>
<p>This arithmetic assumes the average interval and excludes any additional finalization delay. It is not a benchmark result.</p>
<p>Measure under realistic arrival rates, input lengths, and output lengths. Report tail latency as well as averages. A system can look efficient in aggregate while some requests wait too long. vLLM exposes <a href="https://docs.vllm.ai/en/stable/usage/metrics/">production metrics</a> for observing these behaviors.</p>
<p>When an answer feels slow, start by identifying the wait: before the first token, between tokens, or because the system is busy. Those point toward different investigations—queueing and prompt work, decode execution, or serving capacity.</p>
<h2>Follow one token through the whole system</h2>
<p>The next time a response streams onto your screen, picture its path.</p>
<p>The frontend has formatted and tokenized the conversation. A scheduler has found compute and cache capacity for it. Prefill has processed the prompt and produced the first selection. Each decode iteration is extending cached state and choosing what follows. Alongside your request, other requests are entering, finishing, and competing for the same hardware.</p>
<p>That is why understanding inference requires both the model's forward pass and the system that keeps it running.</p>
<hr />
]]></content:encoded></item></channel></rss>