Inference

1. Inference 101

  • Terminology and definitions
    • TTFT — Time to First Token: time until the first output token; prefill typically dominates the model computation here. Prefill relies on large GEMMs (general matrix–matrix multiplications) over all prompt-token rows.
      • Prefill is usually compute-bound.
    • TPOT — Time Per Output Token: time between consecutive generated tokens after the first; the one-row decode computation and KV-cache reads dominate it.
      • Decode is usually memory-bound.
    • Latency: end-to-end response time to complete a single request.
    • Throughput: how many tokens or requests we can process per unit time across all requests, measured in tokens/second or requests/second.

2. Batch and packing

  • Batching: send multiple users’ requests to the GPU together to improve GPU utilization and throughput. Decides which requests are computed together.
    • traditional batching: collect \(N\) requests, process them together, wait for all to finish, then collect the next batch
      • if one sequence generates 500 tokens and another generates 10, the short one sits idle waiting
    • continuous batching: as soon as one sequence finishes, you immediately slot a new request into its place without waiting for the whole batch
      • the batch is always full
    • selective batching: cleverly mix sequences that are in prefill and generation phase
      • idea: prefill is compute-heavy whereas decode is memory-bound
    • token-budget batching: batch examples into batches such that the total number of tokens in a batch (after padding to the max seqlen within that batch) does not exceed a certain budget
      • usually done in finetuning
      • this makes sense because GPU memory is determined by batch_size x sequence_length
  • Packing: arrange variable-length requests compactly to minimize unused padding tokens, reducing wasted GPU computation and memory. Decides how the requests’ tokens are laid out.
    • Sequence packing: concatenate examples up to the maximum sequence length, using causal masks and request boundaries to prevent cross-request attention.
    • Causal attention with packed request boundariesRequest A occupies positions 0–3, B occupies 4–5, and C occupies 6–8. Tokens can attend only to earlier positions and themselves within the same request.Key positions →001122334455667788ABCCausal + request boundaries
      Green cells allow query–key interactions. Packed requests stay logically independent, even when their tokens are physically adjacent.

