<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"><title>Senthilkumar Gopal - LLM-Inference</title><link href="https://sengopal.me/" rel="alternate"/><link href="https://sengopal.me/feeds/llm-inference.atom.xml" rel="self"/><id>https://sengopal.me/</id><updated>2025-01-20T00:00:00-08:00</updated><subtitle>Musings of a machine learning researcher, engineer and leader</subtitle><entry><title>Segment Sums and Segmented Softmax</title><link href="https://sengopal.me/posts/segment-sums-and-segmented-softmax" rel="alternate"/><published>2025-01-20T00:00:00-08:00</published><updated>2025-01-20T00:00:00-08:00</updated><author><name>Senthilkumar Gopal</name></author><id>tag:sengopal.me,2025-01-20:/posts/segment-sums-and-segmented-softmax</id><summary type="html">Segment sums reduce the rows of a tensor by group label. A segmented softmax built from them normalizes the scores of many packed sequences at once, and the way it is written decides whether a compiled graph grows with the number of sequences.</summary><content type="html">&lt;p&gt;A segment sum adds up the rows of a tensor that share a label. Its
inputs are a data tensor and a vector of segment IDs, one per row, and
row &lt;code&gt;s&lt;/code&gt; of the output is the sum of the data rows whose ID is
&lt;code&gt;s&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;out[s] = sum of data[i] for every i where segment_ids[i] == s&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The same pattern works with other reductions, such as max, min and
mean. Frameworks expose it under different names. TensorFlow has &lt;a href="https://www.tensorflow.org/api_docs/python/tf/math/unsorted_segment_sum"&gt;&lt;code&gt;tf.math.unsorted_segment_sum&lt;/code&gt;&lt;/a&gt;,
JAX has &lt;a href="https://docs.jax.dev/en/latest/_autosummary/jax.ops.segment_sum.html"&gt;&lt;code&gt;jax.ops.segment_sum&lt;/code&gt;&lt;/a&gt;,
and PyTorch has &lt;a href="https://docs.pytorch.org/docs/main/generated/torch.Tensor.index_add_.html"&gt;&lt;code&gt;index_add_&lt;/code&gt;&lt;/a&gt;
and &lt;a href="https://docs.pytorch.org/docs/main/generated/torch.Tensor.scatter_reduce_.html"&gt;&lt;code&gt;scatter_reduce_&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;h2 id="a-small-example"&gt;A small example&lt;/h2&gt;
&lt;p&gt;Six values in three segments:&lt;/p&gt;
&lt;div class="sourceCode" id="cb2"&gt;&lt;pre class="sourceCode python"&gt;&lt;code class="sourceCode python"&gt;&lt;span id="cb2-1"&gt;&lt;a aria-hidden="true" href="#cb2-1" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="im"&gt;import&lt;/span&gt; torch&lt;/span&gt;
&lt;span id="cb2-2"&gt;&lt;a aria-hidden="true" href="#cb2-2" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb2-3"&gt;&lt;a aria-hidden="true" href="#cb2-3" tabindex="-1"&gt;&lt;/a&gt;data &lt;span class="op"&gt;=&lt;/span&gt; torch.tensor([&lt;span class="fl"&gt;1.&lt;/span&gt;, &lt;span class="fl"&gt;2.&lt;/span&gt;, &lt;span class="fl"&gt;3.&lt;/span&gt;, &lt;span class="fl"&gt;4.&lt;/span&gt;, &lt;span class="fl"&gt;5.&lt;/span&gt;, &lt;span class="fl"&gt;6.&lt;/span&gt;])&lt;/span&gt;
&lt;span id="cb2-4"&gt;&lt;a aria-hidden="true" href="#cb2-4" tabindex="-1"&gt;&lt;/a&gt;ids &lt;span class="op"&gt;=&lt;/span&gt; torch.tensor([&lt;span class="dv"&gt;0&lt;/span&gt;, &lt;span class="dv"&gt;0&lt;/span&gt;, &lt;span class="dv"&gt;1&lt;/span&gt;, &lt;span class="dv"&gt;1&lt;/span&gt;, &lt;span class="dv"&gt;1&lt;/span&gt;, &lt;span class="dv"&gt;2&lt;/span&gt;])&lt;/span&gt;
&lt;span id="cb2-5"&gt;&lt;a aria-hidden="true" href="#cb2-5" tabindex="-1"&gt;&lt;/a&gt;torch.zeros(&lt;span class="dv"&gt;3&lt;/span&gt;).index_add_(&lt;span class="dv"&gt;0&lt;/span&gt;, ids, data)&lt;/span&gt;
&lt;span id="cb2-6"&gt;&lt;a aria-hidden="true" href="#cb2-6" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;# tensor([ 3., 12.,  6.])&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The segment IDs label rows, so a 2D input needs one ID per row, not
one per element. Each row is reduced as a whole:&lt;/p&gt;
&lt;div class="sourceCode" id="cb3"&gt;&lt;pre class="sourceCode python"&gt;&lt;code class="sourceCode python"&gt;&lt;span id="cb3-1"&gt;&lt;a aria-hidden="true" href="#cb3-1" tabindex="-1"&gt;&lt;/a&gt;x &lt;span class="op"&gt;=&lt;/span&gt; torch.tensor([[&lt;span class="fl"&gt;1.&lt;/span&gt;, &lt;span class="fl"&gt;2.&lt;/span&gt;], [&lt;span class="fl"&gt;3.&lt;/span&gt;, &lt;span class="fl"&gt;4.&lt;/span&gt;], [&lt;span class="fl"&gt;5.&lt;/span&gt;, &lt;span class="fl"&gt;6.&lt;/span&gt;]])&lt;/span&gt;
&lt;span id="cb3-2"&gt;&lt;a aria-hidden="true" href="#cb3-2" tabindex="-1"&gt;&lt;/a&gt;rid &lt;span class="op"&gt;=&lt;/span&gt; torch.tensor([&lt;span class="dv"&gt;0&lt;/span&gt;, &lt;span class="dv"&gt;0&lt;/span&gt;, &lt;span class="dv"&gt;1&lt;/span&gt;])&lt;/span&gt;
&lt;span id="cb3-3"&gt;&lt;a aria-hidden="true" href="#cb3-3" tabindex="-1"&gt;&lt;/a&gt;torch.zeros(&lt;span class="dv"&gt;2&lt;/span&gt;, &lt;span class="dv"&gt;2&lt;/span&gt;).index_add_(&lt;span class="dv"&gt;0&lt;/span&gt;, rid, x)&lt;/span&gt;
&lt;span id="cb3-4"&gt;&lt;a aria-hidden="true" href="#cb3-4" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;# tensor([[4., 6.],&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb3-5"&gt;&lt;a aria-hidden="true" href="#cb3-5" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;#         [5., 6.]])&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The number of segments sets the output shape.
&lt;code&gt;tf.math.segment_sum&lt;/code&gt; infers it from the largest ID and
requires sorted IDs. The unsorted TensorFlow variant and the JAX
function take &lt;code&gt;num_segments&lt;/code&gt; as an argument. A compiled graph
needs a fixed output shape, so code that will be compiled passes
&lt;code&gt;num_segments&lt;/code&gt; explicitly.&lt;/p&gt;
&lt;h2 id="segmented-softmax"&gt;Segmented softmax&lt;/h2&gt;
&lt;p&gt;A softmax over each segment needs two segment reductions, a max for
numerical stability and a sum for the denominator:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;m[s]   = max of scores[i] in segment s
e[i]   = exp(scores[i] - m[segment_ids[i]])
out[i] = e[i] / (sum of e[j] in segment s)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Each segment’s outputs sum to 1, and the segments do not affect each
other.&lt;/p&gt;
&lt;p&gt;LLM serving with continuous batching produces this situation. The
tokens or KV cache blocks of several sequences are packed along one
dimension of a single tensor, and the attention softmax for each
sequence must cover only that sequence’s entries. Here the segment ID of
an entry is the sequence it belongs to.&lt;/p&gt;
&lt;p&gt;transformers-neuronx, the AWS Neuron library for LLM inference, has a
&lt;code&gt;blockwise_softmax&lt;/code&gt; function for its paged KV cache. The
function is in &lt;a href="https://github.com/aws-neuron/transformers-neuronx/blob/1ade6d74224a89fb6366ded52153e2f32781e20d/src/transformers_neuronx/layers/attention_utils.py"&gt;&lt;code&gt;layers/attention_utils.py&lt;/code&gt;&lt;/a&gt;,
published in December 2024. The logits have one row per active cache
block, and &lt;code&gt;block_to_seq&lt;/code&gt; maps each block to its sequence.
The function first reduces within each block, then calls
&lt;code&gt;blockwise_reduce_max&lt;/code&gt; and &lt;code&gt;blockwise_reduce_sum&lt;/code&gt;
to combine the blocks of each sequence. Those two functions are segment
reductions with &lt;code&gt;block_to_seq&lt;/code&gt; as the segment IDs.&lt;/p&gt;
&lt;h2 id="three-ways-to-write-it"&gt;Three ways to write it&lt;/h2&gt;
&lt;p&gt;The three versions below compute the same result. They differ in how
many operations they put into the graph and which hardware units do the
work.&lt;/p&gt;
&lt;h3 id="a-loop-over-segments"&gt;A loop over segments&lt;/h3&gt;
&lt;p&gt;The direct version masks out every other segment, reduces, and writes
the result back to the rows of the current segment:&lt;/p&gt;
&lt;div class="sourceCode" id="cb5"&gt;&lt;pre class="sourceCode python"&gt;&lt;code class="sourceCode python"&gt;&lt;span id="cb5-1"&gt;&lt;a aria-hidden="true" href="#cb5-1" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="kw"&gt;def&lt;/span&gt; softmax_loop(scores, ids, num_segments):&lt;/span&gt;
&lt;span id="cb5-2"&gt;&lt;a aria-hidden="true" href="#cb5-2" tabindex="-1"&gt;&lt;/a&gt;    out &lt;span class="op"&gt;=&lt;/span&gt; torch.empty_like(scores)&lt;/span&gt;
&lt;span id="cb5-3"&gt;&lt;a aria-hidden="true" href="#cb5-3" tabindex="-1"&gt;&lt;/a&gt;    &lt;span class="cf"&gt;for&lt;/span&gt; s &lt;span class="kw"&gt;in&lt;/span&gt; &lt;span class="bu"&gt;range&lt;/span&gt;(num_segments):&lt;/span&gt;
&lt;span id="cb5-4"&gt;&lt;a aria-hidden="true" href="#cb5-4" tabindex="-1"&gt;&lt;/a&gt;        mask &lt;span class="op"&gt;=&lt;/span&gt; ids &lt;span class="op"&gt;==&lt;/span&gt; s&lt;/span&gt;
&lt;span id="cb5-5"&gt;&lt;a aria-hidden="true" href="#cb5-5" tabindex="-1"&gt;&lt;/a&gt;        m &lt;span class="op"&gt;=&lt;/span&gt; torch.where(mask, scores, &lt;span class="bu"&gt;float&lt;/span&gt;(&lt;span class="st"&gt;"-inf"&lt;/span&gt;)).&lt;span class="bu"&gt;max&lt;/span&gt;()&lt;/span&gt;
&lt;span id="cb5-6"&gt;&lt;a aria-hidden="true" href="#cb5-6" tabindex="-1"&gt;&lt;/a&gt;        e &lt;span class="op"&gt;=&lt;/span&gt; torch.where(mask, torch.exp(scores &lt;span class="op"&gt;-&lt;/span&gt; m), &lt;span class="fl"&gt;0.0&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb5-7"&gt;&lt;a aria-hidden="true" href="#cb5-7" tabindex="-1"&gt;&lt;/a&gt;        out &lt;span class="op"&gt;=&lt;/span&gt; torch.where(mask, e &lt;span class="op"&gt;/&lt;/span&gt; e.&lt;span class="bu"&gt;sum&lt;/span&gt;(), out)&lt;/span&gt;
&lt;span id="cb5-8"&gt;&lt;a aria-hidden="true" href="#cb5-8" tabindex="-1"&gt;&lt;/a&gt;    &lt;span class="cf"&gt;return&lt;/span&gt; out&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The two transformers-neuronx functions follow this structure. Each
one loops over &lt;code&gt;range(num_seqs)&lt;/code&gt;, and each iteration emits a
constant, a compare, a masked select, a reduction, a broadcast and a
second masked select:&lt;/p&gt;
&lt;div class="sourceCode" id="cb6"&gt;&lt;pre class="sourceCode python"&gt;&lt;code class="sourceCode python"&gt;&lt;span id="cb6-1"&gt;&lt;a aria-hidden="true" href="#cb6-1" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="cf"&gt;for&lt;/span&gt; seq_id &lt;span class="kw"&gt;in&lt;/span&gt; &lt;span class="bu"&gt;range&lt;/span&gt;(num_seqs):&lt;/span&gt;
&lt;span id="cb6-2"&gt;&lt;a aria-hidden="true" href="#cb6-2" tabindex="-1"&gt;&lt;/a&gt;    seq_full &lt;span class="op"&gt;=&lt;/span&gt; hlo.full(seq_id, s32, o_sizes)&lt;/span&gt;
&lt;span id="cb6-3"&gt;&lt;a aria-hidden="true" href="#cb6-3" tabindex="-1"&gt;&lt;/a&gt;    seq_mask &lt;span class="op"&gt;=&lt;/span&gt; hlo.equal(seq_iota, seq_full)&lt;/span&gt;
&lt;span id="cb6-4"&gt;&lt;a aria-hidden="true" href="#cb6-4" tabindex="-1"&gt;&lt;/a&gt;    masked_logits &lt;span class="op"&gt;=&lt;/span&gt; hlo.masked_select(seq_mask, logits, zero)&lt;/span&gt;
&lt;span id="cb6-5"&gt;&lt;a aria-hidden="true" href="#cb6-5" tabindex="-1"&gt;&lt;/a&gt;    output_br &lt;span class="op"&gt;=&lt;/span&gt; hlo.broadcast(hlo.reduce_sum(masked_logits, dim&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="dv"&gt;0&lt;/span&gt;, keepdim&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="va"&gt;True&lt;/span&gt;), o_sizes, [&lt;span class="dv"&gt;0&lt;/span&gt;, &lt;span class="dv"&gt;1&lt;/span&gt;, &lt;span class="dv"&gt;2&lt;/span&gt;])&lt;/span&gt;
&lt;span id="cb6-6"&gt;&lt;a aria-hidden="true" href="#cb6-6" tabindex="-1"&gt;&lt;/a&gt;    output &lt;span class="op"&gt;=&lt;/span&gt; hlo.masked_select(seq_mask, output_br, output)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This Python loop runs while the graph is being traced, so the
compiled graph contains one copy of the body per sequence. With a
maximum of 64 sequences, the two reductions together emit 768 HLO
instructions where a fixed-size formulation needs a handful. The graph
and its compile time grow with the batch size. Every copy also reads the
full logits tensor, so the memory traffic grows with the number of
sequences too.&lt;/p&gt;
&lt;h3 id="scatter-and-gather"&gt;Scatter and gather&lt;/h3&gt;
&lt;p&gt;A scatter with a reduction writes each entry into the slot of its
segment and combines collisions with max or add. A gather with the
segment IDs then reads each segment’s result back to its entries:&lt;/p&gt;
&lt;div class="sourceCode" id="cb7"&gt;&lt;pre class="sourceCode python"&gt;&lt;code class="sourceCode python"&gt;&lt;span id="cb7-1"&gt;&lt;a aria-hidden="true" href="#cb7-1" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="kw"&gt;def&lt;/span&gt; softmax_scatter(scores, ids, num_segments):&lt;/span&gt;
&lt;span id="cb7-2"&gt;&lt;a aria-hidden="true" href="#cb7-2" tabindex="-1"&gt;&lt;/a&gt;    m &lt;span class="op"&gt;=&lt;/span&gt; torch.full((num_segments,), &lt;span class="bu"&gt;float&lt;/span&gt;(&lt;span class="st"&gt;"-inf"&lt;/span&gt;)).scatter_reduce(&lt;/span&gt;
&lt;span id="cb7-3"&gt;&lt;a aria-hidden="true" href="#cb7-3" tabindex="-1"&gt;&lt;/a&gt;        &lt;span class="dv"&gt;0&lt;/span&gt;, ids, scores, &lt;span class="bu"&gt;reduce&lt;/span&gt;&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="st"&gt;"amax"&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb7-4"&gt;&lt;a aria-hidden="true" href="#cb7-4" tabindex="-1"&gt;&lt;/a&gt;    e &lt;span class="op"&gt;=&lt;/span&gt; torch.exp(scores &lt;span class="op"&gt;-&lt;/span&gt; m[ids])&lt;/span&gt;
&lt;span id="cb7-5"&gt;&lt;a aria-hidden="true" href="#cb7-5" tabindex="-1"&gt;&lt;/a&gt;    denom &lt;span class="op"&gt;=&lt;/span&gt; torch.zeros(num_segments).index_add_(&lt;span class="dv"&gt;0&lt;/span&gt;, ids, e)&lt;/span&gt;
&lt;span id="cb7-6"&gt;&lt;a aria-hidden="true" href="#cb7-6" tabindex="-1"&gt;&lt;/a&gt;    &lt;span class="cf"&gt;return&lt;/span&gt; e &lt;span class="op"&gt;/&lt;/span&gt; denom[ids]&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The graph has the same number of operations for any number of
segments. XLA’s scatter instruction takes the combining function as an
argument, so both the max and the sum map onto it. How fast scatter and
gather run depends on the backend and on how well it handles
data-dependent addresses.&lt;/p&gt;
&lt;h3 id="one-hot-matrix-multiplication"&gt;One-hot matrix
multiplication&lt;/h3&gt;
&lt;p&gt;A one-hot matrix &lt;code&gt;onehot[i, s]&lt;/code&gt; is 1 when entry
&lt;code&gt;i&lt;/code&gt; belongs to segment &lt;code&gt;s&lt;/code&gt;. Multiplying by its
transpose sums each segment, and multiplying by the matrix itself
broadcasts each segment’s value back to its entries:&lt;/p&gt;
&lt;div class="sourceCode" id="cb8"&gt;&lt;pre class="sourceCode python"&gt;&lt;code class="sourceCode python"&gt;&lt;span id="cb8-1"&gt;&lt;a aria-hidden="true" href="#cb8-1" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="kw"&gt;def&lt;/span&gt; softmax_onehot(scores, ids, num_segments):&lt;/span&gt;
&lt;span id="cb8-2"&gt;&lt;a aria-hidden="true" href="#cb8-2" tabindex="-1"&gt;&lt;/a&gt;    onehot &lt;span class="op"&gt;=&lt;/span&gt; torch.nn.functional.one_hot(ids, num_segments).to(scores.dtype)&lt;/span&gt;
&lt;span id="cb8-3"&gt;&lt;a aria-hidden="true" href="#cb8-3" tabindex="-1"&gt;&lt;/a&gt;    m &lt;span class="op"&gt;=&lt;/span&gt; torch.where(onehot.&lt;span class="bu"&gt;bool&lt;/span&gt;(), scores[:, &lt;span class="va"&gt;None&lt;/span&gt;], &lt;span class="bu"&gt;float&lt;/span&gt;(&lt;span class="st"&gt;"-inf"&lt;/span&gt;)).amax(dim&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="dv"&gt;0&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb8-4"&gt;&lt;a aria-hidden="true" href="#cb8-4" tabindex="-1"&gt;&lt;/a&gt;    e &lt;span class="op"&gt;=&lt;/span&gt; torch.exp(scores &lt;span class="op"&gt;-&lt;/span&gt; onehot &lt;span class="op"&gt;@&lt;/span&gt; m)&lt;/span&gt;
&lt;span id="cb8-5"&gt;&lt;a aria-hidden="true" href="#cb8-5" tabindex="-1"&gt;&lt;/a&gt;    &lt;span class="cf"&gt;return&lt;/span&gt; e &lt;span class="op"&gt;/&lt;/span&gt; (onehot &lt;span class="op"&gt;@&lt;/span&gt; (onehot.T &lt;span class="op"&gt;@&lt;/span&gt; e))&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The sums and broadcasts become matrix multiplications, which run on
the matrix units of an accelerator. A max cannot be written as a matmul,
so the max uses a masked reduction over an
&lt;code&gt;[entries, segments]&lt;/code&gt; tensor. That tensor is the cost of this
version. Its size is the number of entries times the number of segments,
times the size of any trailing dimensions. Many of the multiplications
are by zero, which is acceptable when the matrix units would otherwise
sit idle.&lt;/p&gt;
&lt;h2 id="checking-the-versions"&gt;Checking the versions&lt;/h2&gt;
&lt;p&gt;The three functions agree, and each segment of the result sums to
1:&lt;/p&gt;
&lt;div class="sourceCode" id="cb9"&gt;&lt;pre class="sourceCode python"&gt;&lt;code class="sourceCode python"&gt;&lt;span id="cb9-1"&gt;&lt;a aria-hidden="true" href="#cb9-1" tabindex="-1"&gt;&lt;/a&gt;torch.manual_seed(&lt;span class="dv"&gt;0&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb9-2"&gt;&lt;a aria-hidden="true" href="#cb9-2" tabindex="-1"&gt;&lt;/a&gt;scores &lt;span class="op"&gt;=&lt;/span&gt; torch.randn(&lt;span class="dv"&gt;10&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb9-3"&gt;&lt;a aria-hidden="true" href="#cb9-3" tabindex="-1"&gt;&lt;/a&gt;ids &lt;span class="op"&gt;=&lt;/span&gt; torch.tensor([&lt;span class="dv"&gt;0&lt;/span&gt;, &lt;span class="dv"&gt;0&lt;/span&gt;, &lt;span class="dv"&gt;0&lt;/span&gt;, &lt;span class="dv"&gt;1&lt;/span&gt;, &lt;span class="dv"&gt;1&lt;/span&gt;, &lt;span class="dv"&gt;2&lt;/span&gt;, &lt;span class="dv"&gt;2&lt;/span&gt;, &lt;span class="dv"&gt;2&lt;/span&gt;, &lt;span class="dv"&gt;2&lt;/span&gt;, &lt;span class="dv"&gt;3&lt;/span&gt;])&lt;/span&gt;
&lt;span id="cb9-4"&gt;&lt;a aria-hidden="true" href="#cb9-4" tabindex="-1"&gt;&lt;/a&gt;a &lt;span class="op"&gt;=&lt;/span&gt; softmax_loop(scores, ids, &lt;span class="dv"&gt;4&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb9-5"&gt;&lt;a aria-hidden="true" href="#cb9-5" tabindex="-1"&gt;&lt;/a&gt;b &lt;span class="op"&gt;=&lt;/span&gt; softmax_scatter(scores, ids, &lt;span class="dv"&gt;4&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb9-6"&gt;&lt;a aria-hidden="true" href="#cb9-6" tabindex="-1"&gt;&lt;/a&gt;c &lt;span class="op"&gt;=&lt;/span&gt; softmax_onehot(scores, ids, &lt;span class="dv"&gt;4&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb9-7"&gt;&lt;a aria-hidden="true" href="#cb9-7" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="cf"&gt;assert&lt;/span&gt; torch.allclose(a, b) &lt;span class="kw"&gt;and&lt;/span&gt; torch.allclose(a, c)&lt;/span&gt;
&lt;span id="cb9-8"&gt;&lt;a aria-hidden="true" href="#cb9-8" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="cf"&gt;assert&lt;/span&gt; torch.allclose(torch.zeros(&lt;span class="dv"&gt;4&lt;/span&gt;).index_add_(&lt;span class="dv"&gt;0&lt;/span&gt;, ids, a), torch.ones(&lt;span class="dv"&gt;4&lt;/span&gt;))&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h2 id="choosing-an-approach"&gt;Choosing an approach&lt;/h2&gt;
&lt;p&gt;For a compiled graph, a loop whose trip count is a tensor size or a
batch limit makes the graph grow with that size. The scatter and one-hot
versions keep the operation count fixed. Scatter does the least
arithmetic. The one-hot version runs on the matrix units and uses no
data-dependent addressing, at the price of an
&lt;code&gt;[entries, segments]&lt;/code&gt; intermediate. Which one is faster
depends on the backend, so the choice comes from measuring both at the
batch sizes the server runs.&lt;/p&gt;
&lt;p&gt;A fused attention kernel can avoid the segmented softmax altogether.
If the kernel receives a mask that marks which cached positions each
query may attend to, it can run an ordinary softmax with the masked
positions set to a large negative value. The mask then keeps the
sequences apart.&lt;/p&gt;
&lt;h2 id="references"&gt;References&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/aws-neuron/transformers-neuronx/blob/1ade6d74224a89fb6366ded52153e2f32781e20d/src/transformers_neuronx/layers/attention_utils.py"&gt;&lt;code&gt;attention_utils.py&lt;/code&gt;
in transformers-neuronx&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.tensorflow.org/api_docs/python/tf/math/unsorted_segment_sum"&gt;&lt;code&gt;tf.math.unsorted_segment_sum&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.jax.dev/en/latest/_autosummary/jax.ops.segment_sum.html"&gt;&lt;code&gt;jax.ops.segment_sum&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.pytorch.org/docs/main/generated/torch.Tensor.scatter_reduce_.html"&gt;&lt;code&gt;torch.Tensor.scatter_reduce_&lt;/code&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;</content><category term="LLM-Inference"/><category term="kernels"/><category term="xla"/><category term="softmax"/><category term="continuous-batching"/><category term="pytorch"/></entry><entry><title>Paged Attention and Chunked Prefill for LLM Inference</title><link href="https://sengopal.me/posts/paged-attention-and-chunked-prefill-for-llm-inference" rel="alternate"/><published>2024-12-28T00:00:00-08:00</published><updated>2024-12-28T00:00:00-08:00</updated><author><name>Senthilkumar Gopal</name></author><id>tag:sengopal.me,2024-12-28:/posts/paged-attention-and-chunked-prefill-for-llm-inference</id><summary type="html">This post explains how Paged Attention and Chunked Prefill optimize memory and computation in vLLM by organizing key-value caches into dynamic blocks and processing input sequences in manageable chunks. It includes a simple walkthrough with tensor shapes and code to showcase their integration for LLM inference.</summary><content type="html">&lt;p&gt;Large Language Models (LLMs) impose significant memory and compute
demands during inference, particularly when handling long sequences or
large batch sizes. To address these challenges, the vLLM system
introduces two key optimization techniques - Paged Attention&lt;a class="footnote-ref" href="#fn1" id="fnref1" role="doc-noteref"&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; and Chunked Prefill&lt;a class="footnote-ref" href="#fn2" id="fnref2" role="doc-noteref"&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/a&gt;
that target memory efficiency at different stages of inference. This
post examines these techniques, clarifying their roles, mechanisms, and
interplay. We demonstrate that they can be jointly employed to optimize
both the prefill and decoding phases without conflict. Through tensor
shape analysis and execution flow, we illustrate how these strategies
improve throughput and memory utilization.&lt;/p&gt;
&lt;h2 id="memory-bottlenecks-in-llm-inference"&gt;Memory Bottlenecks in LLM
Inference&lt;/h2&gt;
&lt;p&gt;Inference in autoregressive LLMs typically involves two phases:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;&lt;strong&gt;Prefill Phase:&lt;/strong&gt; The model processes a prompt
sequence, computes hidden states, and builds key-value caches for
subsequent decoding.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Decoding Phase:&lt;/strong&gt; The model generates tokens
autoregressively, using previously computed key-value caches.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Both phases can be memory-intensive. In the prefill phase, peak
memory usage can spike when processing long sequences. In the decoding
phase, the cumulative storage of key-value tensors can saturate memory,
particularly in multi-user, high-throughput settings.&lt;/p&gt;
&lt;h2 id="paged-attention"&gt;Paged Attention&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Paged Attention&lt;/strong&gt; is a memory management strategy that
organizes key-value tensors into fixed-size &lt;strong&gt;blocks&lt;/strong&gt;.
Instead of pre-allocating memory proportional to the maximum possible
sequence length, Paged Attention dynamically allocates and pages these
blocks into memory as needed during attention score computation.&lt;/p&gt;
&lt;h3 id="mechanism"&gt;Mechanism&lt;/h3&gt;
&lt;p&gt;Let the input sequence have length &lt;span class="math inline"&gt;&lt;em&gt;L&lt;/em&gt;&lt;/span&gt;, batch size &lt;span class="math inline"&gt;&lt;em&gt;B&lt;/em&gt;&lt;/span&gt;, hidden size &lt;span class="math inline"&gt;&lt;em&gt;H&lt;/em&gt;&lt;/span&gt;, and number of heads &lt;span class="math inline"&gt;&lt;em&gt;n&lt;/em&gt;&lt;sub&gt;head&lt;/sub&gt;&lt;/span&gt;. Without Paged
Attention, key-value tensors are stored as:&lt;/p&gt;
&lt;p&gt;&lt;span class="math display"&gt;Keys,
Values ∈ ℝ&lt;sup&gt;&lt;em&gt;B&lt;/em&gt; × &lt;em&gt;L&lt;/em&gt; × &lt;em&gt;n&lt;/em&gt;&lt;sub&gt;head&lt;/sub&gt; × &lt;em&gt;d&lt;/em&gt;&lt;sub&gt;head&lt;/sub&gt;&lt;/sup&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;Paged Attention partitions these tensors into &lt;strong&gt;blocks&lt;/strong&gt;
of size &lt;code&gt;block_size&lt;/code&gt;. Each block stores:&lt;/p&gt;
&lt;p&gt;&lt;span class="math display"&gt;Block
Tensor ∈ ℝ&lt;sup&gt;&lt;em&gt;B&lt;/em&gt; × block_size × &lt;em&gt;n&lt;/em&gt;&lt;sub&gt;head&lt;/sub&gt; × &lt;em&gt;d&lt;/em&gt;&lt;sub&gt;head&lt;/sub&gt;&lt;/sup&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;During attention computation at position &lt;span class="math inline"&gt;&lt;em&gt;t&lt;/em&gt;&lt;/span&gt;, only the relevant blocks
containing key-value pairs from positions &lt;span class="math inline"&gt;0&lt;/span&gt; to &lt;span class="math inline"&gt;&lt;em&gt;t&lt;/em&gt; − 1&lt;/span&gt; are loaded into memory.&lt;/p&gt;
&lt;h3 id="example-illustration"&gt;Example Illustration&lt;/h3&gt;
&lt;p&gt;Consider the following configuration:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Sequence length &lt;span class="math inline"&gt;&lt;em&gt;L&lt;/em&gt; = 12&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Batch size &lt;span class="math inline"&gt;&lt;em&gt;B&lt;/em&gt; = 2&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Hidden size &lt;span class="math inline"&gt;&lt;em&gt;H&lt;/em&gt; = 8&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Number of heads &lt;span class="math inline"&gt;&lt;em&gt;n_head&lt;/em&gt; = 2&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Head dimension &lt;span class="math inline"&gt;&lt;em&gt;d_head&lt;/em&gt; = 4&lt;/span&gt;
(since &lt;span class="math inline"&gt;&lt;em&gt;H&lt;/em&gt; = &lt;em&gt;n_head&lt;/em&gt; × &lt;em&gt;d_head&lt;/em&gt;&lt;/span&gt;)&lt;/li&gt;
&lt;li&gt;Block size = 4&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The key-value tensor shapes without Paged Attention would be:&lt;/p&gt;
&lt;p&gt;&lt;span class="math display"&gt;Keys,
Values ∈ ℝ&lt;sup&gt;2 × 12 × 2 × 4&lt;/sup&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;With Paged Attention, the sequence is divided into:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Block 1: Positions 0–3 → Shape &lt;span class="math inline"&gt;(2, 4, 2, 4)&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Block 2: Positions 4–7 → Shape &lt;span class="math inline"&gt;(2, 4, 2, 4)&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Block 3: Positions 8–11 → Shape &lt;span class="math inline"&gt;(2, 4, 2, 4)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When computing attention for position &lt;span class="math inline"&gt;&lt;em&gt;t&lt;/em&gt; = 9&lt;/span&gt;, the model dynamically
loads:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Block 1: Positions 0–3&lt;/li&gt;
&lt;li&gt;Block 2: Positions 4–7&lt;/li&gt;
&lt;li&gt;First two positions of Block 3: Positions 8–9&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="chunked-prefill"&gt;Chunked Prefill&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Chunked Prefill&lt;/strong&gt; is an optimization technique applied
during the prefill phase to control peak memory usage. It divides the
input sequence into fixed-size &lt;strong&gt;chunks&lt;/strong&gt; and processes
them sequentially, limiting memory allocation for hidden state and
key-value computation.&lt;/p&gt;
&lt;h3 id="mechanism-1"&gt;Mechanism&lt;/h3&gt;
&lt;p&gt;Given a sequence of length ( L ), the sequence is partitioned into
chunks of size &lt;code&gt;chunk_size&lt;/code&gt;. For each chunk:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;The model computes the hidden states for tokens within the
chunk.&lt;/li&gt;
&lt;li&gt;It computes and caches the key-value tensors corresponding to these
tokens.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;&lt;strong&gt;Chunked Prefill performs full attention computation within
each chunk&lt;/strong&gt;, meaning each token’s query attends to all preceding
tokens, including those in prior chunks.&lt;/p&gt;
&lt;p&gt;However, during prefill, the model &lt;strong&gt;does not compute attention
outputs for future decoding tokens&lt;/strong&gt;; it only prepares the
key-value cache required for the decoding phase.&lt;/p&gt;
&lt;h3 id="example"&gt;Example&lt;/h3&gt;
&lt;p&gt;Using the same configuration:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Sequence length &lt;span class="math inline"&gt;&lt;em&gt;L&lt;/em&gt; = 12&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Batch size &lt;span class="math inline"&gt;&lt;em&gt;B&lt;/em&gt; = 2&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Hidden size &lt;span class="math inline"&gt;&lt;em&gt;H&lt;/em&gt; = 8&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Number of heads &lt;span class="math inline"&gt;&lt;em&gt;n_head&lt;/em&gt; = 2&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Head dimension &lt;span class="math inline"&gt;&lt;em&gt;d_head&lt;/em&gt; = 4&lt;/span&gt;&lt;/li&gt;
&lt;li&gt;Chunk size = 6&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The sequence is divided into:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Chunk 1:&lt;/strong&gt; Positions 0–5&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Chunk 2:&lt;/strong&gt; Positions 6–11&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For each chunk:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Hidden state tensor shape: &lt;span class="math inline"&gt;(2, 6, 8)&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Key-value tensor shape: &lt;span class="math inline"&gt;(2, 6, 2, 4)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Attention Computation during Prefill:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;For token at position &lt;span class="math inline"&gt;&lt;em&gt;t&lt;/em&gt; = 4&lt;/span&gt;
in Chunk 1, attention is computed over positions 0–3 within Chunk
1.&lt;br/&gt;
For token at position &lt;span class="math inline"&gt;&lt;em&gt;t&lt;/em&gt; = 7&lt;/span&gt; in
Chunk 2, attention is computed over:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Cached key-values from Chunk 1 (positions 0–5)&lt;/li&gt;
&lt;li&gt;Tokens 6–6 (preceding tokens in Chunk 2)&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="combined-example-and-execution-flow"&gt;Combined Example and
Execution Flow&lt;/h3&gt;
&lt;p&gt;Let:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Sequence length &lt;span class="math inline"&gt;&lt;em&gt;L&lt;/em&gt; = 12&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Batch size &lt;span class="math inline"&gt;&lt;em&gt;B&lt;/em&gt; = 2&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Hidden size &lt;span class="math inline"&gt;&lt;em&gt;H&lt;/em&gt; = 8&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Number of heads &lt;span class="math inline"&gt;&lt;em&gt;n_head&lt;/em&gt; = 2&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Head dimension &lt;span class="math inline"&gt;&lt;em&gt;d_head&lt;/em&gt; = 4&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Chunk size = 6&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Block size = 4&lt;/li&gt;
&lt;/ul&gt;
&lt;h4 id="prefill-phase"&gt;Prefill Phase&lt;/h4&gt;
&lt;p&gt;The model processes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Chunk 1 (positions 0–5):&lt;/strong&gt;
&lt;ul&gt;
&lt;li&gt;Hidden states: &lt;span class="math inline"&gt;(2, 6, 8)&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Key-value tensors cached: &lt;span class="math inline"&gt;(2, 6, 2, 4)&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Chunk 2 (positions 6–11):&lt;/strong&gt;
&lt;ul&gt;
&lt;li&gt;Hidden states: &lt;span class="math inline"&gt;(2, 6, 8)&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Key-value tensors cached: &lt;span class="math inline"&gt;(2, 6, 2, 4)&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Each token in Chunk 2 attends to all cached key-value pairs from
Chunk 1 and preceding tokens in Chunk 2.&lt;/p&gt;
&lt;h4 id="decoding-phase"&gt;Decoding Phase&lt;/h4&gt;
&lt;p&gt;During decoding, suppose the model is generating token at position
&lt;span class="math inline"&gt;&lt;em&gt;t&lt;/em&gt; = 12&lt;/span&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The model computes attention for the query at &lt;span class="math inline"&gt;&lt;em&gt;t&lt;/em&gt; = 12&lt;/span&gt; over all cached key-value
tensors from positions 0–11.&lt;/li&gt;
&lt;li&gt;Key-value tensors are organized in &lt;strong&gt;blocks&lt;/strong&gt;:&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Paged Attention dynamically loads the necessary blocks during
attention computation.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th style="text-align: center;"&gt;Block&lt;/th&gt;
&lt;th style="text-align: center;"&gt;Positions&lt;/th&gt;
&lt;th style="text-align: center;"&gt;Shape&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td style="text-align: center;"&gt;1&lt;/td&gt;
&lt;td style="text-align: center;"&gt;0–3&lt;/td&gt;
&lt;td style="text-align: center;"&gt;(2, 4, 2, 4)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: center;"&gt;2&lt;/td&gt;
&lt;td style="text-align: center;"&gt;4–7&lt;/td&gt;
&lt;td style="text-align: center;"&gt;(2, 4, 2, 4)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td style="text-align: center;"&gt;3&lt;/td&gt;
&lt;td style="text-align: center;"&gt;8–11&lt;/td&gt;
&lt;td style="text-align: center;"&gt;(2, 4, 2, 4)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&lt;br/&gt;&lt;/p&gt;
&lt;h4 id="tensor-shapes"&gt;Tensor Shapes&lt;/h4&gt;
&lt;table&gt;
&lt;colgroup&gt;
&lt;col style="width: 46%"/&gt;
&lt;col style="width: 53%"/&gt;
&lt;/colgroup&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Component&lt;/th&gt;
&lt;th&gt;Tensor Shape&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Key/Value tensor (no paging)&lt;/td&gt;
&lt;td&gt;(B, L, n_head, d_head)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Key/Value tensor in Paged Attention&lt;/td&gt;
&lt;td&gt;(B, block_size, n_head, d_head) per block&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Key/Value tensor in Chunked Prefill&lt;/td&gt;
&lt;td&gt;(B, chunk_size, n_head, d_head) per chunk&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;hr/&gt;
&lt;p&gt;A simple structure of how &lt;code&gt;block_size&lt;/code&gt; and
&lt;code&gt;chunk_size&lt;/code&gt; are utilized in attention mechanisms is provided
below.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Paged Attention and &lt;code&gt;block_size&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Paged Attention manages the Key-Value (KV) cache by dividing it into
fixed-size blocks, allowing dynamic memory allocation and efficient
handling of varying sequence lengths. The &lt;code&gt;block_size&lt;/code&gt;
parameter determines the number of tokens each block can store. In vLLM,
this is evident in the attention backend implementations.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Example from &lt;code&gt;flash_attn.py&lt;/code&gt;:&lt;/em&gt;&lt;/p&gt;
&lt;div class="sourceCode" id="cb1"&gt;&lt;pre class="sourceCode python"&gt;&lt;code class="sourceCode python"&gt;&lt;span id="cb1-1"&gt;&lt;a aria-hidden="true" href="#cb1-1" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;# Each block can contain up to block_size tokens.&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-2"&gt;&lt;a aria-hidden="true" href="#cb1-2" tabindex="-1"&gt;&lt;/a&gt;block_tables: Optional[torch.Tensor]&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;In this snippet, &lt;code&gt;block_tables&lt;/code&gt; is a tensor that maps
sequences to their respective blocks in the KV cache, with each block
capable of holding up to &lt;code&gt;block_size&lt;/code&gt; tokens. This structure
enables efficient memory usage by allocating only the necessary amount
of memory based on the sequence length.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Chunked Prefill and &lt;code&gt;chunk_size&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Chunked Prefill processes long input sequences by dividing them into
smaller chunks, reducing peak memory usage during the prefill phase. The
&lt;code&gt;chunk_size&lt;/code&gt; parameter defines the size of these chunks. In
vLLM, the attention backends handle chunking to ensure that memory
constraints are respected during computation.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Example from &lt;code&gt;pallas.py&lt;/code&gt;:&lt;/em&gt;&lt;/p&gt;
&lt;div class="sourceCode" id="cb2"&gt;&lt;pre class="sourceCode python"&gt;&lt;code class="sourceCode python"&gt;&lt;span id="cb2-1"&gt;&lt;a aria-hidden="true" href="#cb2-1" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;# Make sure the chunk size is a multiple of 2.&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb2-2"&gt;&lt;a aria-hidden="true" href="#cb2-2" tabindex="-1"&gt;&lt;/a&gt;chunk_size &lt;span class="op"&gt;=&lt;/span&gt; chunk_size &lt;span class="op"&gt;//&lt;/span&gt; &lt;span class="dv"&gt;2&lt;/span&gt; &lt;span class="op"&gt;*&lt;/span&gt; &lt;span class="dv"&gt;2&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb2-3"&gt;&lt;a aria-hidden="true" href="#cb2-3" tabindex="-1"&gt;&lt;/a&gt;num_chunks &lt;span class="op"&gt;=&lt;/span&gt; (batch_size &lt;span class="op"&gt;+&lt;/span&gt; chunk_size &lt;span class="op"&gt;-&lt;/span&gt; &lt;span class="dv"&gt;1&lt;/span&gt;) &lt;span class="op"&gt;//&lt;/span&gt; chunk_size&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Here, the code ensures that &lt;code&gt;chunk_size&lt;/code&gt; is an even number
and calculates &lt;code&gt;num_chunks&lt;/code&gt;, the total number of chunks
needed to process the batch. This approach allows the model to handle
large sequences by processing manageable chunks sequentially, thereby
optimizing memory usage.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Integration in Attention Computation:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The interplay between chunk size and block size exposes a tunable
trade-off between &lt;strong&gt;latency&lt;/strong&gt; and &lt;strong&gt;memory
efficiency&lt;/strong&gt;. A smaller chunk size reduces peak memory during
prefill but may increase latency due to more sequential chunk
processing. A smaller block size reduces persistent memory overhead but
may increase the number of memory page operations, potentially affecting
throughput.&lt;/p&gt;
&lt;p&gt;Adaptive strategies that adjust chunk and block sizes based on
sequence length, batch size, and memory pressure may further improve
resource utilization. During attention computation, especially in
scenarios involving long sequences or large batches, vLLM’s attention
backends utilize both &lt;code&gt;block_size&lt;/code&gt; and
&lt;code&gt;chunk_size&lt;/code&gt; to manage memory effectively. The KV cache is
organized into blocks of size &lt;code&gt;block_size&lt;/code&gt;, and input
sequences are processed in chunks of size &lt;code&gt;chunk_size&lt;/code&gt;. This
dual approach ensures that the model can handle extensive inputs without
exceeding memory limitations.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Example from &lt;code&gt;flashinfer.py&lt;/code&gt;:&lt;/em&gt;&lt;/p&gt;
&lt;div class="sourceCode" id="cb3"&gt;&lt;pre class="sourceCode python"&gt;&lt;code class="sourceCode python"&gt;&lt;span id="cb3-1"&gt;&lt;a aria-hidden="true" href="#cb3-1" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;# Get the number of valid blocks based on sequence length.&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb3-2"&gt;&lt;a aria-hidden="true" href="#cb3-2" tabindex="-1"&gt;&lt;/a&gt;block_table_bound &lt;span class="op"&gt;=&lt;/span&gt; seq_len &lt;span class="op"&gt;//&lt;/span&gt; &lt;span class="va"&gt;self&lt;/span&gt;.block_size &lt;span class="op"&gt;+&lt;/span&gt; &lt;span class="dv"&gt;1&lt;/span&gt; &lt;span class="cf"&gt;if&lt;/span&gt; seq_len &lt;span class="op"&gt;%&lt;/span&gt; &lt;span class="va"&gt;self&lt;/span&gt;.block_size &lt;span class="op"&gt;!=&lt;/span&gt; &lt;span class="dv"&gt;0&lt;/span&gt; &lt;span class="cf"&gt;else&lt;/span&gt; seq_len &lt;span class="op"&gt;//&lt;/span&gt; &lt;span class="va"&gt;self&lt;/span&gt;.block_size&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;This snippet calculates the number of valid blocks required for a
given sequence length, ensuring that the KV cache is allocated
appropriately. By managing the KV cache in blocks and processing input
in chunks, vLLM effectively balances memory usage and computational
efficiency during attention operations.&lt;/p&gt;
&lt;h2 id="sample-code-structure-with-paged-attention-and-chunked-prefill"&gt;Sample
code structure with Paged Attention and Chunked Prefill&lt;/h2&gt;
&lt;p&gt;To provide further clarity on the operational dynamics of
&lt;strong&gt;Paged Attention&lt;/strong&gt; and &lt;strong&gt;Chunked Prefill&lt;/strong&gt;,
the below includes a code walkthrough that models the mechanisms used in
the vLLM system. The following Python code captures the essential logic
behind how the key-value (KV) cache is organized into blocks and how
input sequences are processed in chunks.&lt;/p&gt;
&lt;p&gt;This example is based on the configuration discussed earlier:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Batch size &lt;span class="math inline"&gt;&lt;em&gt;B&lt;/em&gt; = 2&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Sequence length &lt;span class="math inline"&gt;&lt;em&gt;L&lt;/em&gt; = 12&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Hidden size &lt;span class="math inline"&gt;&lt;em&gt;H&lt;/em&gt; = 8&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Number of attention heads &lt;span class="math inline"&gt;&lt;em&gt;n_head&lt;/em&gt; = 2&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Head dimension &lt;span class="math inline"&gt;&lt;em&gt;d_head&lt;/em&gt; = 4&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Block size &lt;span class="math inline"&gt;4&lt;/span&gt;&lt;br/&gt;
&lt;/li&gt;
&lt;li&gt;Chunk size &lt;span class="math inline"&gt;6&lt;/span&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="sourceCode" id="cb4"&gt;&lt;pre class="sourceCode python"&gt;&lt;code class="sourceCode python"&gt;&lt;span id="cb4-1"&gt;&lt;a aria-hidden="true" href="#cb4-1" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="im"&gt;import&lt;/span&gt; torch&lt;/span&gt;
&lt;span id="cb4-2"&gt;&lt;a aria-hidden="true" href="#cb4-2" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-3"&gt;&lt;a aria-hidden="true" href="#cb4-3" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;# Configuration&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-4"&gt;&lt;a aria-hidden="true" href="#cb4-4" tabindex="-1"&gt;&lt;/a&gt;B &lt;span class="op"&gt;=&lt;/span&gt; &lt;span class="dv"&gt;2&lt;/span&gt;                     &lt;span class="co"&gt;# Batch size&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-5"&gt;&lt;a aria-hidden="true" href="#cb4-5" tabindex="-1"&gt;&lt;/a&gt;L &lt;span class="op"&gt;=&lt;/span&gt; &lt;span class="dv"&gt;12&lt;/span&gt;                    &lt;span class="co"&gt;# Sequence length&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-6"&gt;&lt;a aria-hidden="true" href="#cb4-6" tabindex="-1"&gt;&lt;/a&gt;H &lt;span class="op"&gt;=&lt;/span&gt; &lt;span class="dv"&gt;8&lt;/span&gt;                     &lt;span class="co"&gt;# Hidden size&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-7"&gt;&lt;a aria-hidden="true" href="#cb4-7" tabindex="-1"&gt;&lt;/a&gt;n_head &lt;span class="op"&gt;=&lt;/span&gt; &lt;span class="dv"&gt;2&lt;/span&gt;                &lt;span class="co"&gt;# Number of heads&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-8"&gt;&lt;a aria-hidden="true" href="#cb4-8" tabindex="-1"&gt;&lt;/a&gt;d_head &lt;span class="op"&gt;=&lt;/span&gt; H &lt;span class="op"&gt;//&lt;/span&gt; n_head      &lt;span class="co"&gt;# Head dimension&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-9"&gt;&lt;a aria-hidden="true" href="#cb4-9" tabindex="-1"&gt;&lt;/a&gt;block_size &lt;span class="op"&gt;=&lt;/span&gt; &lt;span class="dv"&gt;4&lt;/span&gt;            &lt;span class="co"&gt;# Paged Attention block size&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-10"&gt;&lt;a aria-hidden="true" href="#cb4-10" tabindex="-1"&gt;&lt;/a&gt;chunk_size &lt;span class="op"&gt;=&lt;/span&gt; &lt;span class="dv"&gt;6&lt;/span&gt;            &lt;span class="co"&gt;# Chunked Prefill size&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-11"&gt;&lt;a aria-hidden="true" href="#cb4-11" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-12"&gt;&lt;a aria-hidden="true" href="#cb4-12" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;# Initialize key-value cache using block table&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-13"&gt;&lt;a aria-hidden="true" href="#cb4-13" tabindex="-1"&gt;&lt;/a&gt;num_blocks &lt;span class="op"&gt;=&lt;/span&gt; (L &lt;span class="op"&gt;+&lt;/span&gt; block_size &lt;span class="op"&gt;-&lt;/span&gt; &lt;span class="dv"&gt;1&lt;/span&gt;) &lt;span class="op"&gt;//&lt;/span&gt; block_size&lt;/span&gt;
&lt;span id="cb4-14"&gt;&lt;a aria-hidden="true" href="#cb4-14" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-15"&gt;&lt;a aria-hidden="true" href="#cb4-15" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;# Each sequence in batch has its own block table mapping token idx to physical block&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-16"&gt;&lt;a aria-hidden="true" href="#cb4-16" tabindex="-1"&gt;&lt;/a&gt;block_table &lt;span class="op"&gt;=&lt;/span&gt; torch.arange(num_blocks).repeat(B, &lt;span class="dv"&gt;1&lt;/span&gt;)  &lt;span class="co"&gt;# [B, num_blocks]&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-17"&gt;&lt;a aria-hidden="true" href="#cb4-17" tabindex="-1"&gt;&lt;/a&gt;kv_cache &lt;span class="op"&gt;=&lt;/span&gt; torch.randn(B, num_blocks, block_size, n_head, d_head)  &lt;span class="co"&gt;# KV store&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-18"&gt;&lt;a aria-hidden="true" href="#cb4-18" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-19"&gt;&lt;a aria-hidden="true" href="#cb4-19" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;# Dummy queries for current chunk&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-20"&gt;&lt;a aria-hidden="true" href="#cb4-20" tabindex="-1"&gt;&lt;/a&gt;Q &lt;span class="op"&gt;=&lt;/span&gt; torch.randn(B, chunk_size, n_head, d_head)&lt;/span&gt;
&lt;span id="cb4-21"&gt;&lt;a aria-hidden="true" href="#cb4-21" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-22"&gt;&lt;a aria-hidden="true" href="#cb4-22" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;# Prefill processing loop (Chunked Prefill)&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-23"&gt;&lt;a aria-hidden="true" href="#cb4-23" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="cf"&gt;for&lt;/span&gt; b &lt;span class="kw"&gt;in&lt;/span&gt; &lt;span class="bu"&gt;range&lt;/span&gt;(B):&lt;/span&gt;
&lt;span id="cb4-24"&gt;&lt;a aria-hidden="true" href="#cb4-24" tabindex="-1"&gt;&lt;/a&gt;    &lt;span class="cf"&gt;for&lt;/span&gt; chunk_start &lt;span class="kw"&gt;in&lt;/span&gt; &lt;span class="bu"&gt;range&lt;/span&gt;(&lt;span class="dv"&gt;0&lt;/span&gt;, L, chunk_size):&lt;/span&gt;
&lt;span id="cb4-25"&gt;&lt;a aria-hidden="true" href="#cb4-25" tabindex="-1"&gt;&lt;/a&gt;        chunk_end &lt;span class="op"&gt;=&lt;/span&gt; &lt;span class="bu"&gt;min&lt;/span&gt;(chunk_start &lt;span class="op"&gt;+&lt;/span&gt; chunk_size, L)&lt;/span&gt;
&lt;span id="cb4-26"&gt;&lt;a aria-hidden="true" href="#cb4-26" tabindex="-1"&gt;&lt;/a&gt;        curr_chunk_len &lt;span class="op"&gt;=&lt;/span&gt; chunk_end &lt;span class="op"&gt;-&lt;/span&gt; chunk_start&lt;/span&gt;
&lt;span id="cb4-27"&gt;&lt;a aria-hidden="true" href="#cb4-27" tabindex="-1"&gt;&lt;/a&gt;        q &lt;span class="op"&gt;=&lt;/span&gt; Q[b, :curr_chunk_len]  &lt;span class="co"&gt;# [chunk_len, n_head, d_head]&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-28"&gt;&lt;a aria-hidden="true" href="#cb4-28" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-29"&gt;&lt;a aria-hidden="true" href="#cb4-29" tabindex="-1"&gt;&lt;/a&gt;        &lt;span class="co"&gt;# Accumulate attention outputs&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-30"&gt;&lt;a aria-hidden="true" href="#cb4-30" tabindex="-1"&gt;&lt;/a&gt;        attn_out &lt;span class="op"&gt;=&lt;/span&gt; []&lt;/span&gt;
&lt;span id="cb4-31"&gt;&lt;a aria-hidden="true" href="#cb4-31" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-32"&gt;&lt;a aria-hidden="true" href="#cb4-32" tabindex="-1"&gt;&lt;/a&gt;        &lt;span class="co"&gt;# Compute attention over previous tokens using Paged Attention blocks&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-33"&gt;&lt;a aria-hidden="true" href="#cb4-33" tabindex="-1"&gt;&lt;/a&gt;        &lt;span class="cf"&gt;for&lt;/span&gt; t &lt;span class="kw"&gt;in&lt;/span&gt; &lt;span class="bu"&gt;range&lt;/span&gt;(chunk_start, chunk_end):&lt;/span&gt;
&lt;span id="cb4-34"&gt;&lt;a aria-hidden="true" href="#cb4-34" tabindex="-1"&gt;&lt;/a&gt;            &lt;span class="co"&gt;# For query at position t, get all keys from positions [0, t]&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-35"&gt;&lt;a aria-hidden="true" href="#cb4-35" tabindex="-1"&gt;&lt;/a&gt;            t_block_idx &lt;span class="op"&gt;=&lt;/span&gt; t &lt;span class="op"&gt;//&lt;/span&gt; block_size&lt;/span&gt;
&lt;span id="cb4-36"&gt;&lt;a aria-hidden="true" href="#cb4-36" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-37"&gt;&lt;a aria-hidden="true" href="#cb4-37" tabindex="-1"&gt;&lt;/a&gt;            context_keys &lt;span class="op"&gt;=&lt;/span&gt; []&lt;/span&gt;
&lt;span id="cb4-38"&gt;&lt;a aria-hidden="true" href="#cb4-38" tabindex="-1"&gt;&lt;/a&gt;            context_values &lt;span class="op"&gt;=&lt;/span&gt; []&lt;/span&gt;
&lt;span id="cb4-39"&gt;&lt;a aria-hidden="true" href="#cb4-39" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-40"&gt;&lt;a aria-hidden="true" href="#cb4-40" tabindex="-1"&gt;&lt;/a&gt;            &lt;span class="co"&gt;# Page in required blocks&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-41"&gt;&lt;a aria-hidden="true" href="#cb4-41" tabindex="-1"&gt;&lt;/a&gt;            &lt;span class="cf"&gt;for&lt;/span&gt; blk_id &lt;span class="kw"&gt;in&lt;/span&gt; &lt;span class="bu"&gt;range&lt;/span&gt;(t_block_idx &lt;span class="op"&gt;+&lt;/span&gt; &lt;span class="dv"&gt;1&lt;/span&gt;):  &lt;span class="co"&gt;# include current block&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-42"&gt;&lt;a aria-hidden="true" href="#cb4-42" tabindex="-1"&gt;&lt;/a&gt;                physical_block &lt;span class="op"&gt;=&lt;/span&gt; block_table[b, blk_id]&lt;/span&gt;
&lt;span id="cb4-43"&gt;&lt;a aria-hidden="true" href="#cb4-43" tabindex="-1"&gt;&lt;/a&gt;                kv_block &lt;span class="op"&gt;=&lt;/span&gt; kv_cache[b, physical_block]   &lt;span class="co"&gt;# [block_size, n_head, d_head]&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-44"&gt;&lt;a aria-hidden="true" href="#cb4-44" tabindex="-1"&gt;&lt;/a&gt;                context_keys.append(kv_block)&lt;/span&gt;
&lt;span id="cb4-45"&gt;&lt;a aria-hidden="true" href="#cb4-45" tabindex="-1"&gt;&lt;/a&gt;                context_values.append(kv_block)  &lt;span class="co"&gt;# simplified: keys = values&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-46"&gt;&lt;a aria-hidden="true" href="#cb4-46" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-47"&gt;&lt;a aria-hidden="true" href="#cb4-47" tabindex="-1"&gt;&lt;/a&gt;            &lt;span class="co"&gt;# Flatten context into a single tensor [T', n_head, d_head]&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-48"&gt;&lt;a aria-hidden="true" href="#cb4-48" tabindex="-1"&gt;&lt;/a&gt;            K &lt;span class="op"&gt;=&lt;/span&gt; torch.cat(context_keys, dim&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="dv"&gt;0&lt;/span&gt;)[:t&lt;span class="op"&gt;+&lt;/span&gt;&lt;span class="dv"&gt;1&lt;/span&gt;]  &lt;span class="co"&gt;# causal&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-49"&gt;&lt;a aria-hidden="true" href="#cb4-49" tabindex="-1"&gt;&lt;/a&gt;            V &lt;span class="op"&gt;=&lt;/span&gt; torch.cat(context_values, dim&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="dv"&gt;0&lt;/span&gt;)[:t&lt;span class="op"&gt;+&lt;/span&gt;&lt;span class="dv"&gt;1&lt;/span&gt;]&lt;/span&gt;
&lt;span id="cb4-50"&gt;&lt;a aria-hidden="true" href="#cb4-50" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-51"&gt;&lt;a aria-hidden="true" href="#cb4-51" tabindex="-1"&gt;&lt;/a&gt;            q_t &lt;span class="op"&gt;=&lt;/span&gt; q[t &lt;span class="op"&gt;-&lt;/span&gt; chunk_start]  &lt;span class="co"&gt;# query vector at position t&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-52"&gt;&lt;a aria-hidden="true" href="#cb4-52" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-53"&gt;&lt;a aria-hidden="true" href="#cb4-53" tabindex="-1"&gt;&lt;/a&gt;            &lt;span class="co"&gt;# Scaled dot-product attention&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-54"&gt;&lt;a aria-hidden="true" href="#cb4-54" tabindex="-1"&gt;&lt;/a&gt;            scores &lt;span class="op"&gt;=&lt;/span&gt; torch.einsum(&lt;span class="st"&gt;"hd,thd-&amp;gt;t"&lt;/span&gt;, q_t, K) &lt;span class="op"&gt;/&lt;/span&gt; (d_head &lt;span class="op"&gt;**&lt;/span&gt; &lt;span class="fl"&gt;0.5&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb4-55"&gt;&lt;a aria-hidden="true" href="#cb4-55" tabindex="-1"&gt;&lt;/a&gt;            probs &lt;span class="op"&gt;=&lt;/span&gt; torch.softmax(scores, dim&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="dv"&gt;0&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb4-56"&gt;&lt;a aria-hidden="true" href="#cb4-56" tabindex="-1"&gt;&lt;/a&gt;            ctx &lt;span class="op"&gt;=&lt;/span&gt; torch.einsum(&lt;span class="st"&gt;"t,thd-&amp;gt;hd"&lt;/span&gt;, probs, V)&lt;/span&gt;
&lt;span id="cb4-57"&gt;&lt;a aria-hidden="true" href="#cb4-57" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-58"&gt;&lt;a aria-hidden="true" href="#cb4-58" tabindex="-1"&gt;&lt;/a&gt;            attn_out.append(ctx)&lt;/span&gt;
&lt;span id="cb4-59"&gt;&lt;a aria-hidden="true" href="#cb4-59" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb4-60"&gt;&lt;a aria-hidden="true" href="#cb4-60" tabindex="-1"&gt;&lt;/a&gt;        &lt;span class="co"&gt;# Stack outputs: [chunk_len, n_head, d_head]&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb4-61"&gt;&lt;a aria-hidden="true" href="#cb4-61" tabindex="-1"&gt;&lt;/a&gt;        attn_out &lt;span class="op"&gt;=&lt;/span&gt; torch.stack(attn_out, dim&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="dv"&gt;0&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb4-62"&gt;&lt;a aria-hidden="true" href="#cb4-62" tabindex="-1"&gt;&lt;/a&gt;        &lt;span class="bu"&gt;print&lt;/span&gt;(&lt;span class="ss"&gt;f"Chunk [&lt;/span&gt;&lt;span class="sc"&gt;{&lt;/span&gt;chunk_start&lt;span class="sc"&gt;}&lt;/span&gt;&lt;span class="ss"&gt;:&lt;/span&gt;&lt;span class="sc"&gt;{&lt;/span&gt;chunk_end&lt;span class="sc"&gt;}&lt;/span&gt;&lt;span class="ss"&gt;] attention output shape:"&lt;/span&gt;, attn_out.shape)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3 id="operational-flow"&gt;Operational Flow&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The block_table holds logical-to-physical mappings of KV blocks
for each sequence in the batch. Each block can store
&lt;code&gt;block_size&lt;/code&gt; tokens.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The KV cache (kv_cache) is allocated as &lt;span class="math inline"&gt;[&lt;em&gt;B&lt;/em&gt;, num_blocks, block_size, &lt;em&gt;n_head&lt;/em&gt;, &lt;em&gt;d_head&lt;/em&gt;]&lt;/span&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;For each chunk (driven by &lt;code&gt;chunk_size&lt;/code&gt;), queries are
processed in a causal way: each query &lt;span class="math inline"&gt;&lt;em&gt;t&lt;/em&gt;&lt;/span&gt; attends to all previous tokens
(positions 0 to &lt;span class="math inline"&gt;&lt;em&gt;t&lt;/em&gt;&lt;/span&gt;), using the
paged blocks.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Only the relevant blocks (from block 0 up to block &lt;span class="math inline"&gt;⌊&lt;em&gt;t&lt;/em&gt;/block_size⌋&lt;/span&gt;) are paged
in.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Attention is computed with the standard scaled dot-product
mechanism using concatenated keys and values.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Paged Attention&lt;/strong&gt; ensures that the key-value cache
is organized into fixed-size &lt;strong&gt;blocks&lt;/strong&gt;. Each token’s query
accesses the minimum required set of blocks based on its position &lt;span class="math inline"&gt;&lt;em&gt;t&lt;/em&gt;&lt;/span&gt;. This reduces persistent memory
footprint and supports dynamic allocation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Chunked Prefill&lt;/strong&gt; ensures that the input sequences
are processed in &lt;strong&gt;chunks&lt;/strong&gt; of size &lt;span class="math inline"&gt;6&lt;/span&gt;. For each chunk, attention scores are
computed incrementally over all previously processed tokens, including
those in earlier chunks. This limits peak memory usage during the
prefill phase.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Dynamic Paging&lt;/strong&gt; is setup such that for each token
&lt;span class="math inline"&gt;&lt;em&gt;t&lt;/em&gt;&lt;/span&gt; in a chunk, only the blocks
containing keys/values from positions &lt;span class="math inline"&gt;0&lt;/span&gt;
to &lt;span class="math inline"&gt;&lt;em&gt;t&lt;/em&gt;&lt;/span&gt; are loaded, ensuring
efficient memory utilization.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="conclusion"&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Paged Attention&lt;/strong&gt; and &lt;strong&gt;Chunked Prefill&lt;/strong&gt;
are orthogonal strategies for optimizing LLM inference in
memory-constrained environments. Paged Attention reduces persistent
memory consumption during attention score computation by dynamically
paging key-value blocks. Chunked Prefill mitigates peak memory usage
during the prefill phase by processing input sequences in chunks. There
are also exploration around kernel-level optimizations, fused attention
score computation across blocks, and dynamic eviction policies for the
block table to further improve inference throughput under multi-user,
long-sequence workloads.&lt;/p&gt;
&lt;h3 id="references"&gt;References&lt;/h3&gt;
&lt;section class="footnotes footnotes-end-of-document" id="footnotes" role="doc-endnotes"&gt;
&lt;hr/&gt;
&lt;ol&gt;
&lt;li id="fn1"&gt;&lt;p&gt;vLLM Paged Attention — vLLM.
https://docs.vllm.ai/en/latest/design/kernel/paged_attention.html#vllm-paged-attention.
Accessed 27 Mar. 2025.&lt;a class="footnote-back" href="#fnref1" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li id="fn2"&gt;&lt;p&gt;Optimization and Tuning — vLLM.
https://docs.vllm.ai/en/latest/performance/optimization.html#chunked-prefill.
Accessed 27 Mar. 2025.&lt;a class="footnote-back" href="#fnref2" role="doc-backlink"&gt;↩︎&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;/section&gt;</content><category term="LLM-Inference"/><category term="ml-code"/><category term="llm"/><category term="vllm"/><category term="serving"/></entry><entry><title>LLM Inference Systems</title><link href="https://sengopal.me/posts/llm-inference-systems" rel="alternate"/><published>2024-05-18T00:00:00-07:00</published><updated>2024-05-18T00:00:00-07:00</updated><author><name>Senthilkumar Gopal</name></author><id>tag:sengopal.me,2024-05-18:/posts/llm-inference-systems</id><summary type="html">A quick clarification between the terms - Triton, TensorRT, and TensorRT-LLM</summary><content type="html">&lt;p&gt;In my exploration of various inference systems, there is a general
confusion about Triton, TensorRT, and TensorRT-LLM. These are all
related to optimizing and deploying machine learning models, but with
different purposes and use cases, specifically what inputs and outputs
that they support.&lt;/p&gt;
&lt;h3 id="triton"&gt;Triton&lt;/h3&gt;
&lt;p&gt;Triton is an open-source inference &lt;strong&gt;server&lt;/strong&gt; (NVIDIA)
designed to optimize and deploy machine learning models for inference
workloads and supports multiple deep learning frameworks, including
TensorFlow, PyTorch, and TensorRT. Triton supportsfeatures like
batching, concurrent model execution, and dynamic batching to improve
performance and efficiency.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Inputs&lt;/strong&gt; Triton can accept inputs in various formats,
such as images, text, or numerical data, depending on the machine
learning model being deployed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Outputs&lt;/strong&gt; The outputs depend on the specific machine
learning model and its task, such as classification results, object
detection bounding boxes, or text generation.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="tensorrt"&gt;TensorRT&lt;/h3&gt;
&lt;p&gt;TensorRT is a high-performance deep learning inference optimizer and
runtime &lt;strong&gt;library&lt;/strong&gt; developed by NVIDIA designed to
optimize and accelerate the inference performance of deep learning
models on NVIDIA GPUs. TensorRT can optimize models from various deep
learning frameworks, including TensorFlow, PyTorch, and ONNX.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Inputs&lt;/strong&gt; TensorRT accepts deep learning models in
various formats, such as TensorFlow frozen graphs, PyTorch traced
models, or ONNX models.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Outputs&lt;/strong&gt; TensorRT optimizes the models for faster
inference on NVIDIA GPUs, but it does not change the model’s output
format. The outputs remain the same as the original model, such as
classification probabilities, object detection bounding boxes, or
segmentation masks.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3 id="tensorrt-llm"&gt;TensorRT-LLM&lt;/h3&gt;
&lt;p&gt;TensorRT-LLM is a branch of TensorRT specifically designed for
optimizing and deploying large language models (LLMs) on NVIDIA GPUs. It
provides optimizations and techniques tailored for the efficient
inference of LLMs, which can be computationally expensive due to their
large size and complex architectures.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Inputs&lt;/strong&gt; TensorRT-LLM accepts pre-trained LLM models
in various formats, such as TensorFlow, PyTorch, or ONNX.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Outputs&lt;/strong&gt; The outputs of TensorRT-LLM remain the same
as the original LLM model, which typically involves generating text
based on the input prompt or context.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;TL;DR - Triton is an inference server that can deploy and optimize
models from different frameworks, including TensorRT-optimized models.
TensorRT is a library for optimizing and accelerating deep learning
models for inference on NVIDIA GPUs. TensorRT-LLM is a specialized
branch of TensorRT focused on optimizing and deploying large language
models efficiently on NVIDIA GPUs.&lt;/p&gt;</content><category term="LLM-Inference"/><category term="ml-code"/><category term="llm"/></entry><entry><title>Top-2 Logit Analysis for Accuracy Across Hardware</title><link href="https://sengopal.me/posts/top-2-logit-analysis-for-accuracy-across-hardware" rel="alternate"/><published>2024-04-18T00:00:00-07:00</published><updated>2024-04-18T00:00:00-07:00</updated><author><name>Senthilkumar Gopal</name></author><id>tag:sengopal.me,2024-04-18:/posts/top-2-logit-analysis-for-accuracy-across-hardware</id><summary type="html">The gap between the top two tokens at each generation step shows where a model is uncertain, and where two hardware paths can select different tokens without either being incorrect.</summary><content type="html">&lt;p&gt;When a model selects an unexpected token, the gap between the top two
candidates at that step is a useful first measurement. A small gap
indicates that the model is uncertain, and sampling at that step is
close to a coin flip. A large gap indicates that the model is confident.
Plotting the gap across all generation steps shows which steps are
stable and which are sensitive to small numeric changes.&lt;/p&gt;
&lt;h2 id="step-1-dump-logits-offline"&gt;Step 1: dump logits offline&lt;/h2&gt;
&lt;p&gt;The TensorRT-LLM &lt;code&gt;run.py&lt;/code&gt; script can write both context
and generation logits to disk.&lt;/p&gt;
&lt;div class="sourceCode" id="cb1"&gt;&lt;pre class="sourceCode bash"&gt;&lt;code class="sourceCode bash"&gt;&lt;span id="cb1-1"&gt;&lt;a aria-hidden="true" href="#cb1-1" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;#!/bin/bash&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-2"&gt;&lt;a aria-hidden="true" href="#cb1-2" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;# dump_logits.sh&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-3"&gt;&lt;a aria-hidden="true" href="#cb1-3" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;# Generates a npy array on disk with the generated logits&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-4"&gt;&lt;a aria-hidden="true" href="#cb1-4" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb1-5"&gt;&lt;a aria-hidden="true" href="#cb1-5" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="va"&gt;script&lt;/span&gt;&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="st"&gt;"run.py"&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-6"&gt;&lt;a aria-hidden="true" href="#cb1-6" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="va"&gt;engine_dir&lt;/span&gt;&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="st"&gt;"r8_trt_logits/8-gpu/"&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-7"&gt;&lt;a aria-hidden="true" href="#cb1-7" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="va"&gt;input_csv&lt;/span&gt;&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="st"&gt;"tokenizer_input.csv"&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-8"&gt;&lt;a aria-hidden="true" href="#cb1-8" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb1-9"&gt;&lt;a aria-hidden="true" href="#cb1-9" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="ex"&gt;mpirun&lt;/span&gt; &lt;span class="at"&gt;-np&lt;/span&gt; 8 &lt;span class="at"&gt;--allow-run-as-root&lt;/span&gt; python &lt;span class="va"&gt;${script}&lt;/span&gt; &lt;span class="dt"&gt;\&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-10"&gt;&lt;a aria-hidden="true" href="#cb1-10" tabindex="-1"&gt;&lt;/a&gt;  &lt;span class="at"&gt;--input_file&lt;/span&gt; &lt;span class="va"&gt;${input_csv}&lt;/span&gt; &lt;span class="dt"&gt;\&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-11"&gt;&lt;a aria-hidden="true" href="#cb1-11" tabindex="-1"&gt;&lt;/a&gt;  &lt;span class="at"&gt;--output_csv&lt;/span&gt; outputs.csv &lt;span class="dt"&gt;\&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-12"&gt;&lt;a aria-hidden="true" href="#cb1-12" tabindex="-1"&gt;&lt;/a&gt;  &lt;span class="at"&gt;--output_logits_npy&lt;/span&gt; logits.npy &lt;span class="dt"&gt;\&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-13"&gt;&lt;a aria-hidden="true" href="#cb1-13" tabindex="-1"&gt;&lt;/a&gt;  &lt;span class="at"&gt;--top_p&lt;/span&gt; 1.0 &lt;span class="dt"&gt;\&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-14"&gt;&lt;a aria-hidden="true" href="#cb1-14" tabindex="-1"&gt;&lt;/a&gt;  &lt;span class="at"&gt;--temperature&lt;/span&gt; 1.0 &lt;span class="dt"&gt;\&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-15"&gt;&lt;a aria-hidden="true" href="#cb1-15" tabindex="-1"&gt;&lt;/a&gt;  &lt;span class="at"&gt;--max_output_len&lt;/span&gt; 100 &lt;span class="dt"&gt;\&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb1-16"&gt;&lt;a aria-hidden="true" href="#cb1-16" tabindex="-1"&gt;&lt;/a&gt;  &lt;span class="at"&gt;--engine_dir&lt;/span&gt; &lt;span class="st"&gt;"&lt;/span&gt;&lt;span class="va"&gt;${engine_dir}&lt;/span&gt;&lt;span class="st"&gt;"&lt;/span&gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The flags have the following roles:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;--input_file&lt;/code&gt; reads the tokenized input prompts from a
CSV file.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;--output_csv&lt;/code&gt; writes the generated text.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;--output_logits_npy&lt;/code&gt; writes the per-step logits as a
&lt;code&gt;.npy&lt;/code&gt; file.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;--top_p 1.0 --temperature 1.0&lt;/code&gt; keeps the full
distribution with no truncation.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;--max_output_len 100&lt;/code&gt; generates 100 output tokens.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;mpirun -np 8&lt;/code&gt; runs the engine across 8 GPUs with tensor
parallelism.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The engine must be built with
&lt;code&gt;--gather_generation_logits&lt;/code&gt;, otherwise it does not return
generation logits.&lt;/p&gt;
&lt;p&gt;The resulting &lt;code&gt;logits.npy&lt;/code&gt; has shape
&lt;code&gt;(batch_size, beam_size, token_gen_steps, vocab_size)&lt;/code&gt;. For
greedy decoding with &lt;code&gt;beam_size=1&lt;/code&gt; and
&lt;code&gt;batch_size=1&lt;/code&gt;, a 100-token generation produces a tensor of
shape &lt;code&gt;(1, 1, 100, vocab_size)&lt;/code&gt;.&lt;/p&gt;
&lt;h2 id="step-2-analyze-the-deltas"&gt;Step 2: analyze the deltas&lt;/h2&gt;
&lt;p&gt;The following script loads the dump and plots the gap:&lt;/p&gt;
&lt;div class="sourceCode" id="cb2"&gt;&lt;pre class="sourceCode python"&gt;&lt;code class="sourceCode python"&gt;&lt;span id="cb2-1"&gt;&lt;a aria-hidden="true" href="#cb2-1" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="co"&gt;# analyze_logits.py&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb2-2"&gt;&lt;a aria-hidden="true" href="#cb2-2" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="im"&gt;import&lt;/span&gt; numpy &lt;span class="im"&gt;as&lt;/span&gt; np&lt;/span&gt;
&lt;span id="cb2-3"&gt;&lt;a aria-hidden="true" href="#cb2-3" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="im"&gt;import&lt;/span&gt; torch&lt;/span&gt;
&lt;span id="cb2-4"&gt;&lt;a aria-hidden="true" href="#cb2-4" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="im"&gt;import&lt;/span&gt; pandas &lt;span class="im"&gt;as&lt;/span&gt; pd&lt;/span&gt;
&lt;span id="cb2-5"&gt;&lt;a aria-hidden="true" href="#cb2-5" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="im"&gt;import&lt;/span&gt; matplotlib.pyplot &lt;span class="im"&gt;as&lt;/span&gt; plt&lt;/span&gt;
&lt;span id="cb2-6"&gt;&lt;a aria-hidden="true" href="#cb2-6" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="im"&gt;import&lt;/span&gt; sys&lt;/span&gt;
&lt;span id="cb2-7"&gt;&lt;a aria-hidden="true" href="#cb2-7" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb2-8"&gt;&lt;a aria-hidden="true" href="#cb2-8" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb2-9"&gt;&lt;a aria-hidden="true" href="#cb2-9" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="kw"&gt;def&lt;/span&gt; diff2(logits_at_step, step&lt;span class="op"&gt;=-&lt;/span&gt;&lt;span class="dv"&gt;1&lt;/span&gt;):&lt;/span&gt;
&lt;span id="cb2-10"&gt;&lt;a aria-hidden="true" href="#cb2-10" tabindex="-1"&gt;&lt;/a&gt;    &lt;span class="co"&gt;"""Difference between the top-2 logits at a single step."""&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb2-11"&gt;&lt;a aria-hidden="true" href="#cb2-11" tabindex="-1"&gt;&lt;/a&gt;    top2 &lt;span class="op"&gt;=&lt;/span&gt; torch.topk(logits_at_step, &lt;span class="dv"&gt;2&lt;/span&gt;).values&lt;/span&gt;
&lt;span id="cb2-12"&gt;&lt;a aria-hidden="true" href="#cb2-12" tabindex="-1"&gt;&lt;/a&gt;    &lt;span class="bu"&gt;print&lt;/span&gt;(&lt;span class="ss"&gt;f"step &lt;/span&gt;&lt;span class="sc"&gt;{&lt;/span&gt;step&lt;span class="sc"&gt;}&lt;/span&gt;&lt;span class="ss"&gt;: top2=&lt;/span&gt;&lt;span class="sc"&gt;{&lt;/span&gt;top2&lt;span class="sc"&gt;}&lt;/span&gt;&lt;span class="ss"&gt;"&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb2-13"&gt;&lt;a aria-hidden="true" href="#cb2-13" tabindex="-1"&gt;&lt;/a&gt;    &lt;span class="cf"&gt;return&lt;/span&gt; &lt;span class="bu"&gt;abs&lt;/span&gt;(top2[&lt;span class="dv"&gt;0&lt;/span&gt;].item() &lt;span class="op"&gt;-&lt;/span&gt; top2[&lt;span class="dv"&gt;1&lt;/span&gt;].item())&lt;/span&gt;
&lt;span id="cb2-14"&gt;&lt;a aria-hidden="true" href="#cb2-14" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb2-15"&gt;&lt;a aria-hidden="true" href="#cb2-15" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb2-16"&gt;&lt;a aria-hidden="true" href="#cb2-16" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="kw"&gt;def&lt;/span&gt; plot(values):&lt;/span&gt;
&lt;span id="cb2-17"&gt;&lt;a aria-hidden="true" href="#cb2-17" tabindex="-1"&gt;&lt;/a&gt;    df &lt;span class="op"&gt;=&lt;/span&gt; pd.Series(values)&lt;/span&gt;
&lt;span id="cb2-18"&gt;&lt;a aria-hidden="true" href="#cb2-18" tabindex="-1"&gt;&lt;/a&gt;    df.plot(&lt;/span&gt;
&lt;span id="cb2-19"&gt;&lt;a aria-hidden="true" href="#cb2-19" tabindex="-1"&gt;&lt;/a&gt;        ylabel&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="st"&gt;"diff of top two probabilities"&lt;/span&gt;,&lt;/span&gt;
&lt;span id="cb2-20"&gt;&lt;a aria-hidden="true" href="#cb2-20" tabindex="-1"&gt;&lt;/a&gt;        xlabel&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="st"&gt;"token generation steps"&lt;/span&gt;,&lt;/span&gt;
&lt;span id="cb2-21"&gt;&lt;a aria-hidden="true" href="#cb2-21" tabindex="-1"&gt;&lt;/a&gt;        legend&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="va"&gt;False&lt;/span&gt;,&lt;/span&gt;
&lt;span id="cb2-22"&gt;&lt;a aria-hidden="true" href="#cb2-22" tabindex="-1"&gt;&lt;/a&gt;    )&lt;/span&gt;
&lt;span id="cb2-23"&gt;&lt;a aria-hidden="true" href="#cb2-23" tabindex="-1"&gt;&lt;/a&gt;    plt.hlines(y&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="fl"&gt;0.0&lt;/span&gt;, xmin&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="dv"&gt;0&lt;/span&gt;, xmax&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="bu"&gt;len&lt;/span&gt;(values),&lt;/span&gt;
&lt;span id="cb2-24"&gt;&lt;a aria-hidden="true" href="#cb2-24" tabindex="-1"&gt;&lt;/a&gt;               colors&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="st"&gt;'red'&lt;/span&gt;, linestyles&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="st"&gt;'-'&lt;/span&gt;, lw&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="dv"&gt;1&lt;/span&gt;,&lt;/span&gt;
&lt;span id="cb2-25"&gt;&lt;a aria-hidden="true" href="#cb2-25" tabindex="-1"&gt;&lt;/a&gt;               label&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="st"&gt;'no diff in probs'&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb2-26"&gt;&lt;a aria-hidden="true" href="#cb2-26" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb2-27"&gt;&lt;a aria-hidden="true" href="#cb2-27" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb2-28"&gt;&lt;a aria-hidden="true" href="#cb2-28" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="kw"&gt;def&lt;/span&gt; main():&lt;/span&gt;
&lt;span id="cb2-29"&gt;&lt;a aria-hidden="true" href="#cb2-29" tabindex="-1"&gt;&lt;/a&gt;    gen_logits &lt;span class="op"&gt;=&lt;/span&gt; torch.from_numpy(np.load(sys.argv[&lt;span class="dv"&gt;1&lt;/span&gt;]))&lt;/span&gt;
&lt;span id="cb2-30"&gt;&lt;a aria-hidden="true" href="#cb2-30" tabindex="-1"&gt;&lt;/a&gt;    batch_sz, beam_sz, token_gen_steps, vocab_size &lt;span class="op"&gt;=&lt;/span&gt; gen_logits.shape&lt;/span&gt;
&lt;span id="cb2-31"&gt;&lt;a aria-hidden="true" href="#cb2-31" tabindex="-1"&gt;&lt;/a&gt;    &lt;span class="bu"&gt;print&lt;/span&gt;(&lt;span class="ss"&gt;f"logits shape: &lt;/span&gt;&lt;span class="sc"&gt;{&lt;/span&gt;gen_logits&lt;span class="sc"&gt;.&lt;/span&gt;shape&lt;span class="sc"&gt;}&lt;/span&gt;&lt;span class="ss"&gt;"&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb2-32"&gt;&lt;a aria-hidden="true" href="#cb2-32" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb2-33"&gt;&lt;a aria-hidden="true" href="#cb2-33" tabindex="-1"&gt;&lt;/a&gt;    logits_diff &lt;span class="op"&gt;=&lt;/span&gt; []&lt;/span&gt;
&lt;span id="cb2-34"&gt;&lt;a aria-hidden="true" href="#cb2-34" tabindex="-1"&gt;&lt;/a&gt;    probs_diff &lt;span class="op"&gt;=&lt;/span&gt; []&lt;/span&gt;
&lt;span id="cb2-35"&gt;&lt;a aria-hidden="true" href="#cb2-35" tabindex="-1"&gt;&lt;/a&gt;    &lt;span class="cf"&gt;for&lt;/span&gt; step &lt;span class="kw"&gt;in&lt;/span&gt; &lt;span class="bu"&gt;range&lt;/span&gt;(token_gen_steps):&lt;/span&gt;
&lt;span id="cb2-36"&gt;&lt;a aria-hidden="true" href="#cb2-36" tabindex="-1"&gt;&lt;/a&gt;        logits_at_step &lt;span class="op"&gt;=&lt;/span&gt; gen_logits[&lt;span class="dv"&gt;0&lt;/span&gt;][&lt;span class="dv"&gt;0&lt;/span&gt;][step]&lt;/span&gt;
&lt;span id="cb2-37"&gt;&lt;a aria-hidden="true" href="#cb2-37" tabindex="-1"&gt;&lt;/a&gt;        logits_diff.append(diff2(logits_at_step, step))&lt;/span&gt;
&lt;span id="cb2-38"&gt;&lt;a aria-hidden="true" href="#cb2-38" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb2-39"&gt;&lt;a aria-hidden="true" href="#cb2-39" tabindex="-1"&gt;&lt;/a&gt;        probs_at_step &lt;span class="op"&gt;=&lt;/span&gt; torch.softmax(logits_at_step, dim&lt;span class="op"&gt;=-&lt;/span&gt;&lt;span class="dv"&gt;1&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb2-40"&gt;&lt;a aria-hidden="true" href="#cb2-40" tabindex="-1"&gt;&lt;/a&gt;        probs_diff.append(diff2(probs_at_step, step))&lt;/span&gt;
&lt;span id="cb2-41"&gt;&lt;a aria-hidden="true" href="#cb2-41" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb2-42"&gt;&lt;a aria-hidden="true" href="#cb2-42" tabindex="-1"&gt;&lt;/a&gt;        &lt;span class="co"&gt;# When probabilities are exactly tied (which shouldn't happen in fp32):&lt;/span&gt;&lt;/span&gt;
&lt;span id="cb2-43"&gt;&lt;a aria-hidden="true" href="#cb2-43" tabindex="-1"&gt;&lt;/a&gt;        &lt;span class="cf"&gt;if&lt;/span&gt; probs_diff &lt;span class="kw"&gt;and&lt;/span&gt; probs_diff[&lt;span class="op"&gt;-&lt;/span&gt;&lt;span class="dv"&gt;1&lt;/span&gt;] &lt;span class="op"&gt;==&lt;/span&gt; &lt;span class="dv"&gt;0&lt;/span&gt;:&lt;/span&gt;
&lt;span id="cb2-44"&gt;&lt;a aria-hidden="true" href="#cb2-44" tabindex="-1"&gt;&lt;/a&gt;            past_ids &lt;span class="op"&gt;=&lt;/span&gt; torch.argmax(gen_logits[&lt;span class="dv"&gt;0&lt;/span&gt;][&lt;span class="dv"&gt;0&lt;/span&gt;], dim&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="dv"&gt;1&lt;/span&gt;)[:step]&lt;/span&gt;
&lt;span id="cb2-45"&gt;&lt;a aria-hidden="true" href="#cb2-45" tabindex="-1"&gt;&lt;/a&gt;            &lt;span class="bu"&gt;print&lt;/span&gt;(&lt;span class="ss"&gt;f"  TIE at step &lt;/span&gt;&lt;span class="sc"&gt;{&lt;/span&gt;step&lt;span class="sc"&gt;}&lt;/span&gt;&lt;span class="ss"&gt;; previous tokens: &lt;/span&gt;&lt;span class="sc"&gt;{&lt;/span&gt;past_ids&lt;span class="sc"&gt;}&lt;/span&gt;&lt;span class="ss"&gt;"&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb2-46"&gt;&lt;a aria-hidden="true" href="#cb2-46" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb2-47"&gt;&lt;a aria-hidden="true" href="#cb2-47" tabindex="-1"&gt;&lt;/a&gt;    plot(probs_diff)&lt;/span&gt;
&lt;span id="cb2-48"&gt;&lt;a aria-hidden="true" href="#cb2-48" tabindex="-1"&gt;&lt;/a&gt;    plt.legend(loc&lt;span class="op"&gt;=&lt;/span&gt;&lt;span class="st"&gt;"upper right"&lt;/span&gt;)&lt;/span&gt;
&lt;span id="cb2-49"&gt;&lt;a aria-hidden="true" href="#cb2-49" tabindex="-1"&gt;&lt;/a&gt;    plt.show()&lt;/span&gt;
&lt;span id="cb2-50"&gt;&lt;a aria-hidden="true" href="#cb2-50" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb2-51"&gt;&lt;a aria-hidden="true" href="#cb2-51" tabindex="-1"&gt;&lt;/a&gt;&lt;/span&gt;
&lt;span id="cb2-52"&gt;&lt;a aria-hidden="true" href="#cb2-52" tabindex="-1"&gt;&lt;/a&gt;&lt;span class="cf"&gt;if&lt;/span&gt; &lt;span class="va"&gt;__name__&lt;/span&gt; &lt;span class="op"&gt;==&lt;/span&gt; &lt;span class="st"&gt;"__main__"&lt;/span&gt;:&lt;/span&gt;
&lt;span id="cb2-53"&gt;&lt;a aria-hidden="true" href="#cb2-53" tabindex="-1"&gt;&lt;/a&gt;    main()&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;The script runs as
&lt;code&gt;python analyze_logits.py logits.npy&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;It computes two values per step:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;logits_diff&lt;/code&gt;&lt;/strong&gt; is the gap between the top
two raw logits. It measures the model’s confidence in raw units.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;probs_diff&lt;/code&gt;&lt;/strong&gt; is the gap between the top
two probabilities after softmax. It measures how close the step is to a
coin flip.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="reading-the-plot"&gt;Reading the plot&lt;/h2&gt;
&lt;p&gt;Most plots contain three kinds of steps. The thresholds below are
working heuristics, not fixed constants.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;High-confidence steps&lt;/strong&gt; have a &lt;code&gt;probs_diff&lt;/code&gt;
above 0.3. Greedy decoding and sampling produce the same token. On
simple prompts, a well-trained model spends most of its steps in this
range.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Borderline steps&lt;/strong&gt; have a &lt;code&gt;probs_diff&lt;/code&gt;
between 0.05 and 0.3. The model prefers one token, but sampling can
still select the second. Temperature affects the output at these
steps.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Coin-flip steps&lt;/strong&gt; have a &lt;code&gt;probs_diff&lt;/code&gt; below
0.05. The top two tokens are nearly tied, so a different hardware path
or a small numeric difference can change the sampled token. Divergence
between CPU and Neuron, or between BF16 and FP32, tends to occur at
these steps.&lt;/p&gt;
&lt;p&gt;The shape of the whole curve also characterizes the model:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;When nearly every step is high-confidence, the prompts lie well
within what the model has learned, and its outputs repeat across
runs.&lt;/li&gt;
&lt;li&gt;When coin-flip steps are frequent, sampling produces varied outputs
from run to run.&lt;/li&gt;
&lt;li&gt;A bimodal curve indicates confident early steps, constrained by the
prefix, followed by open-ended later steps.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2 id="cross-hardware-validation"&gt;Cross-hardware validation&lt;/h2&gt;
&lt;p&gt;When a Neuron model is validated against a GPU model, this analysis
identifies where divergence is expected. The relevant quantity is the
logit gap, because the numeric noise enters through the logits. Near a
logit value of 20, one BF16 ULP is 0.125. When the top-two logit gap is
within a few ULPs, the two hardware paths can rank the top two tokens
differently, and neither result is incorrect. For two nearly tied
tokens, a logit gap of 0.125 corresponds to a probability gap of at most
about 0.06, so such steps already fall in the coin-flip range.&lt;/p&gt;
&lt;p&gt;The validation procedure is as follows:&lt;/p&gt;
&lt;ol type="1"&gt;
&lt;li&gt;Run the model on GPU as the reference and dump the logits.&lt;/li&gt;
&lt;li&gt;Run the model on Neuron as the target and dump the logits.&lt;/li&gt;
&lt;li&gt;For each step, read &lt;code&gt;logits_diff&lt;/code&gt; from the reference
run.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;logits_diff&lt;/code&gt; is well above the expected logit error,
for example several BF16 ULPs at the logit’s magnitude, the tokens are
expected to match.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;logits_diff&lt;/code&gt; is within that error, a token mismatch
is acceptable.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Consider a run that diverges at step 47. If step 47 is a coin-flip
step, the divergence is expected. If step 47 is a high-confidence step,
the divergence indicates a real bug. The script distinguishes between
the two cases. The &lt;a href="https://sengopal.me/posts/a-simple-tensor-comparison-utility-for-accuracy-debugging"&gt;&lt;code&gt;compare_logits&lt;/code&gt;&lt;/a&gt;
utility complements this check by measuring how the two logit tensors
differ at a given step.&lt;/p&gt;
&lt;h2 id="probabilities-or-logits"&gt;Probabilities or logits&lt;/h2&gt;
&lt;p&gt;The analysis can use either the raw logits or the probabilities after
softmax.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The logits diff&lt;/strong&gt; is easier to compare against the
resolution of the data type. Near a logit value of 20, one BF16 ULP is
0.125, so a gap of 1.2 is well above the noise.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;The probabilities diff&lt;/strong&gt; maps directly to sampling
behavior. If the top two tokens have probabilities 0.6 and 0.4, the diff
is 0.2, and sampling at temperature 1.0 selects the second token 40% of
the time.&lt;/p&gt;
&lt;p&gt;Both values are inexpensive to compute, so the script records
both.&lt;/p&gt;
&lt;h2 id="extending-the-analysis"&gt;Extending the analysis&lt;/h2&gt;
&lt;p&gt;With &lt;code&gt;probs_diff&lt;/code&gt; available for every step, several
further analyses require only a few lines of code.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A histogram of &lt;code&gt;probs_diff&lt;/code&gt;&lt;/strong&gt; across all
steps summarizes the model’s confidence on a set of prompts. When most
of the mass lies near zero, the output depends heavily on the sampling
settings.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Per-step entropy&lt;/strong&gt;, &lt;code&gt;−Σ p log p&lt;/code&gt; over the
full distribution, captures more information than the top-two gap.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Top-K agreement between two models&lt;/strong&gt; compares the
top-K token sets from two models at each step. It provides a finer
measure of agreement than argmax alone.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Confidence after specific tokens&lt;/strong&gt; tests whether the
model becomes less confident after it produces certain tokens. This
analysis can expose systematic sampling instability.&lt;/p&gt;
&lt;h2 id="practical-notes"&gt;Practical notes&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Memory.&lt;/strong&gt; A 100-step generation with a 128k vocabulary
in FP32 occupies about 50 MB per request. Storing the dump as float16
halves this, provided the analysis tolerates the lower precision.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;MPI and multiple GPUs.&lt;/strong&gt; In a tensor-parallel model,
only rank 0 holds the gathered logits. The dump should be written from
rank 0 only, otherwise each rank writes a partial copy.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Beam search.&lt;/strong&gt; With &lt;code&gt;beam_size &amp;gt; 1&lt;/code&gt;, the
dump contains one distribution per beam. The analysis still applies, but
each beam has its own confidence curve.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Sampling parameters.&lt;/strong&gt; The dump contains the logits
before top-p, top-k and temperature are applied. The analysis can
therefore be repeated with different sampling settings without running
the model again.&lt;/p&gt;</content><category term="LLM-Inference"/><category term="neuron"/><category term="tensorrt-llm"/><category term="logits"/><category term="sampling"/><category term="debugging"/><category term="visualization"/></entry></feed>