Local LLM Inference Engines Compared: Ollama, vLLM, llama.cpp, SGLang, and TGI

Local LLM Inference Engines Compared: Ollama, vLLM, llama.cpp, SGLang, and TGI

A team stands up a local model on a workstation with a 24 GB GPU. A developer pulls a 7B-class model, runs it through a desktop-friendly runner, and the demo is delightful: first token in under a second, answers streaming at reading speed. Two weeks later the same box serves a code-review bot, a ticket summarizer and a handful of engineers hitting a chat UI. Latency now swings from fast to unusable, requests queue behind a single long prompt, and one afternoon the process dies with an out-of-memory error even though the model weights fit comfortably. Nothing about the model changed. The workload did.

That gap between "it runs" and "it serves" is what the choice of inference engine decides. Ollama, llama.cpp, vLLM, SGLang and Hugging Face TGI all load the same open-weight checkpoints and expose similar HTTP endpoints, so they look interchangeable on a feature list. Underneath, they make different bets about memory layout, batching and scheduling, and those bets decide which of them survives concurrent load, long prompts, a laptop, or a rack of GPUs. This article explains the mechanisms that matter, gives you a way to size a deployment on paper, and ends with a checklist for picking one.

1. What an inference engine actually spends its time on

Generating text with a transformer has two phases with opposite performance profiles. Prefill processes the whole prompt in one pass. It is a large matrix-matrix workload, so it is limited by raw compute, and its cost grows with prompt length. Decode then produces one token at a time. Each step reads every weight of the model (or, for a mixture-of-experts model, the active experts) plus the cached attention state, to compute a single token. That is a matrix-vector workload and it is limited by memory bandwidth, not by arithmetic.

This explains most of the behavior you will see in practice. A single user decoding on a consumer GPU is bandwidth-bound, so a smaller or more aggressively quantized model is faster almost in proportion to its size. Add more concurrent users and the same weight read can be shared across all of them, which is why batching raises total throughput so dramatically while each user's own speed drops only modestly. The whole discipline of serving engines is about keeping the GPU busy with a full batch without running out of the other scarce resource: memory for the KV cache.

The KV cache stores the attention keys and values of every token already processed, per layer, so decode does not recompute them. It grows linearly with sequence length and with the number of concurrent sequences, and it is allocated in addition to the weights. Two engines that load identical weights can differ by a large factor in how many concurrent requests they hold, purely because of how they manage this cache.

The three levers every engine pulls

  • Weight format and quantization. Fewer bits per weight means less memory and, in the bandwidth-bound decode phase, more tokens per second, at some quality cost that depends on the method and the model.
  • KV cache management. Contiguous per-request buffers waste memory on fragmentation and over-reservation; paged and shared layouts recover it.
  • Scheduling. Static batches wait for the slowest request; continuous batching admits new requests between decode steps so the GPU never idles on a finished sequence.

2. llama.cpp and GGUF: the portable baseline

llama.cpp is a C/C++ inference library built around the GGUF file format, which packs weights, tokenizer and metadata into one file. Its defining property is reach. It runs on CPUs with SIMD, on Apple Silicon through Metal, on NVIDIA GPUs through CUDA, and on AMD and other GPUs through ROCm and Vulkan backends, and it can split a model between CPU and GPU when the model does not fit in VRAM. For a machine without a datacenter GPU, nothing else comes close in flexibility.

Its quantization family is the other draw. GGUF offers block-quantized formats from roughly 2 to 8 bits per weight, and the "K-quant" variants (names such as Q4_K_M or Q5_K_M) mix precision across tensors so that the most sensitive ones keep more bits. The common rule of thumb is that 4- to 5-bit variants give a large memory reduction with a modest quality loss for most chat and coding use, while the very low-bit variants degrade noticeably. Treat that as a starting point and evaluate on your own prompts.

llama.cpp ships a server, llama-server, with an OpenAI-compatible API and slots for parallel requests. Two details trip people up. First, the context size you set is the total across all parallel slots, so a server started with a 16,384-token context and four slots gives each request roughly 4,096 tokens. Second, partial GPU offload (the number of layers placed on the GPU) is a manual tuning knob: too few layers and you leave speed on the table, too many and the KV cache no longer fits next to them.

