Run a local model with llama.cpp

To run a local language model, install llama.cpp, download a compatible GGUF model and test it with llama-cli. Start with a Q4_K_M file, then measure speed, memory and answer quality on your own workload before choosing a smaller or larger quantization.

Local inference gives you control over where the model runs, but it does not guarantee privacy. A server, application logs or connected tools can still expose prompts.

1. Install llama.cpp for your hardware

The official llama.cpp repository provides source code, pre-built releases and backend-specific build instructions. Pre-built binaries are the quickest route if a release matches your operating system and hardware. Building from source lets you select a GPU backend.

First, install Git, CMake and a C++ compiler. GPU builds also need the relevant toolkit or development files.

On macOS or Linux, build a CPU version in a terminal:

bash
git clone https://github.com/ggml-org/llama.cpp.git
cd llama.cpp
cmake -B build -DGGML_METAL=OFF
cmake --build build --config Release -j

On Windows, open a developer terminal with a C++ build environment and run:

powershell
git clone https://github.com/ggml-org/llama.cpp.git
cd llama.cpp
cmake -B build
cmake --build build --config Release

The remaining examples use Unix-style paths. On Windows, executables may be under build\bin\Release and have an .exe extension.

To use a GPU, configure a separate build directory with one appropriate backend:

bash
## NVIDIA GPU with CUDA installed
cmake -B build-gpu -DGGML_CUDA=ON

## Vulkan-compatible GPU with Vulkan development files installed
cmake -B build-gpu -DGGML_VULKAN=ON

## Apple Silicon with Metal
cmake -B build-gpu -DGGML_METAL=ON

Then run cmake --build build-gpu --config Release -j. If configuration fails, check the repository's current build instructions; backend requirements and flags can change. The repository also provides container images if you prefer not to build locally.

A successful GPU build does not prove that a model is using the GPU. After loading the model, check the startup output for the backend, device and offloaded layers. If those are absent, make sure you are running the binary from the GPU build directory.

2. Choose and download a GGUF model

GGUF packages model weights and metadata, including architecture and context information. Quantization stores weights at reduced precision. It can make a model fit in memory, but it can also change its answers.

Start your shortlist with the task, not the file suffix:

  • Code generation: try an instruct version of Qwen 2.5-Coder. Evaluate it with your own tests and languages.
  • General reasoning and document questions: try Llama 3.1 Instruct or Qwen 2.5 Instruct. Test whether answers preserve details and acknowledge missing evidence.
  • Multilingual work: try Qwen 2.5 or Aya 23, then test the actual languages and writing styles you need.
  • Retrieval: choose a supported embedding model separately from the chat model. Compare retrieval quality as well as generated answers.

These are starting candidates, not rankings. Check each exact model card for its licence, intended use, supported context and GGUF availability. Llama and Gemma community licences have different conditions from permissive licences; do not assume that an open-weight download permits your intended use. For an individual legal question, consult a qualified professional.

Pick a quantization and leave memory headroom

Q4_K_M is a practical first candidate for chat. K-quants group weights into super-blocks and store scaling information alongside them to preserve more useful detail at low precision. IQ formats use importance-aware information when quantizing. They can be worth testing when memory is tight, but the result depends on the model and calibration used to create the file.

Candidate Relative memory demand When to test it
Q3_K_S or a supported IQ variant Lower A larger file does not fit; check task quality carefully
Q4_K_M Moderate First comparison for general chat and drafting
Q5_K_M Higher Code or detail-sensitive work where Q4 misses your quality target
Q8_0 Higher still A higher-precision reference when memory permits

Suffixes such as _S and _M identify variants within a family; they do not predict every model's quality. Compare files made from the same base model. A study of Llama-3.1-8B-Instruct reported that Q4_K_M retained roughly 98% of the FP16 baseline's MMLU accuracy at roughly 25% of its model size, as of January 2026. That is one model and benchmark, not a guarantee for your documents or code.

As a starting sizing guide, a quantized 7B–8B model may fit in roughly 8–12 GB, while a 70B Q4_K_M model can need more than 40 GB. These are planning estimates, not capacity guarantees. Check the actual GGUF file size and leave additional RAM or VRAM for the runtime, other applications, working buffers and the KV cache, which stores information needed during a conversation. Long contexts and concurrent requests increase cache demand.

If a model barely fits, reduce context or concurrency, offload fewer layers, or try a smaller model or quantization. Partial GPU offload uses both GPU and system memory; inspect the reported placement rather than assuming the whole file is in VRAM.

Download a concrete example

For a small setup test, the following command downloads an illustrative Qwen instruct GGUF using the Hugging Face command-line tool. It is useful for checking the installation, not a recommendation for demanding production work.

bash
python -m pip install -U "huggingface_hub[cli]"
hf download Qwen/Qwen2.5-0.5B-Instruct-GGUF \
  qwen2.5-0.5b-instruct-q4_k_m.gguf \
  --local-dir models

The resulting path is models/qwen2.5-0.5b-instruct-q4_k_m.gguf. Check the repository's file list if the provider changes filenames. For a professional deployment, verify the artifact's hash against a trusted, independently obtained value, and record the model revision and licence.

3. Test a prompt in the CLI

Replace the path with your own GGUF if you chose another model:

