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
2
3
pip install -U "transformers[torch,serving]" huggingface_hub
hf auth login # Needed for gated/private repos
hf download Qwen/Qwen2.5-0.5B --local-dir ./Qwen2.5-0.5B # Or use huggingface_hub.snapshot_download

Load locally with AutoClasses (see How the KV Cache Works in HuggingFace Transformers for generation-time KV caching):

1
2
3
4
5
6
7
8
9
from transformers import AutoModelForCausalLM, AutoTokenizer

model_path = "./Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto", dtype="auto")

inputs = tokenizer("The secret to baking a good cake is", return_tensors="pt").to(model.device)
outputs = model.generate(**inputs, max_new_tokens=20)
print(tokenizer.decode(outputs[0], skip_special_tokens=True))

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
2
3
4
5
6
7
8
9
10
11
# 1. Install conversion dependencies & download snapshot
pip install huggingface_hub transformers torch gguf sentencepiece tiktoken
hf download Qwen/Qwen2.5-0.5B-Instruct --local-dir ~/Qwen/Qwen2.5-0.5B-Instruct

# 2. Convert to lossless bf16 GGUF (ideal baseline for quantization)
python llama.cpp/convert_hf_to_gguf.py ~/Qwen/Qwen2.5-0.5B-Instruct \
--outtype bf16 --outfile ~/Qwen/Qwen2.5-0.5B-Instruct-BF16.gguf

# 3. Quantize and serve (OpenAI API + Web UI on http://127.0.0.1:8080)
llama-quantize ~/Qwen/Qwen2.5-0.5B-Instruct-BF16.gguf ~/Qwen/Qwen2.5-0.5B-Instruct-Q4_K_M.gguf Q4_K_M
llama-server -m ~/Qwen/Qwen2.5-0.5B-Instruct-Q4_K_M.gguf
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
2
3
curl http://127.0.0.1:8080/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"messages": [{"role": "user", "content": "Hello, who are you?"}], "temperature": 0.7, "max_tokens": 256}'

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
2
3
4
5
6
7
8
# Install on Linux
wget https://ollama.com/download/ollama-linux-amd64.tgz
sudo tar -C /usr -xzvf ollama-linux-amd64.tgz

# Start server, pull a model, and chat interactively
ollama serve # Keep running in a terminal (verify with: ollama -v)
ollama pull gemma3:4b
ollama run gemma3:4b

Call programmatically using an OpenAI-compatible client:

1
2
3
4
5
6
7
8
from chat_completions_conversation import ChatCompletionsConversation

conversation = ChatCompletionsConversation(
api_key="",
base_url="http://localhost:11434/v1",
model="gemma3:4b",
)
conversation.send_and_receive_response("Hello, how are you?")

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:

  1. Subclass vllm.platforms.interface.Platform for your hardware.
  2. Override get_compile_backend to return your custom compiler backend.
  3. Implement compile(fx_graph, example_inputs, compiler_config) to lower the fx.GraphModule for the target device and return (compiled_callable, cache_handle).

Hugging Face Models and LLM Inference Engines: llama.cpp, Ollama, and vLLM
https://jifengwu2k.github.io/2026/05/04/Hugging-Face-Models-and-LLM-Inference-Engines/
Author
Jifeng Wu
Posted on
May 4, 2026
Licensed under