Hugging Face Models and LLM Inference Engines: llama.cpp, Ollama, and vLLM
A Hugging Face repository is a versioned bundle of model artifacts—not a self-contained executable. Weights only become runnable when paired with software that knows the model’s architecture, tokenizer rules, and tensor layout.
flowchart LR
HF["Hugging Face Hub<br/>(config.json, *.safetensors, tokenizer)"] --> TF["Transformers / transformers serve<br/>(Reference PyTorch eager runtime)"]
HF -->|"convert_hf_to_gguf.py"| GGUF["GGUF (+ Quantization)"]
GGUF --> LCP["llama.cpp<br/>(Portable C/C++ + mmap)"]
GGUF --> OLL["Ollama<br/>(Managed local CLI & API)"]
HF -->|"Native / backend loader"| VLLM["vLLM<br/>(Continuous batching + PagedAttention)"]
1. Hugging Face Repositories and Transformers
A typical text-generation repository contains config.json (model_type, architectures, layer dimensions), generation_config.json, tokenizer files (tokenizer.json, tokenizer_config.json), sharded .safetensors weights (plus model.safetensors.index.json), and optionally custom Python files mapped via auto_map (which require trust_remote_code=True after code review and revision pinning).
Download, load, and serve
1 | |
Load locally with AutoClasses (see How the KV Cache Works in HuggingFace Transformers for generation-time KV caching):
1 | |
Or expose an OpenAI-compatible endpoint (http://localhost:8000/v1) directly via transformers serve Qwen/Qwen2.5-0.5B-Instruct --reasoning auto.
Why arbitrary model export is hard
There is no universal converter from an arbitrary Transformers repository to ONNX, XLA, GGUF, or a custom serving engine. Export tools (torch.export, torch.onnx.export, torch.fx) struggle with data-dependent control flow, changing tensor shapes, MoE routing, custom kernels, and bespoke KV caches. Correct engine support usually requires reimplementing the architecture, mapping weight names/layouts, and validating logits against a reference.
| Runtime | Primary Goal | Model Format | Best Fit |
|---|---|---|---|
transformers serve |
Maximum ecosystem compatibility | HF config + .safetensors |
Newly released or custom architectures |
llama.cpp |
Portability and low-memory execution | GGUF (often quantized) | CPUs, Apple Silicon, consumer GPUs |
Ollama |
Turnkey local model management | Managed GGUF packages / Modelfile |
Rapid local setup and dev workflows |
vLLM |
High-throughput concurrent serving | HF artifacts in supported backends | Production multi-user APIs on GPUs/accelerators |
2. llama.cpp: Portable Local Inference and GGUF
llama.cpp is a C/C++ runtime targeting CPUs, Apple Silicon, and GPUs with minimal dependencies. It reads GGUF, a single-file format packing metadata, tokenizer data, and tensors that can be memory-mapped (mmap) for fast startup (though active weights still need sufficient RAM/VRAM to avoid thrashing).
End-to-end workflow: Download → Convert → Quantize → Serve
convert_hf_to_gguf.py supports 90+ architectures (check with python convert_hf_to_gguf.py --print-supported-models):
1 | |
| Quant Type | Approx. Size (0.5B) | Notes |
|---|---|---|
Q4_K_M |
~0.4 GB | Best all-round balance |
Q5_K_M |
~0.5 GB | Higher quality |
Q8_0 |
~0.7 GB | Near-lossless |
IQ3_M / IQ4_NL |
~0.3–0.4 GB | Ultra-compact variants |
Test the server at http://127.0.0.1:8080/v1/chat/completions:
1 | |
3. Ollama: Managed Local Models
Ollama wraps a llama.cpp-style execution engine with a local model registry, Modelfile customization, and an OpenAI-compatible HTTP server (http://localhost:11434/v1). It trades low-level runtime knobs for one-command ergonomics and also accepts custom GGUF files.
Install, run, and call via API
1 | |
Call programmatically using an OpenAI-compatible client:
1 | |
4. vLLM: High-Throughput Inference Operating System
At first glance, vLLM looks like an OpenAI-compatible HTTP server, but its real role is a specialized LLM inference operating system. Wrapping Hugging Face model.generate() in an API fails under concurrency because of poor batching, KV-cache fragmentation, Python per-token overhead, and inability to mix long and short requests. Because each active request has its own prompt length, decode progress, KV state, and stopping rule, vLLM schedules concurrent stateful token streams at the token level.
flowchart LR
Req["Concurrent Requests"] --> Sched["Token-Level Continuous Scheduler"]
Sched --> PA["PagedAttention<br/>(Logical Tokens → Fixed Physical KV Blocks)"]
PA --> Comp["torch.compile / fx.GraphModule"]
Comp --> Plat["Platform.get_compile_backend()"]
Plat --> HW["GPU / Custom Accelerator"]
PagedAttention, continuous batching, and memory sharing
Traditional engines reserve one contiguous KV-cache buffer per request up to its maximum sequence length, causing severe internal fragmentation (unused reserved slots) and external fragmentation (unusable gaps between allocations). PagedAttention applies OS virtual-memory paging to the KV cache:
- The KV cache is partitioned into fixed-size blocks (analogous to physical page frames; tokens act like bytes and requests like processes).
- A per-sequence page table maps logical token positions to non-contiguous physical blocks allocated on demand, eliminating external fragmentation and confining internal fragmentation to the final block.
- Continuous (rolling) batching dynamically slots new requests into the batch as soon as blocks and compute free up, instead of waiting for the longest sequence in a static batch.
- Memory sharing lets requests with identical prompt prefixes point their page tables to the same physical KV blocks, cutting memory use and time-to-first-token.
Custom accelerator compilation
vLLM uses PyTorch Dynamo (torch.compile) to trace a model’s forward pass into an fx.GraphModule (graph IR, weights/state, and generated forward()). To target a new accelerator backend:
- Subclass
vllm.platforms.interface.Platformfor your hardware. - Override
get_compile_backendto return your custom compiler backend. - Implement
compile(fx_graph, example_inputs, compiler_config)to lower thefx.GraphModulefor the target device and return(compiled_callable, cache_handle).