24  The Treat Dispenser at Scale

Inference, vLLM, and PagedAttention

⏳ 2026 Edition: Last verified: 2026-02-24

Prerequisites: Chapter 23

Technical Keywords: Inference at Scale, Continuous Batching, PagedAttention, vLLM Architecture, Speculative Decoding, KV Cache Compression, Quantization, Temperature


🧭 Advanced Track Navigation Core Track completion is defined by Checkpoints 1-4. This chapter belongs to the Advanced Track. Safe to skim on first pass; not required for checkpoints.

Pixel is fully trained. The 10,000 GPUs have done their job. You hit “Save.” Now you launch your startup, KittenGPT, and deploy Pixel to the internet.

On day one, 5,000 humans log on and ask Pixel a question at the exact same millisecond.

Training is hard, but Inference (generating text for users) is a brutal, high-speed logistical nightmare. If you process users one by one, user #5,000 will have to wait 3 hours for their poem. If you try to process them all at once, the GPU memory explodes.

We need a hyper-efficient treat dispenser.


24.1 Continuous Batching: The Revolving Door

In Chapter 3, we learned about Mini-batches. We process 32 images at once. But LLMs generate text one word at a time (Autoregressive).

User A asks: “Say hello.” (Outputs 1 word). User B asks: “Write a 500-page book.” (Outputs 100,000 words).

If we batch User A and User B together, the GPU has to wait for the 500-page book to finish before it can clear the batch and let User C into the system! User A’s spot sits completely empty and wasted for hours.

Modern servers use Continuous Batching (In-Flight Batching). Instead of waiting for the entire prompt to finish, the GPU evaluates generation word by word. The exact millisecond User A’s “hello” is finished, the GPU ejects User A and slots User C into the batch for the very next mathematical step. The GPU is never idle.


24.2 PagedAttention (vLLM): The Restaurant Seating Chart

Remember the KV Cache from Chapter 12? It saves the “scent” of previous tokens (both the input prompt and generated output) so the model doesn’t have to recalculate them.

For 5,000 concurrent users, the KV Cache is absolutely massive. Historically, when a user asked a question, the server would pre-allocate a massive, continuous block of GPU RAM just in case the user generated a long story. But if the user only generated 5 tokens, 99% of that RAM was wasted. The server would crash from Memory Fragmentation.

Researchers invented PagedAttention (the core of the open-source vLLM engine) (Kwon et al., 2023). It works exactly like memory paging in a computer’s OS. Instead of reserving a massive table for a user, PagedAttention chops the KV Cache into tiny “blocks” (pages) of 16 tokens that hold both prompt tokens and newly generated tokens. As a request fills 16 tokens, it is dynamically assigned one tiny block of memory wherever it fits; on the 17th token, it gets a second block.

This completely eliminates memory waste, allowing a single GPU to serve 4\times to 20\times more users simultaneously!


24.3 Speculative Decoding: The Fast Guess

Generating tokens one by one is limited by Memory Bandwidth (how fast the GPU can move the 70B weights from its RAM to its compute cores). The compute cores are actually sitting idle 90% of the time, just waiting for the heavy weights to arrive!

How do we speed this up? Speculative Decoding (Leviathan et al., 2023).

  1. We put a tiny, stupid, ultra-fast 1-Billion parameter kitten next to the massive 70-Billion parameter lion.
  2. The tiny kitten rapidly guesses the next 5 tokens: “The cat sat on the”
  3. The massive lion takes those 5 draft tokens and runs a single parallel Forward Pass to check the math.
  4. The massive lion (the primary model) verifies the math: “Yes, those are the exact 5 tokens I would have calculated.”

Because verifying 5 draft tokens in a single parallel pass loads the massive weights once rather than 5 times, it can be far more efficient than 5 separate autoregressive decoding steps (with actual speedup depending on how many draft tokens get accepted and hardware overhead)! If the tiny kitten guesses wrong on token 3, the lion rejects it, fixes token 3, and throws away the rest.

Diagram showing speculative decoding flow