bash
./build/bin/llama-cli \
  -m models/qwen2.5-0.5b-instruct-q4_k_m.gguf \
  -p "Explain what a database index does." \
  -c 4096 -n 128 --temp 0

-c sets the context capacity; -n limits generated tokens. A token is a piece of text, not necessarily a whole word. Temperature changes sampling: use a low setting for repeatable comparisons, then test the setting your application will actually use.

For a GPU build, request layer offload and inspect the startup output:

bash
./build-gpu/bin/llama-cli \
  -m models/qwen2.5-0.5b-instruct-q4_k_m.gguf \
  -p "Explain what a database index does." \
  -n 128 -ngl 99

-ngl 99 requests offload of up to that many layers; it does not prove that all layers fit or that the backend is active. If you get an architecture or format error, check support for the exact model and update llama.cpp if needed.

Use the CLI for one-off tests and the server when an application needs an HTTP interface. For retrieval vectors, use the embeddings endpoint with an appropriate embedding model rather than assuming a chat model is suitable.

4. Start a local API and request embeddings

Start the chat server with an explicit loopback address and context limit:

bash
./build/bin/llama-server \
  -m models/qwen2.5-0.5b-instruct-q4_k_m.gguf \
  --host 127.0.0.1 --port 9931 --ctx-size 4096

From another terminal on the same machine:

bash
curl http://127.0.0.1:9931/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "local-model",
    "messages": [{"role": "user", "content": "Explain database indexes."}],
    "temperature": 0,
    "max_tokens": 128
  }'

The model name is illustrative. If your configuration requires a particular identifier, use the one the server exposes. Loopback binding limits network access to the host, but other local processes may still reach an unauthenticated server.

For embeddings, stop the chat server and start a separate instance with a compatible embedding GGUF:

bash
./build/bin/llama-server -m embedding-model.gguf \
  --embedding --host 127.0.0.1 --port 9932

Then request a vector:

bash
curl http://127.0.0.1:9932/v1/embeddings \
  -H "Content-Type: application/json" \
  -d '{"model":"local-embedding","input":"A database index speeds up lookups."}'

Check llama-server --help for your build's options and the embedding model's instructions for input formatting. Use the same embedding model for indexing and queries unless you have validated a different arrangement. See RAG architecture for local LLM embeddings.

5. Benchmark speed, memory and quality

llama-bench measures prompt processing and generation separately. Prompt processing affects how quickly the model handles input; generation throughput affects how quickly the answer appears.

Start with a CPU baseline, then use the GPU build if available:

bash
./build/bin/llama-bench -m model.gguf -p 512 -n 128 -t 4 -ngl 0
./build-gpu/bin/llama-bench -m model.gguf -p 512 -n 128 -t 4 -ngl 99

The lengths and thread count are illustrative. Match them to your workload and inspect llama-bench --help for your build. Record both token rates, model and quantization, build, hardware, thread count and actual layer placement. Repeat runs under similar machine load.

On Linux, measure peak process resident memory alongside a CPU benchmark with:

bash
/usr/bin/time -v ./build/bin/llama-bench \
  -m model.gguf -p 512 -n 128 -t 4 -ngl 0

Read "Maximum resident set size" in the output. For NVIDIA GPU memory, observe nvidia-smi while the benchmark runs. It gives a snapshot, so sample throughout the run to find the peak. On macOS, use Activity Monitor's Memory and GPU views. System and GPU measurements are not interchangeable, especially on unified-memory machines.

Compare Q4_K_M, Q5_K_M and Q8_0 from the same model with fixed settings first. Then tune threads around your physical-core count, GPU offload and batch sizes. -b controls the logical batch and -ub the physical micro-batch; keep micro-batch no larger than batch. Larger batches can help prompt processing but also consume more memory. Do not assume they improve generation.

On Apple Silicon, test Flash Attention and an 8-bit KV cache against your baseline:

bash
./build-gpu/bin/llama-cli -m model.gguf \
  -p "Summarize the supplied text." -n 128 -ngl 99 \
  -fa on --cache-type-k q8_0 --cache-type-v q8_0

Check the startup output for support. A smaller cache can make a longer context practical, but test quality and memory with real requests, including concurrency.

Compare answers on the same representative prompts. Run generated code tests in isolation; for extraction, check the output against the source and validate its structure. Include cases where the correct answer is "not enough information." The guide to evaluating LLM capabilities and governance covers wider evaluation and oversight.

6. Protect a shared server and its prompts

Keep the server on loopback for local development. Before shared use, put it behind a controlled reverse proxy with TLS, authentication, rate limits and request-size limits, and prevent clients from reaching the backend directly. Check your build's --api-key-file option, protect and rotate keys, and monitor availability without routinely logging prompts.

Restrict diagnostic endpoints. A misconfigured /slots endpoint can expose prompt data. Isolate tenants and untrusted workloads, verify model hashes, and keep llama.cpp and its dependencies updated. Strip unnecessary secrets and personal data before inference where possible.

Treat retrieved text and model output as untrusted. If a model can call tools or execute code, validate and authorize each action outside the model; see sandboxing AI agents.

The members' bonus contains a tuning sweep, model-selection matrix, evaluation harness, and deployment examples for a proxy and isolated container.