LLMLLM inferenceKV cachedecoding

How LLMs Generate Text: Inference, KV-Cache, Decoding & Sampling Explained (2026)

How LLM inference works under the hood: autoregressive decoding, KV-cache, logits & softmax, temperature, top-p/top-k, beam search, speculative decoding and streaming.

ToolsLead TeamSeptember 7, 202613 min read
Share:
Updated Sep 7, 2026

LLM inference looks instant — but under the hood it’s 500 sequential forward passes, each attending to all previous tokens, each cached, sampled and streamed. Understanding this path explains latency, cost, temperature quirks, and why long context is expensive.

⚡ Inference in 4 Steps

  1. Prefill: Process prompt (e.g., 4K tokens) in one parallel pass, compute & cache K/V for each layer.
  2. Decode loop: For each new token: compute Q/K/V for just that token, attend to cached K/V, produce logits.
  3. Sample: Logits → softmax (with temperature/top-p) → pick next token.
  4. Repeat until EOS or length limit; stream each token to client.

Autoregressive Generation: One Token at a Time

Unlike BERT which outputs all at once, LLMs are autoregressive: token t depends on tokens 1…t-1. Pseudocode:

tokens = tokenize(prompt) // e.g., [The, cat, sat]

kv_cache = prefill(tokens) // compute K/V for prompt

for step in range(max_len):

  logits = model.forward(tokens[-1], kv_cache) // only last token

  next_id = sample(logits / temp, top_p) // decode

  if next_id == EOS: break

  tokens.append(next_id); kv_cache.append(next_id); stream(next_id)

Every step re-runs the whole 80-layer network — just with one token input plus cached history. So 500 output tokens = 500 full forward passes + 1 prefill.

KV-Cache: The 10× Speedup

Without cache, step n would recompute K/V for tokens 1…n-1 via O(n·d) per layer → total O(n²) for sequence length n. With cache, we store:

ComponentSize per token per layerTotal for 128K, 32 layers, d=4096
K2 bytes (BF16) × 4096 ≈ 8KB2 × 8KB × 32 = 512KB per token → 64GB for 128K!
V8KB

That’s why long context needs tricks:

  • GQA (Grouped-Query Attention): Share K/V heads — Llama 3 70B GQA-8 cuts cache 4× vs MHA (64GB → 16GB for 128K).
  • Quantized KV (INT8/INT4): Store K/V in 8-bit → half memory, 1–2% quality loss. Standard for 128K+ serving.
  • PagedAttention (vLLM): Store cache in non-contiguous blocks like OS virtual memory → eliminates fragmentation, enables 10× higher throughput via continuous batching.
  • Sliding window/eviction: Keep only recent 4K + sink tokens — for cheap long-context chat where old history less critical.

For “Chat with PDF” on a 40-page doc (10K tokens), cache is ~5GB in BF16, manageable. For 1M context (Gemini), cache is 500GB — sharded across 8 GPUs.

Logits → Softmax → Probabilities

Final linear head maps last hidden state h (4096-dim) → logits vector size vocab (e.g., 128K). Each logit is raw score for that token. Then:

logits = [3.2, 1.1, 0.5, -1.0, -3.4] // for tokens ["cat", "dog", "mat", "car", "zyx"]

logits_T = logits / temperature // T=0.7 sharpens, T=1.0 unchanged, T=1.5 flattens

probs = softmax(logits_T) // exp(logit)/sum(exp)

// T=0.7 → probs ≈ [0.68, 0.19, 0.09, 0.03, 0.01]

// T=1.5 → probs ≈ [0.42, 0.25, 0.18, 0.10, 0.05] // more random

This distribution is what sampling strategies operate on. The top logit isn’t always picked — that randomness creates creativity and also hallucinations.

Sampling Strategies: Temperature, Top-p, Top-k

ParamWhat it doesWhen highWhen low / 0Typical 2026 default
TemperatureScales logits before softmaxMore random, creative, diverse0 = greedy (argmax), deterministic0.7 (chat), 0.2 (code)
Top-p (nucleus)Keeps smallest set with cumulative prob ≥ pp=1.0 keeps all (no filtering)p=0.1 keeps only 1–2 tokens0.9–0.95
Top-kKeeps top k tokens onlyk=100 diversek=1 = greedyDisabled (top-p preferred)
Repetition penaltyDivides logits of already-generated tokens by penalty1.0 off, 1.2 penalizes repeats1.0 none1.0–1.1

Visual example

Prompt: “The future of AI is” → raw logits: {bright:2.8, uncertain:1.2, here:1.0, ...}

  • Greedy (T=0): always “bright” → “The future of AI is bright and will …” (safe, boring)
  • T=1.0, top-p 0.9: samples among “bright/uncertain/here/exciting” → diverse each run
  • T=0.3: sharpens “bright” to 0.85 → mostly “bright” but occasional variation

ToolsLead chat uses T≈0.7 + top-p 0.9 — balanced factuality and fluency. For AI Question Generator, we bump to 0.9 for variety.

Beam Search vs Sampling vs Greedy