When not to use it: when you need to serve dozens of concurrent users from one GPU with predictable tail latency. llama.cpp can batch, but its scheduler and cache layout are tuned for flexibility and single-digit concurrency more than for saturating a datacenter card.

3. Ollama: a packaging and lifecycle layer

Ollama's value is the experience around the engine rather than a different engine. You pull a model by name from a registry, a background service manages loading and unloading, and a small Modelfile describes a model variant with its system prompt and parameters. Historically it has been built on llama.cpp, and its newer releases have added their own runtime paths for some model families, so check the current documentation rather than assuming. For most teams the practical consequence is that Ollama inherits GGUF-style quantization and the broad hardware support, and adds convenience.

The convenience also hides decisions that matter in production. Models stay resident for a keep-alive period and are then unloaded, so the first request after idle time pays the full load cost. The default context length is modest, and long prompts are silently truncated unless you raise it. Parallelism and the number of simultaneously loaded models are controlled by environment settings such as OLLAMA_NUM_PARALLEL, OLLAMA_MAX_LOADED_MODELS and OLLAMA_KEEP_ALIVE, and raising parallelism multiplies the KV cache the runner reserves.

# Modelfile: pin the context window and sampling so behavior is reproducible
cat > Modelfile <<'EOF'
FROM llama3.1:8b
PARAMETER num_ctx 8192
PARAMETER temperature 0.2
SYSTEM You are a concise code-review assistant.
EOF
ollama create reviewer -f Modelfile

# keep the model warm for an hour and allow 4 concurrent requests
OLLAMA_KEEP_ALIVE=1h OLLAMA_NUM_PARALLEL=4 ollama serve

# the native chat endpoint (an OpenAI-compatible one exists under /v1)
curl http://localhost:11434/api/chat -d '{
  "model": "reviewer",
  "messages": [{"role": "user", "content": "Review: def add(a, b): return a - b"}],
  "stream": false
}'

Ollama is the right default for a single developer, a prototype, an internal tool with a handful of users, or an edge machine where operational simplicity beats peak throughput. It is a poor fit when you need fine control over batching, prefix caching policy or multi-GPU tensor parallelism.

4. vLLM: PagedAttention and continuous batching

vLLM was built to fix the memory waste in naive KV cache handling. A conventional server reserves a contiguous buffer per request sized for the maximum possible length, so most of it sits unused and the rest fragments. vLLM's PagedAttention instead divides the KV cache into fixed-size blocks and keeps a per-sequence block table, much like virtual memory pages in an operating system. Sequences take blocks as they grow, free them when they finish, and identical prefixes can share physical blocks. The result is that far more concurrent sequences fit in the same memory.

The second ingredient is continuous batching. The scheduler works at the granularity of a single decode step. When a sequence emits its end token, its slot is handed to a waiting request immediately instead of the batch waiting for the slowest member. Combined with chunked prefill, which splits a long prompt into pieces interleaved with other requests' decode steps, this keeps latency for short requests reasonable even when someone submits a very long prompt.

vLLM targets datacenter GPUs first, with support for tensor parallelism across several GPUs, a range of quantization formats (such as AWQ, GPTQ and FP8 on hardware that supports it), LoRA adapter serving and an OpenAI-compatible server. Hardware coverage beyond NVIDIA has been growing but varies by release, so verify your accelerator before committing. The cost of all this is complexity: you tune --gpu-memory-utilization, --max-model-len and the maximum number of concurrent sequences, and a wrong setting shows up as a failed start or as preempted requests under load.

# vLLM: reserve 90% of GPU memory, cap context, serve an OpenAI-compatible API
vllm serve meta-llama/Llama-3.1-8B-Instruct \
  --max-model-len 16384 \
  --gpu-memory-utilization 0.90 \
  --max-num-seqs 64 \
  --port 8000

5. SGLang: prefix reuse and structured generation

SGLang approaches the same problem from the workload side. Many real applications send requests that share a long prefix: the same system prompt, the same few-shot examples, the same retrieved document asked about many times, or an agent loop that appends a little to a growing conversation. SGLang's RadixAttention keeps KV cache entries in a radix tree keyed by token sequences, so any new request automatically reuses the longest matching prefix already in memory. For agent and RAG workloads with heavy prefix overlap, this removes a large share of prefill work.

