Step 5 of 5
Optimization & Serving
Quantization, distillation, FlashAttention, speculative decoding, PagedAttention, MoE - and how to run models locally or in production.
15 min read
A model that's accurate but slow and expensive doesn't ship. This guide covers the techniques that make models smaller, faster, and cheaper - and the serving stack you'll use, from a laptop to production. It ends with a hands-on walkthrough of running models locally with Ollama.
Making models smaller#
Quantization#
Weights are normally stored as 16-bit floats. Quantization stores them in fewer bits - 8, 4, sometimes fewer - trading a small amount of accuracy for large savings in memory and bandwidth. Since decoding is memory-bandwidth-bound, smaller weights also mean faster tokens.
- FP32 (4 bytes)~28 GB
- FP16 / BF16 (2 bytes)~14 GB
- INT8 (1 byte)~7 GB
- 4-bit~4 GB
| Format | What it is | Where it's used |
|---|---|---|
| GGUF | File format from llama.cpp bundling quantized weights (Q4_K_M, Q5_K_M, Q8_0...) | Ollama, llama.cpp, LM Studio - CPU and Apple Silicon friendly |
| GPTQ | One-shot post-training quantization that minimizes layer-wise error | GPU inference (vLLM, TGI, ExLlama) |
| AWQ | Protects the ~1% of salient weights (found via activations), quantizes the rest | GPU inference; good quality at 4-bit |
| FP8 | 8-bit floating point, natively supported on recent GPUs | High-throughput production serving |
Distillation#
Train a small student model to imitate a large teacher. Rather than learning from hard labels alone, the student learns from the teacher's full probability distribution ("soft targets"), which carries far more information per example - e.g., that a wrong answer was almost right. Many small, capable models today are distilled from larger ones, often using teacher-generated training data.
- Quantization
- Storing model weights in fewer bits (8, 4) to cut memory and speed up inference - decoding is memory-bandwidth-bound, so smaller weights = faster tokens.
- GGUF
- A file format from llama.cpp that bundles quantized weights - the standard for running models on CPU and Apple Silicon via Ollama.
- Distillation
- Training a small student model to imitate a large teacher's full probability distribution, transferring capability at a fraction of the size.
Model merging#
Combine the weights of several fine-tuned models from the same base - by averaging, or with methods like SLERP, TIES, or DARE - to blend their skills without additional training. It's cheap to try and popular in the open-model community, though results need careful evaluation.
Making inference faster#
FlashAttention#
Attention's bottleneck on GPUs isn't arithmetic - it's moving the n × n score matrix in and out of slow high-bandwidth memory. FlashAttention computes exact attention in tiles that stay in fast on-chip SRAM, never materializing the full matrix. Same output, far less memory traffic, and much longer sequences become practical.
Speculative decoding#
Decoding generates one token per forward pass of the big model. Speculative decoding lets a small, fast draft model propose several tokens, then the big model checks all of them in a single parallel pass and keeps the longest correct prefix.
- 01Draft modelGuesses the next 4-8 tokens quickly
- 02Target modelVerifies all guesses in one pass
- 03Accept prefixKeep tokens until the first mismatch
- 04RepeatOutput identical to the big model alone
PagedAttention and continuous batching#
Serving many users means juggling many KV caches of unpredictable length. Naive servers pre-allocate the maximum length per request and waste most of it. PagedAttention (the core of vLLM) stores the KV cache in fixed-size blocks, like an operating system's virtual memory pages, so memory is allocated on demand and fragmentation nearly disappears.
Continuous batching adds and removes requests from the running batch at every decoding step instead of waiting for a whole batch to finish. Together they multiply throughput on the same hardware.
- FlashAttention
- An IO-aware attention kernel that computes exact attention in tiles that stay in fast on-chip SRAM - same output, far less memory traffic.
- Speculative decoding
- A small draft model proposes several tokens; the big model verifies them in one parallel pass - identical output, fewer expensive forward passes.
- Continuous batching
- Adds and removes requests from a running batch at every decode step instead of waiting for the whole batch to finish - much better GPU utilization.
- vLLM
- A high-throughput inference server built on PagedAttention - the standard for production LLM serving with continuous batching and tensor parallelism.
Mixture of Experts vs dense#
A dense model uses every parameter for every token. A Mixture of Experts (MoE) model replaces each MLP with many "expert" MLPs and a router that sends each token to only a few of them.
- Expert 1active
- Expert 2idle
- Expert 3active
- Expert 4...8idle
| Dense | MoE | |
|---|---|---|
| Compute per token | All parameters | Only active experts - much cheaper |
| Memory | Parameters | All experts must be loaded - high |
| Quality per FLOP | Baseline | Higher: more capacity for the same compute |
| Best for | Memory-constrained or simple deployments | High-throughput serving where memory is available |
The serving stack#
- Local and prototyping: Ollama or llama.cpp. One command, runs on a laptop, OpenAI-compatible API.
- Production throughput: vLLM or SGLang on GPUs - PagedAttention, continuous batching, tensor parallelism, prefix caching.
- Multi-provider apps: put a gateway like LiteLLM (self-hosted) or OpenRouter (hosted) in front so you can switch models, add fallbacks, and track spend without changing application code.
Run LLMs locally with Ollama#
Running models on your own machine is free, private, and works offline. Ollama is the quickest way to start.
8 GB RAM
comfortable for 3-4B models
16 GB
7-8B models at 4-bit
32 GB+
14B-32B models
:11434
local API port
1. Install. On macOS and Windows, download the app from ollama.com. On Linux:
curl -fsSL https://ollama.com/install.sh | sh
2. Run a model. The first run downloads it; after that it starts in seconds.
ollama run llama3.2 # small, fast general model
ollama pull qwen2.5-coder # download without starting a chat
ollama list # what's installed
ollama ps # what's loaded in memory right now
3. Call it from code. Ollama serves a local HTTP API, including an OpenAI-compatible endpoint, so most SDKs work by changing the base URL:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama") # key is ignored
reply = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Explain the KV cache in two sentences."}],
)
print(reply.choices[0].message.content)
4. Customize with a Modelfile to set a system prompt and parameters:
FROM llama3.2
PARAMETER temperature 0.3
SYSTEM You are a concise senior data scientist. Answer in under 120 words.
ollama create ds-helper -f Modelfile && ollama run ds-helper
Papers behind this guide
GPTQ: Post-Training Quantization
One-shot 3-4-bit weight quantization for GPT-scale models with minimal accuracy loss.
IST Austria / ETH Zürich, 2022
AWQ: Activation-aware Weight Quantization
Protect the ~1% of salient weights and quantize the rest - a popular 4-bit format.
MIT Han Lab, 2023
Distilling the Knowledge in a Neural Network
Train a small student to mimic a large teacher's soft probabilities.
Google, 2015
Speculative Decoding
A small draft model proposes tokens; the big model verifies them in parallel - same output, faster.
Google Research, 2022
vLLM: PagedAttention
Manage the KV cache like virtual memory pages - the core idea behind vLLM's throughput.
UC Berkeley, 2023
Switch Transformers
Sparse Mixture-of-Experts routing each token to one expert - trillion-parameter scale.
Google Brain, 2021
Mixtral of Experts
An open sparse MoE: 8 experts per layer, 2 active per token.
Mistral AI, 2024
DeepSeek-V2: Mixture of Experts
How DeepSeek achieved frontier performance at a fraction of the compute cost using MoE architecture.
DeepSeek AI, 2024