3. Sampling and decoding

  • Sampling strategies
    • The Transformer and LM Head produce vocabulary logits \(z=[z_1,z_2,\ldots,z_V]\). Softmax converts them into probabilities: \(\boxed{p_i=\frac{e^{z_i}}{\sum_j e^{z_j}}}\).
    • Greedy decoding: always select the highest-probability token: \(\boxed{x_{t+1}=\arg\max_i p_i}\).
    • Multinomial sampling: randomly draw a token according to its probability: \(\boxed{x_{t+1}\sim\operatorname{Categorical}(p)}\).
      • \(\sim\) means “sample from a probability distribution.”
    • Temperature sampling: control how sharp the probability distribution is: \(\boxed{p_i(T)=\frac{e^{z_i/T}}{\sum_j e^{z_j/T}}}\), where \(T\) is the temperature.
      • T=1: keep the original probability distribution.
      • 0<T<1: amplify relative logit differences, making probabilities more concentrated.
      • T>1: reduce relative differences, making probabilities more uniform.
      • \(T\to0^+\): approach greedy decoding. Actual code must never divide by zero.
    • Top-k sampling: keep only the \(k\) highest-probability tokens, renormalize their probabilities, then sample randomly.
    • Top-p / nucleus sampling: sort tokens by probability, retain the smallest prefix whose cumulative probability reaches the threshold \(p\), then renormalize and sample.
    • Typical LLM sampling pipeline: \(\boxed{\text{Logits}\rightarrow\text{Temperature}\rightarrow\text{Top-k/Top-p}\rightarrow\text{Renormalize}\rightarrow\text{Sample}}\).
      • Temperature, top-k, and top-p can be combined.
    • Next-token distribution comparison

      Each row shows the final selection probabilities. Multinomial sampling uses the original distribution.

      Next-token distribution comparisonCompare the original softmax distribution, greedy selection, temperatures 0.5 and 2, top-k 2, and top-p 0.8. Grey cells are excluded from sampling.catsdogspizzamusicyouOriginal40%30%15%10%5%Greedy100%0%0%0%0%Temp 0.556.1%31.6%7.9%3.5%0.9%Temp 2.030%26%18.4%15%10.6%Top-k = 257.1%42.9%0%0%0%Top-p = .847.1%35.3%17.6%0%0%Grey = excluded from sampling
  • Decoding strategies
    • Speculative decoding: optimize generation speed, rather than improve the target model’s quality.
      • A fast Draft Model proposes several tokens for successive future positions, not just one token for the next position.
      • The Target Model uses causal attention to compute the conditional probabilities of these candidate positions in parallel in one larger forward pass.
      • Verify draft tokens in order.
        • In speculative sampling, the draft probability is \(q(y)\) and the target probability is \(p(y)\); the acceptance probability is \(\boxed{P(\mathrm{accept}\ y)=\min\left(1,\frac{p(y)}{q(y)}\right)}\).
      • Accept the consecutive valid prefix; at the first rejected token, sample a corrected replacement, then continue with the next round.
      • more context
        • speculative decoding exploits the fact that prefill is faster than generation
        • generate \(K\) tokens from draft model \(q\)
        • evaluate those tokens with target model \(p\)
          • accept each draft token \(x\) with probability \(\min\left(1,\frac{p(x)}{q(x)}\right)\)

            • if \(p(x)>q(x)\), we definitely take it
          • if rejected, sample from adjusted distribution \(\max(0, p(x)-q(x))\) after renormalization

            • starting at the first rejected token
          • if all draft tokens are accepted, sample one bonus token from the target model; otherwise sample a replacement from the adjusted distribution at the first rejection

        • P(emitting token \(x\)) = P(draft \(x\)) * P(accept \(x\)) + P(sampled token rejected) * P(sample \(x\))
          • case 1 (first term): \(x\) is accepted from the draft \(q(x)\cdot\min\left(1,\frac{p(x)}{q(x)}\right)=\min(q(x),p(x))\)
          • case 2 (second term): \(x\) is chosen after rejection
            • probability of drafting and rejecting a draft token \(x'\):

              • 0 if \(p(x')>q(x')\)
              • otherwise \(q(x')\cdot\left(1-\frac{p(x')}{q(x')}\right)=q(x')-p(x')\)
            • so the total probability of rejection is \(P(\text{rejection})=\sum_{x'}\max(0,q(x')-p(x')) =\sum_{x'}\max(0,p(x')-q(x'))\)

              • the second step follows bc both \(p\) and \(q\) sum to 1
            • when we reject, we sample from \(\frac{\max(0,p(x)-q(x))}{\sum_{x'}\max(0,p(x')-q(x'))}\)

            • so the probably of getting \(x\) after rejection is \(\sum_{x'}\max(0,p(x')-q(x'))\cdot \frac{\max(0,p(x)-q(x))}{\sum_{x'}\max(0,p(x')-q(x'))}=\max(0,p(x)-q(x))\)

          • combining both cases \(\min(q(x),p(x))+\max(0,p(x)-q(x))=p(x)\)

4. KV cache

  • 1 · Project only the live token: at step t=4, compute q₄, k₄, and v₄. Earlier queries are finished, so only q₄ is live.
  • 2 · Append one row: add k₄ and v₄ beneath the three cached rows. K_cache and V_cache grow from (3,H) to (4,H) while their column width H stays fixed.
  • 3 · Score the history: \(\operatorname{scores}_4=q_4K_{cache}^{\top}:\quad(1,H)(H,4)\rightarrow(1,4)\). The four score cells correspond to keys k₁…k₄; the first three key rows are reused directly from cache.
  • 4 · Mix the cached values: \(a_4=\operatorname{softmax}(\operatorname{scores}_4),\qquad o_4=a_4V_{cache}:\quad(1,4)(4,H)\rightarrow(1,H)\). The same four weights select information from value rows v₁…v₄. Past V rows are therefore cached along with K; past Q rows are never reused.
  • KV-cache memory: \(M_{KV}=2\times B\times L\times N\times T\times H\times\text{bytes}\).
    \(M_{KV}\): cache memory; \(2\): K + V; \(B\): batch size; \(L\): layers; \(N\): KV heads; \(T\): cached tokens; \(H\): head dimension; \(\text{bytes}\): bytes/scalar.
KV cache · PyTorch implementation
import torch
import torch.nn.functional as F

# 沿用原来的逐 token 示例,只演示 MHA 的 cache 路径;省略 norm、RoPE、残差。
# model 提供 embed、layers、lm_head;每层提供 qkv_proj 和 ffn。
# qkv_proj: D -> 3D;num_heads * head_dim = D。
# GQA 的 K/V heads 更少,需要分别投影,不能直接 chunk 成相同宽度。

def create_kv_cache(batch, num_layers, num_heads, max_seq_len, head_dim,
                    device, dtype):
    # torch.zeros(*shape) 创建指定形状的全 0 tensor。
    # torch.zeros(1, 2, 3, 4).shape == (1, 2, 3, 4)。
    # device 决定 CPU/GPU;dtype 决定精度和每个数的字节数。
    # 例如 device='cuda', dtype=torch.float16:GPU 上每个数占 2 bytes。
    # 每层独立创建 K/V,避免多个层共享同一个 tensor。
    return [
        {
            'k': torch.zeros(batch, num_heads, max_seq_len, head_dim,
                             device=device, dtype=dtype),
            'v': torch.zeros(batch, num_heads, max_seq_len, head_dim,
                             device=device, dtype=dtype),
        }
        for _ in range(num_layers)
    ]


# inference_mode 关闭 autograd 和相关记录,适合推理,减少额外开销。
# 它不会关闭 dropout;推理前仍要调用 model.eval()。
@torch.inference_mode()
def forward_with_cache(model, new_token, kv_cache, position, num_heads):
    # position 从 0 开始;此前的 cache 行必须已经写入,可来自 prefill。
    # 这里只处理一个新 token,new_token: [B, 1],且是整数 token IDs。
    # embed 按 ID 查向量:若词表矩阵为 [V, D],输入 [B, 1] -> [B, 1, D]。
    x = model.embed(new_token)
    B, S, D = x.shape  # S = 1
    H = D // num_heads

    for layer_idx, layer in enumerate(model.layers):
        # chunk(3, dim=-1):沿最后一维尽量均分成 3 块;这里 3D 恰好均分。
        # torch.tensor([1, 2, 3, 4, 5, 6]).chunk(3)
        # -> (tensor([1, 2]), tensor([3, 4]), tensor([5, 6]))。
        # [B, 1, 3D] -> 三个 [B, 1, D] tensors。
        q, k, v = layer.qkv_proj(x).chunk(3, dim=-1)

        # view(B, S, num_heads, H):不改变元素,把最后的 D 拆成 heads 和 H。
        # [1, 1, 8] -> [1, 1, 4, 2];view 要求原 tensor 的 stride 兼容。
        # transpose(1, 2) 交换 token 和 head 维度:
        # [B, S, num_heads, H] -> [B, num_heads, S, H]。
        q = q.view(B, S, num_heads, H).transpose(1, 2)
        k = k.view(B, S, num_heads, H).transpose(1, 2)
        v = v.view(B, S, num_heads, H).transpose(1, 2)

        # squeeze(2) 只去掉第 2 维上长度为 1 的维度:
        # [1, 4, 1, 2] -> [1, 4, 2];若该维不是 1,就不会删除。
        # 不用 squeeze(),否则 batch=1 时连 batch 维也会被删掉。
        # [:, :, position, :] 选中所有 batches/heads 在 position 的那一行。
        # position=3 时写第 4 行,其余历史行保持原值;预分配避免每步拼接。
        kv_cache[layer_idx]['k'][:, :, position, :] = k.squeeze(2)
        kv_cache[layer_idx]['v'][:, :, position, :] = v.squeeze(2)

        # :position+1 是左闭右开切片:position=3 时取索引 0、1、2、3。
        # [B, num_heads, max_seq_len, H] -> [B, num_heads, position+1, H]。
        # 只读已写入的前缀,后面的预分配 0 不参与 attention。
        k_full = kv_cache[layer_idx]['k'][:, :, :position+1, :]
        v_full = kv_cache[layer_idx]['v'][:, :, :position+1, :]

        # scaled_dot_product_attention(q, k, v) 等价于:
        # softmax((q @ k.transpose(-2, -1)) / sqrt(H)) @ v。
        # 例如 q=[1,4,1,2],K/V=[1,4,4,2],输出=[1,4,1,2]。
        # dropout_p=0.0:推理时不随机丢弃 attention weights。
        # is_causal=False:这里唯一的 query 是最新 token,前缀全都允许看。
        # 不能直接设 True:非方形 causal mask 会按左上角对齐,错误屏蔽历史。
        out = F.scaled_dot_product_attention(
            q, k_full, v_full, dropout_p=0.0, is_causal=False,
        )

        # transpose 换回 [B, S, num_heads, H]。
        # contiguous() 按当前维度顺序连续存储,之后才能安全地 view。
        # view(B, S, D) 把每个 token 的各个 head 拼回一个 D 维向量。
        # [1, 4, 1, 2] -> [1, 1, 4, 2] -> [1, 1, 8]。
        x = out.transpose(1, 2).contiguous().view(B, S, D)
        x = layer.ffn(x)

    # [B, 1, D] -> [B, 1, V],供下一步选择 token;cache 已原地更新。
    return model.lm_head(x)

5. Reducing KV cache

  • Attention Architecture
    • Reduces: \(N\) (KV heads).
    • in standard multi-head attention (MHA) transformer attention, KV cache scales as num_layers × num_heads × seq_len × head_dim × 2 (K and V)
    • in multi-query attention (MQA), all heads share the same K and V, but each head has its own Q
      • KV cache shrinks by a factor of num_heads
      • inference is much faster and more memory-efficient
    • in group-query attention (GQA), heads are divided into groups, each group shares K and V
      • middle ground between MHA and MQA
    • MQA and GQA shares KV across heads, so we lose some representational capacity per head
    • multi-head latent attention (MLA) introduced in DeepSeek v2
      • instead of keeping keys and values with shape (seq_len, num_heads × head_dim) in the KV cache, cache a smaller latent vector (seq_len, latent_dim)
      • then at each decoding step, project the latent KVs back up to full size
    • MLA keeps a separate KV per head but compresses them into a shared latent space
      • adds some extra compute at inference time (the projection from latent to KV)
      • standard RoPE complicates MLA matrix absorption; DeepSeek uses decoupled RoPE with a separate positional key component to make them compatible
    KV cache architectures
  • Cross-layer attention
    • Reduces: effective \(L\) (cached layers).
    • Multiple attention layers share the same cached keys and values instead of storing a separate K/V cache for every layer.
  • Local attention
    • Reduces: \(T\) (cached tokens).
    • Each token attends only to a recent window instead of the entire history. In sliding-window layers, K/V entries outside the active window can be evicted from the cache.
  • KV quantization
    • Reduces: \(\text{bytes}\) (bytes per scalar).
    • Store cached keys and values at lower precision, such as INT8 or INT4 instead of BF16/FP16. Quantization scales let attention recover approximate values, trading some precision and scale metadata for a smaller cache.
  • PagedAttention
    • Reduces: no parameter directly; reduces allocation waste and fragmentation rather than the logical KV-cache size.
    • Divide each request’s KV cache into fixed-size blocks, with a block table mapping logical token positions to physical memory. Blocks can occupy non-contiguous GPU memory and be allocated as generation grows, reducing reserved-but-unused space and fragmentation.
Implementation · GQA attention with KV cache
def repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
    """
    Repeat each Key/Value head so GQA can match the number of Query heads.

    GQA projects fewer K/V heads than Q heads. For example, with 8 Query
    heads and 2 K/V heads, n_rep = 8 // 2 = 4: K/V head 0 serves Query
    heads 0..3, and K/V head 1 serves Query heads 4..7.

    Keeping only num_kv_heads in the persistent KV cache is the memory win.
    This helper expands those compact heads only when attention needs a
    head-aligned K/V tensor.

    Args:
        x: Key or Value tensor shaped
           [batch, seq_len, num_kv_heads, head_dim].
        n_rep: Number of Query heads served by each K/V head:
               num_attention_heads // num_kv_heads.

    Returns:
        Tensor shaped [batch, seq_len, num_attention_heads, head_dim].
    """
    bs, slen, num_key_value_heads, head_dim = x.shape

    # MHA has one K/V head per Query head, so no broadcasting is necessary.
    if n_rep == 1:
        return x

    # PyTorch shape trace, using 2 K/V heads and n_rep=4 as an example:
    # [B, L, 2, D]
    #   -> index None / unsqueeze(3): [B, L, 2, 1, D]
    #   -> expand:                   [B, L, 2, 4, D]
    #   -> reshape:                  [B, L, 8, D]
    #
    # x[:, :, :, None, :] inserts a singleton replica axis after the K/V-head
    # axis. It is equivalent to x.unsqueeze(3) and does not copy tensor data.
    #
    # expand(..., n_rep, ...) broadcasts that size-1 axis to n_rep. In
    # PyTorch, expand returns a view with stride 0 on the replica axis: all
    # replicas initially refer to the same underlying K/V values, so expand
    # itself does not allocate or physically duplicate the data. Avoid
    # in-place writes on this expanded view because several logical elements
    # alias the same storage.
    #
    # reshape(...) then merges [num_kv_heads, n_rep] into one head axis. The
    # ordering becomes [kv0, kv0, ..., kv1, kv1, ...], which aligns each
    # contiguous Query-head group with its shared K/V head. Because the input
    # contains a stride-0 expanded dimension, this merge usually cannot remain
    # a simple view; reshape is allowed to materialize a contiguous repeated
    # tensor. This is why reshape works where view(...) may fail on the
    # non-contiguous expanded layout. The persistent cache is still compact;
    # the possible materialization happens only for the attention operation.
    return (
        x[:, :, :, None, :]  # [B, L, num_kv_heads, 1, head_dim]
        .expand(
            bs,
            slen,
            num_key_value_heads,
            n_rep,
            head_dim,
        )  # broadcast view: [B, L, num_kv_heads, n_rep, head_dim]
        .reshape(
            bs,
            slen,
            num_key_value_heads * n_rep,
            head_dim,
        )  # merged head axis: [B, L, num_attention_heads, head_dim]
    )


class Attention(nn.Module):
    """
    Multi-head causal self-attention with GQA, RoPE, KV cache, and an SDPA fast path.

    Attention(Q, K, V) = softmax(QK^T / sqrt(head_dim)) V
    """

    def __init__(self, args: MiniMindConfig):
        super().__init__()

        # ---------- GQA configuration ----------
        # If num_key_value_heads is absent, fall back to MHA: one K/V head per Q head.
        self.num_key_value_heads = (
            args.num_attention_heads
            if args.num_key_value_heads is None
            else args.num_key_value_heads
        )
        assert args.num_attention_heads % self.num_key_value_heads == 0

        self.n_local_heads = args.num_attention_heads
        self.n_local_kv_heads = self.num_key_value_heads
        self.n_rep = self.n_local_heads // self.n_local_kv_heads
        self.head_dim = args.hidden_size // args.num_attention_heads

        # ---------- Q/K/V and output projections ----------
        # Q keeps every attention head; K and V project only num_kv_heads for GQA.
        self.q_proj = nn.Linear(
            args.hidden_size,
            args.num_attention_heads * self.head_dim,
            bias=False,
        )
        self.k_proj = nn.Linear(
            args.hidden_size,
            self.num_key_value_heads * self.head_dim,
            bias=False,
        )
        self.v_proj = nn.Linear(
            args.hidden_size,
            self.num_key_value_heads * self.head_dim,
            bias=False,
        )
        self.o_proj = nn.Linear(
            args.num_attention_heads * self.head_dim,
            args.hidden_size,
            bias=False,
        )

        self.attn_dropout = nn.Dropout(args.dropout)
        self.resid_dropout = nn.Dropout(args.dropout)
        self.dropout = args.dropout

        # PyTorch 2.x exposes fused scaled-dot-product attention through SDPA.
        self.flash = (
            hasattr(torch.nn.functional, "scaled_dot_product_attention")
            and args.flash_attn
        )

    def forward(
        self,
        x: torch.Tensor,
        position_embeddings: Tuple[torch.Tensor, torch.Tensor],
        past_key_value: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
        use_cache=False,
        attention_mask: Optional[torch.Tensor] = None,
    ):
        """
        Args:
            x: [batch, seq_len, hidden_size].
            position_embeddings: RoPE (cos, sin) tensors.
            past_key_value: Cached K/V tensors shaped
                [batch, past_len, num_kv_heads, head_dim].
            use_cache: Return the updated compact K/V cache when True.
            attention_mask: [batch, seq_len], where 1 is valid and 0 is masked.

        Returns:
            output: [batch, seq_len, hidden_size].
            past_kv: Updated compact K/V cache, or None.
        """
        bsz, seq_len, _ = x.shape

        # ---------- 1. Project Q, K, and V ----------
        xq, xk, xv = self.q_proj(x), self.k_proj(x), self.v_proj(x)

        # Q uses all Query heads; K/V retain only the smaller GQA head count.
        xq = xq.view(bsz, seq_len, self.n_local_heads, self.head_dim)
        xk = xk.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)
        xv = xv.view(bsz, seq_len, self.n_local_kv_heads, self.head_dim)

        # ---------- 2. Apply RoPE to Q and K ----------
        cos, sin = position_embeddings
        xq, xk = apply_rotary_pos_emb(xq, xk, cos, sin)

        # ---------- 3. Append the compact KV cache ----------
        if past_key_value is not None:
            # Concatenate along sequence length; the K/V-head axis stays compact.
            # Result: [batch, past_len + seq_len, num_kv_heads, head_dim].
            xk = torch.cat([past_key_value[0], xk], dim=1)
            xv = torch.cat([past_key_value[1], xv], dim=1)

        # Save before repeat_kv so the persistent cache stores only num_kv_heads.
        past_kv = (xk, xv) if use_cache else None

        # ---------- 4. Align K/V heads with Query heads ----------
        # Attention kernels expect [batch, heads, sequence, head_dim].
        xq = xq.transpose(1, 2)
        xk = repeat_kv(xk, self.n_rep).transpose(1, 2)
        xv = repeat_kv(xv, self.n_rep).transpose(1, 2)

        # ---------- 5. Compute causal attention ----------
        # Use fused PyTorch SDPA for full-sequence causal attention when no cache
        # or nontrivial mask requires the explicit path below.
        if (
            self.flash
            and seq_len > 1
            and past_key_value is None
            and (attention_mask is None or torch.all(attention_mask == 1))
        ):
            output = F.scaled_dot_product_attention(
                xq,
                xk,
                xv,
                dropout_p=self.dropout if self.training else 0.0,
                is_causal=True,
            )
        else:
            # 5.1 Scaled QK^T scores:
            # [B, H, query_len, D] @ [B, H, D, kv_len]
            # -> [B, H, query_len, kv_len].
            scores = (xq @ xk.transpose(-2, -1)) / math.sqrt(self.head_dim)

            # 5.2 Apply a causal mask to the current sequence portion. Cached
            # history remains visible; only future positions in the live block
            # receive -inf before softmax.
            scores[:, :, :, -seq_len:] += torch.triu(
                torch.full(
                    (seq_len, seq_len),
                    float("-inf"),
                    device=scores.device,
                ),
                diagonal=1,
            )

            # 5.3 Convert a 1/0 token mask into additive score bias.
            if attention_mask is not None:
                extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
                extended_attention_mask = (1.0 - extended_attention_mask) * -1e9
                scores = scores + extended_attention_mask

            # 5.4 Compute softmax in FP32 for stability, then restore Q's dtype.
            scores = F.softmax(scores.float(), dim=-1).type_as(xq)

            # 5.5 Drop attention probabilities only during training.
            scores = self.attn_dropout(scores)

            # 5.6 Weighted value sum -> [batch, heads, query_len, head_dim].
            output = scores @ xv

        # ---------- 6. Merge heads and project to hidden_size ----------
        output = output.transpose(1, 2).reshape(bsz, seq_len, -1)
        output = self.resid_dropout(self.o_proj(output))

        return output, past_kv