Speculative Decoding — tiny model drafts, big model verifies.

24.4 Quantization: Shrinking the Lion

If you want to run Llama 3 on your MacBook, you don’t have 140 GB of RAM.

You use Quantization. Neural network weights are normally stored in FP16 (16-bit floating point, meaning 16 zeroes and ones are used to store a decimal with ~3–4 significant digits, such as 0.1235).

Quantization aggressively rounds the math down to INT8 (8-bit) or even INT4 (4-bit).

  • In FP16, the network uses ~65k bit patterns (63,487 finite numeric values, giving ~3–4 significant digits like 0.1235) to represent each weight.
  • In INT8, we map those weights onto just 256 integer levels paired with a scaling factor (then dequantize back during matrix computation)!
  • We lose mathematical precision, but because we need fewer bits to store each weight, memory drops dramatically: a 70B model is roughly ~140GB in FP16/BF16, ~70GB in INT8, and ~35GB in INT4 (weights-only rough math, ignoring extra metadata/overheads).

When should you use which?

  • FP16 / BF16 (16-bit): Use this for Training and Cloud Inference. If you have the massive GPU budget, keep the precision for the highest fidelity.
  • INT8 (8-bit): Use this for standard Inference when you need speed and efficiency, often with minimal quality loss for many workloads (but not universally zero loss).
  • INT4 (4-bit): Use this for Edge Devices (MacBooks, Phones). The model becomes incredibly fast and cheap, but might struggle with highly complex math or coding logic due to rounding errors.

24.5 Temperature: The Drunk vs Sober Kitten

When an LLM outputs probabilities for the next token (via Softmax), you control how it samples those probabilities using Temperature (T, where T = 1.0 leaves the model’s raw probabilities unchanged).

  • Low Temperature (T = 0.1): The Sober Accountant. Sharpening the distribution makes the model almost exclusively pick the highest-probability token. Sampling becomes highly concentrated and low-variance (unlike strict greedy decoding, which is truly deterministic), yet not inherently more factual (a confident mistake stays confidently wrong). Good for coding or math.
  • Higher Temperature (T = 0.9, or > 1.0): The Drunk Poet. Compared with T = 0.1, T = 0.9 sits close to unscaled sampling (T = 1.0) and preserves far more diversity—while pushing T > 1.0 flattens the distribution even further, giving lower-ranked tokens a higher chance of being chosen. Output becomes more varied, unpredictable, and creative (with higher risk of off-track generations). Good for brainstorming or fantasy stories.

Rosetta Stone

Kitten World Math/Concept Engineering Impact
“Kick the user out immediately when done” Continuous Batching Maximizes GPU utilization.
“Tiny tables instead of one massive table” PagedAttention (vLLM) Eliminates KV Cache fragmentation; massive throughput increase.
“Tiny kitten guesses, Lion verifies” Speculative Decoding Bypasses the memory-bandwidth bottleneck to increase speed.
“Violently round the decimals” Quantization (GGUF/AWQ) Fits a massive model on a laptop.

24.6 Removing the Training Wheels

The Real Engineering

We talked about continuous batching and the treat dispenser. In production LLM inference, memory bandwidth (reading weights from HBM to SRAM) is the primary bottleneck, not compute (FLOPs). Continuous Batching operates at the token level, evicting finished requests immediately. PagedAttention eliminates memory fragmentation by allocating KV cache in non-contiguous OS-like pages. Quantization maps FP16 weights down to INT8 or INT4, trading slight quantization error for massive reductions in memory bandwidth requirements and VRAM footprint.

24.7 Paws and Reflect: Chapter 24 Quiz