The other pillar is a runtime for structured output and multi-call programs. SGLang can constrain decoding to a grammar or JSON schema, and it offers a frontend language for chaining several model calls with shared state so the engine can schedule them together. If your application is "call the model, parse the result, call it again with part of the previous context", the engine seeing that structure is an advantage a generic completion endpoint cannot match.

# SGLang server (flag names follow the project's launch_server entry point)
python -m sglang.launch_server \
  --model-path meta-llama/Llama-3.1-8B-Instruct \
  --port 30000

The trade-off is the same as vLLM's: datacenter orientation, more knobs, and a project that moves quickly, so pin versions. Prefix caching only pays off if your prompts are actually structured to share a stable prefix; a system prompt that embeds a timestamp at the top defeats it completely.

6. Text Generation Inference (TGI) and the shape of the field

Hugging Face's Text Generation Inference is a Rust and Python server that was an early production-grade answer to this problem. It provides continuous batching, tensor parallelism, token streaming, quantization options and tight integration with the Hugging Face model hub, and it was widely deployed behind managed endpoints. If you already run Hugging Face infrastructure it remains a coherent option.

The field has moved quickly, though, and several newer engines have taken much of the mindshare for self-hosting. Before adopting TGI for a new deployment, check the project's current status and release cadence, and confirm it supports the model architecture you need, since architecture support is exactly where servers diverge. The general lesson applies to every engine in this article: you are choosing a project as much as a design, so look at how recently it shipped support for the models you care about.

A qualitative comparison

The table compares design properties, not measured speed. Throughput depends heavily on model, hardware, quantization and prompt mix, so benchmark on your own workload before deciding.

Engine Sweet spot Hardware reach Cache and batching design Main cost
llama.cpp Laptops, mixed CPU/GPU, edge, low concurrency Very broad (CPU, Metal, CUDA, ROCm, Vulkan) Slot-based parallelism, flexible but not tuned for large batches Manual offload and context tuning
Ollama Developer machines, prototypes, small internal tools Broad, inherited from its runtime Simple parallelism setting, keep-alive model residency Less control, defaults can hide truncation and cold starts
vLLM Many concurrent users on datacenter GPUs Strongest on NVIDIA, widening elsewhere Paged KV cache, continuous batching, chunked prefill Tuning and operational complexity
SGLang Agents, RAG and few-shot workloads with shared prefixes Datacenter GPUs first Radix-tree prefix reuse, constrained decoding Needs prompts built for reuse; fast-moving project
TGI Teams already on Hugging Face tooling Datacenter GPUs, some other accelerators Continuous batching, tensor parallelism Check project momentum and architecture support

7. A worked example: sizing a deployment on paper

Before you install anything, estimate memory. Take an 8-billion-parameter model of the Llama-3 family shape: 32 transformer layers, 8 key-value heads (grouped-query attention), a head dimension of 128, and an fp16 KV cache. For each token, each layer stores one key vector and one value vector per KV head.

That is 2 (key and value) x 32 layers x 8 heads x 128 dimensions x 2 bytes = 131,072 bytes, or 128 KiB per token. An 8,192-token sequence therefore holds about 1 GiB of KV cache, and sixteen such sequences hold about 16 GiB. The weights are separate: roughly 16 GB in fp16, or in the neighborhood of 4 to 5 GB at 4-bit quantization. On a 24 GB card, 4-bit weights leave around 19 GB, which is enough for roughly sixteen 8k-token sequences minus runtime overhead and activation memory. In fp16 the weights alone would leave only 8 GB, about eight sequences. Quantizing the KV cache, where an engine supports it, shifts the balance again at some quality risk.

def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_elem=2):
    # 2 = one key vector and one value vector per head per layer
    return 2 * layers * kv_heads * head_dim * bytes_per_elem