MethodSearchDiversitySpeedUse in LLMs?
Greedy1 path, best token each stepNone — deterministicFastestCode, extraction
Beam (k=4)Keep 4 best sequences, pruneLowSlow (4×)Rare — translation, but not chat (LLMs prefer sampling)
Sampling (T, top-p)1 path sampledHighFastChat — almost universal
Best-of-NSample N sequences, pick best by reward modelMediumSlowReasoning (e.g., AlphaCode)

Why not beam? Beam finds higher log-probability overall but produces generic, dull text (“The future of AI is bright and promising.”). Sampling yields more human-like burstiness and is cheaper.

Streaming, Stop Tokens & Repetition Penalty

  • EOS token: Model learned to emit special <EOS> (end-of-sequence) to signal “I’m done.” Decoder stops when sampled. Max tokens is fallback.
  • Streaming: Server pushes each token via SSE/WebSocket as soon as sampled; browser appends without waiting for full response. Without streaming, 12s wait feels broken.
  • Repetition penalty: Without it, models may loop: “very very very very…”. Penalty lowers logits of already-generated tokens by 1.1×, breaking loops. For PDF Q&A, we keep penalty low (1.05) to allow quoted repetition when citing.
  • Seed + system fingerprint: With T=0 and seed fixed, same prompt gives same output (deterministic) — but across deployments, hardware non-determinism may still vary.

Speculative & Efficient Decoding

At 40 tokens/sec, 2K response = 50 seconds — too slow for chat. Tricks:

  • Speculative decoding (Google, OpenAI): Draft model (e.g., 1B) predicts 4 tokens quickly → large model verifies in one forward pass (parallel). If draft matches ~75% of the time, speed up 2–2.5× with no quality loss.
  • Continuous batching (vLLM, TensorRT-LLM): Pack many users’ decode steps into one GPU batch — utilization 80%+ vs 20% without. ToolsLead’s PDF services batch summarization jobs like this.
  • Quantized decode (AWQ, GPTQ): Store weights in INT4 → 4× less VRAM, 1.5–2× faster, <2% quality loss for 70B models. Essential for running Llama 70B on single 48GB GPU.

Latency & Cost of Long Context

ContextPrefill time (H100)KV cache (GQA, BF16)Cost per 1K tokens (input/output)
4K80ms2GB$0.005 / $0.015 (GPT-4o-mini)
32K500ms16GB$0.01 / $0.03
128K2–3s64GB (needs sharding)$0.10 / $0.30 (higher tier)

This explains why “Chat with 500-page PDF” costs 10× more: prefill is quadratic, cache huge, and decode slows because each step attends over 128K. Practical design: don’t feed whole PDF as context — use RAG (Part 5) to retrieve top chunks, not whole doc. Full-context is for tasks where every paragraph matters (legal deep-read, thesis review).

Try real-time streaming — on your PDF

Ask a complex question and watch tokens stream with citations — understanding decoding makes waiting feel shorter.

FAQs

Try these free tools mentioned in this article:

Frequently Asked Questions

What is KV-cache in LLMs?

During autoregressive generation, each step would recompute Keys and Values for all previous tokens — O(n²). KV-cache stores computed K/V per layer, so step n+1 only computes Q/K/V for the new token and reuses cached K/V for history. It cuts generation from quadratic to linear and gives 10-20× speedup. Memory cost is 2 × layers × n × d_head per sequence.

Open Chat with PDF

What does temperature do in LLM?

Temperature T scales logits before softmax: P ∝ exp(logit/T). T=0 (greedy) picks highest logit's token always — deterministic, repetitive. T=0.7-1.0 smooths distribution — more diverse, creative. T>1.5 becomes incoherent. Code generation often uses T=0.2; creative writing uses T=0.8-1.0; ToolsLead chat uses ~0.7 balanced.

Open Chat with PDF

Top-p vs top-k — difference?

Top-k keeps only the top k tokens (e.g., k=40) then renormalizes. Top-p (nucleus) keeps smallest set whose cumulative probability ≥ p (e.g., p=0.9) — dynamic k per step based on uncertainty. Top-p adapts better: when model is confident ("2+2=" → '4' with 0.95 prob), it keeps 1 token; when uncertain (poem start), it keeps many. Most 2026 APIs default to top-p 0.9-0.95 and disable top-k.

Open Chat with PDF

Why do LLMs stream token-by-token?

Because generating 500 tokens at 40 tokens/sec takes 12.5 seconds — users would stare at blank screen. Streaming emits each token as produced (via server-sent events), so you see first word in ~200ms and read as it generates, improving perceived latency 10×.

Open Chat with PDF

What is speculative decoding?

Use a small draft model (e.g., 1B) to predict 3-5 tokens ahead, then run the large model once to verify them in parallel. If draft is correct (70-80% of time), you generate 3 tokens for cost of ~1 large forward pass — 2-3× faster. Used in GPT-4o, Gemini for interactive latency.

Open Chat with PDF

Was this article helpful?

T

About ToolsLead Team

ToolsLead is a privacy-first PDF platform. Most tools run in your browser — your files never leave your device. For heavy tasks we use encrypted, auto-deleted server processing. No signup required for basic tools.

Browse all PDF tools