1. You are running a standard batching server. User A generates 5 words. User B generates 2,000 words. How long does User C have to wait in the queue before their prompt starts processing? User C has to wait for User B’s entire 2,000-word generation to finish before the batch clears! Continuous Batching fixes this by swapping User A out for User C immediately.
2. Why did early LLM servers run out of memory even if the actual generated text was short? What vLLM feature fixed this? Because they pre-allocated massive, contiguous blocks of RAM for the KV Cache “just in case.” PagedAttention fixed this by dynamically allocating tiny, non-contiguous blocks (pages) on demand as prompt and generated tokens are stored.
3. In Speculative Decoding, if the tiny 1B model guesses the next 3 tokens wrong, does the final output provided to the user suffer in quality? No! The quality is identical to the massive Lion. The Lion verifies every single guess. If the guess is wrong, the Lion overwrites it with its own exact distribution. The only penalty is speed (a wasted guess), not quality.

24.8 Chapter 24 Summary

You’ve learned the high-speed logistics of running AI in production:

  • The Autoregressive Bottleneck: Generating one token at a time is constrained by memory bandwidth, not raw compute.
  • Continuous Batching: Dynamically swapping users in and out of the GPU step-by-step to keep utilization high.
  • PagedAttention (vLLM): Solving the massive KV Cache memory crisis by borrowing “paging” architecture from Operating Systems.
  • Speculative Decoding: Using a tiny “draft” model to guess tokens ahead of time, allowing the massive model to verify them in parallel.
  • Quantization: Rounding the decimal weights down to 8-bit or 4-bit to drastically shrink memory requirements for edge deployment.

AI Safety Thread: Chapter 24

The Economics of Unsafe Deployment: Alignment (Phase V) is mathematically fragile. If you aggressively Quantize a model down to 4-bit to save money on server costs, the subtle decimal weights that encode the “Safety Guardrails” can degrade under rounding error. A polite, helpful FP16 model may become easier to jailbreak or less reliable on safety behavior when quantized to INT4 in some settings. Furthermore, running advanced safety checks (like OOD detection) costs extra FLOPs, increasing latency. In the race for the fastest, cheapest API, some organizations may face incentives to reduce costly safeguards.


🛑 CHECKPOINT 6: Frontier Engineering

You have built a solid foundation in the physical reality of Machine Learning. You can size a cluster, distribute a workload, and reason about serving thousands of concurrent users.

Readiness at this checkpoint is for educational progression only, not professional certification or authorization for high-risk deployment.

You are no longer just a mathematician. You are an AI Systems Engineer.

The Rules of this Checkpoint:

  • You must understand the difference between Compute (FLOPs) and Memory (VRAM) bottlenecks.
  • You must be able to match the correct parallelism strategy to the correct hardware constraint.

Conceptual Evaluation: 1. The Budget: You have a 10-Billion parameter model and 100 Billion tokens of data. According to Chinchilla scaling laws, is this model Compute-Optimal, Data-Constrained, or Over-Trained? (Answer: Data-Constrained. A 10B model needs 200B tokens (20N) to be optimal. You don’t have enough books for the kitten) 2. The Network Cable: You have 8 GPUs in Server A, and 8 GPUs in Server B, connected by a standard ethernet cable. You need to split a massive Transformer. Should you use Tensor Parallelism between Server A and Server B? (Answer: Absolutely not. Tensor Parallelism requires massive, constant communication. The slow ethernet cable will cause a fatal bottleneck. You should use Pipeline Parallelism across the servers) 3. The Fast Lion: How does Speculative Decoding increase generation speed without changing the weights of the primary model? (Answer: By turning sequential autoregressive steps into parallel verification of draft tokens—loading the massive weights once to verify several tokens can be far more efficient than separate single-token decoding steps)

When you can reason through these checks, continue to the integration and simulator capstone phase.

✅ Readiness Check

Use the corresponding checkpoint notebook in appendix-repo as a self-check before proceeding. Note: Passing a checkpoint means you have the core conceptual competency for the next phase; it does not imply professional deployment readiness.


You have built the math, trained the lion, aligned its soul, and built the warehouse to house it. In our final Phase, we will put it all together. We will learn how to build GenAI pipelines, manage MLOps, and execute a Capstone project. It is time to let the cat outside. 🐈🌍


Next: Chapter 25: Scientific Kitty Workflow & Tools