def max_sequences(vram_gb, weights_gb, overhead_gb, ctx_tokens, per_token):
    free = (vram_gb - weights_gb - overhead_gb) * 1024**3
    return int(free // (ctx_tokens * per_token))

per_tok = kv_bytes_per_token(layers=32, kv_heads=8, head_dim=128)
print(per_tok)                                  # 131072 bytes = 128 KiB
print(max_sequences(24, 4.5, 2.0, 8192, per_tok))  # about 17 on these assumptions

Run the same arithmetic for your own model; the layer count, KV head count and head dimension are in the model's configuration file. The point is the shape of the answer: memory, not compute, usually caps concurrency, and context length is the multiplier you control. Halving the context you allow doubles the sequences you can hold.

Rule of thumb: concurrency is bounded by (free memory after weights) divided by (context length x KV bytes per token). If a vendor claim about "users supported" does not state the context length, it is not a claim you can plan around.

8. Decision checklist and failure modes

Work through these questions in order. The first "yes" that applies usually decides the engine.

  1. Is this one person or a prototype, on a laptop or workstation? Start with Ollama, or llama.cpp if you want direct control over quantization and offload.
  2. Does the target machine lack a datacenter GPU, or need CPU or Apple Silicon support? Choose llama.cpp (directly or through Ollama).
  3. Will many users share one or more GPUs with latency targets? Choose vLLM or SGLang, and load-test with your real prompt lengths.
  4. Do most requests share a long, stable prefix (system prompt, documents, agent history)? Favor SGLang, or enable prefix caching in vLLM and confirm the hit rate.
  5. Do you need strictly valid JSON or grammar-constrained output? Pick an engine with constrained decoding and test the failure behavior when the schema is unsatisfiable.
  6. Do you depend on an architecture released recently? Check that the engine supports it before anything else; this single fact eliminates options more often than performance does.

Failure modes to plan for

  • Out-of-memory under load, not at startup. The KV cache grows with traffic. Cap context length and concurrent sequences explicitly instead of relying on defaults.
  • Silent truncation. A prompt longer than the configured context is cut without an error in some runners. Log prompt token counts and compare with the limit.
  • Head-of-line blocking. One enormous prompt monopolizes prefill. Chunked prefill and request-size limits at your gateway contain it.
  • Cold starts. Loading a large model from disk takes long enough to time out a client. Keep models resident or warm them at deploy time.
  • Quantization regressions. A format that looks fine on chat can degrade structured extraction or code. Evaluate on the task you ship.
  • Drift between engines. The same checkpoint under different engines and chat templates can produce different outputs. Pin the engine version and the template together.

9. Common mistakes and what to do on Monday

The most common mistake is benchmarking with one request at a time, then deploying for twenty. Single-stream numbers tell you about memory bandwidth and quantization; they say nothing about scheduling. The second is comparing engines on different quantizations and calling it an engine comparison. The third is forgetting the chat template: a model served with the wrong template degrades in ways that look like a weak model. The fourth is treating a local model as a drop-in for a frontier API on every task, when its strength is bounded, repeatable work where you can verify the result.

That last point is how a production agent stack should think about it. Small local models earn their place on narrow, typed decisions such as classifying a request, extracting fields or routing a task, where the output is checked against a schema before anything acts on it. Heavy reasoning stays with larger models, and nothing is declared done until the result has been verified independently. An inference engine is infrastructure for that pattern, not a substitute for it.

A short plan for the first week

  1. Write down your real workload: typical and worst-case prompt length, output length, expected concurrent users, and latency target.
  2. Do the memory arithmetic from section 7 for two candidate models and two quantizations.
  3. Stand up one engine from section 8's checklist and replay recorded production-shaped prompts at your target concurrency, recording time to first token and per-token latency at the median and the 99th percentile.
  4. Set explicit limits: maximum context, maximum concurrent sequences, request timeout.
  5. Add a health check, log token counts, and decide in advance what happens when the server is saturated: queue, shed load, or fall back to a hosted model.

Questions teams ask

Can I just use Ollama in production? For a small number of users with modest latency needs, yes, provided you set context and keep-alive deliberately. If you need to sustain many concurrent streams, move to an engine with continuous batching and a paged cache.

Is a bigger quantization always better? No. Past a point the quality gain is small and the memory cost is real; more KV cache headroom often serves users better than a few extra bits per weight.

Do I need multiple GPUs? Only if the weights plus cache do not fit in one, or one GPU cannot meet your throughput. Tensor parallelism adds communication cost, so prefer one larger GPU over two smaller ones when the budget allows.