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
Approximate weight memory for a 7B-parameter model. Add headroom for the KV cache and activations.
FormatWhat it isWhere it's used
GGUFFile 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
GPTQOne-shot post-training quantization that minimizes layer-wise errorGPU inference (vLLM, TGI, ExLlama)
AWQProtects the ~1% of salient weights (found via activations), quantizes the restGPU inference; good quality at 4-bit
FP88-bit floating point, natively supported on recent GPUsHigh-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.

  1. 01Draft modelGuesses the next 4-8 tokens quickly
  2. 02Target modelVerifies all guesses in one pass
  3. 03Accept prefixKeep tokens until the first mismatch
  4. 04RepeatOutput identical to the big model alone
When the draft is usually right - boilerplate, code, predictable text - you get several tokens per expensive pass, with mathematically identical output quality.

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.

RouterScores each token; picks the top 2
  • Expert 1active
  • Expert 2idle
  • Expert 3active
  • Expert 4...8idle
Mixtral 8x7B: 8 experts per layer, 2 active per token - about 47B total parameters but only ~13B used per token. DeepSeek-V2: 236B total, 21B active.
DenseMoE
Compute per tokenAll parametersOnly active experts - much cheaper
MemoryParametersAll experts must be loaded - high
Quality per FLOPBaselineHigher: more capacity for the same compute
Best forMemory-constrained or simple deploymentsHigh-throughput serving where memory is available

The serving stack#

ApplicationYour app, agent, or RAG pipeline
GatewayLiteLLM, OpenRouter - one API, many providers, fallbacks, budgets, logging
Inference servervLLM, SGLang, TGI (production) · Ollama, llama.cpp, LM Studio (local)
Model weightsFP16/BF16, FP8, GPTQ/AWQ (GPU) or GGUF (CPU/Apple Silicon)
HardwareData-center GPUs · consumer GPUs · Apple Silicon unified memory · CPU
From your application down to the hardware.
  • 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

Further reading

Search Data Science After Dark

Search across prompts, models, papers, guides, and library topics.