Running open models locally with Hugging Face

Load, prompt and quantise open-weight models with Transformers, and serve them with Ollama or llama.cpp.

Intermediate about 4 h

The picture

  1. 01

    Pick a model

    size vs VRAM

  2. 02

    Load

    dtype, device_map

  3. 03

    Chat template

    correct format

  4. 04

    Generate

    sampling params

  5. 05

    Serve

    OpenAI-compatible API

Why bother

Local and open models let you control cost, latency, privacy and behaviour, and they are the only way to fine-tune. They are also how you learn what an API hides.

Will it fit?

Memory for weights is roughly parameters × bytes per parameter. Add working memory for the KV cache and activations.

def weight_gb(params_b: float, bits: int) -> float:
    return params_b * bits / 8          # billions of params × bytes per param = GB

for bits in (16, 8, 4):
    print(bits, "bit:", weight_gb(7, bits), "GB for a 7B model")   # 14, 7, 3.5

A 7B model needs about 14 GB in 16-bit but only about 4 GB in 4-bit, at some quality cost.

Loading and prompting correctly

Instruction-tuned models expect a specific chat template with role markers. Use the tokenizer's template; never hand-write it.

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

name = "Qwen/Qwen2.5-1.5B-Instruct"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, torch_dtype=torch.bfloat16, device_map="auto")

messages = [
    {"role": "system", "content": "You are concise."},
    {"role": "user", "content": "Explain the KV cache in two sentences."},
]
ids = tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt").to(model.device)
out = model.generate(ids, max_new_tokens=150, do_sample=False)
print(tok.decode(out[0][ids.shape[1]:], skip_special_tokens=True))

4-bit loading

from transformers import BitsAndBytesConfig
bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
                         bnb_4bit_compute_dtype=torch.bfloat16)
model = AutoModelForCausalLM.from_pretrained(name, quantization_config=bnb, device_map="auto")

Serving locally with an OpenAI-compatible API

ollama pull llama3.2
ollama serve            # exposes an OpenAI-compatible endpoint on port 11434
from openai import OpenAI
local = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")   # key is ignored
r = local.chat.completions.create(model="llama3.2", messages=[{"role": "user", "content": "hi"}])
print(r.choices[0].message.content)

Because the interface matches, the code you wrote against hosted APIs works unchanged. That makes swapping, comparing and falling back between models cheap.

Common mistakes

  • Using a base model where an instruct model is needed.
  • Skipping the chat template, which quietly lowers quality.
  • Comparing a quantised local model to a hosted one on one prompt and drawing a conclusion.

Exercises

  1. Run the same 20 prompts on a local 1.5B model and a hosted model and compare accuracy and latency.
  2. Load one model in 16-bit and 4-bit and measure memory, speed and a small quality metric.

You are done when you can…

  • Run an instruction-tuned model locally using its chat template
  • Estimate whether a model fits your GPU at 16-bit, 8-bit and 4-bit
  • Point existing OpenAI-SDK code at a local server