Sub topic 11
Running open-weight models locally and on servers
This chapter covers how to run an open-weight model yourself, on a laptop or on a server. It assumes you can read basic Python, have called an HTTP API or SDK before, and know the terms prompt, token, and context. It also assumes you have seen the idea of parameter count and precision from earlier chapters.
What self-hosting means
Self-hosting means you download the model weights and run an inference program on hardware you control. The inference program is called a serving tool or inference engine. It loads the weights into memory, takes prompts, and produces tokens.
You pick a serving tool based on where the model will run and how many users it must handle. The two common situations are:
- Local use: one person, one machine, such as a laptop or a workstation. This suits development, prototyping, and private experiments.
- Server use: many users or many requests at the same time. This suits production workloads.
Both situations can expose the same kind of interface, which keeps your application code the same either way.
Check memory first
Before installing anything, estimate whether the model fits. Weight memory is the parameter count times the bytes per weight. Halving the precision halves the memory.
def weight_memory_gb(params_billion: float, bits_per_weight: int) -> float:
"""Memory for the weights alone, in GB (1 GB = 1e9 bytes)."""
return params_billion * bits_per_weight / 8
for bits in (16, 8, 4):
print(f"7B model at {bits}-bit: {weight_memory_gb(7, bits):.1f} GB")
# 7B model at 16-bit: 14.0 GB
# 7B model at 8-bit: 7.0 GB
# 7B model at 4-bit: 3.5 GBThis number is a floor, not the total. You also need room for the KV cache, which is the memory the model uses to remember the tokens already in the conversation. The KV cache grows with context length and with the number of requests running at once. The runtime adds its own overhead too. A common planning habit is to leave 20 to 30 percent of memory free beyond the weights, and more if you use long contexts or serve many users.
If the model does not fit, you have three options: use a smaller model, use a lower-precision (quantized) version, or use more or larger hardware.
Where the model's memory lives
Memory type matters as much as the amount.
| Hardware | Where weights live | Typical effect |
|---|---|---|
| Dedicated GPU | GPU memory (VRAM) | Fast. The model must fit in VRAM. |
| Apple silicon laptop | Unified memory shared with the CPU | Moderate speed. Larger models fit than on most consumer GPUs. |
| CPU only | System RAM | Works, but slow. Fine for small models and testing. |
Some tools can split a model between GPU and CPU memory. This lets a model run that would not fit in VRAM alone, but the layers on the CPU slow down every token. Treat splitting as a fallback, not a production plan.
Local tools
Several tools make local use simple. They differ in focus.
- Ollama downloads models by name and runs them with one command. It is a good starting point. It serves a local HTTP API that includes an OpenAI-compatible endpoint.
- llama.cpp is a C and C++ inference engine that runs on CPUs and many GPUs. It uses the GGUF file format, which stores quantized weights. Many other tools build on it.
- LM Studio is a desktop application with a graphical interface for downloading and chatting with models. It can also start a local server.
These tools usually download quantized models by default, often around 4-bit. That is why a 7B model can run on a laptop with 8 GB or 16 GB of memory.
Server tools
For production, the main concern changes from "does it run" to "how many requests per second can it handle." Server-grade engines focus on throughput.
- vLLM is a serving engine built for high throughput. It uses continuous batching, which adds new requests to a running batch instead of waiting for the batch to finish. It also manages the KV cache efficiently. It exposes an OpenAI-compatible server.
- Hugging Face Text Generation Inference (TGI) is another production server with similar goals.
- llama.cpp server is lighter and works when you need CPU or modest GPU deployments.
Check each project's current documentation for supported models and hardware, because this area changes quickly.
Use the same client code everywhere
Most of these tools expose an OpenAI-compatible endpoint. That means your application can use the same SDK for a hosted API and for your own server. Only the base URL, key, and model name change. Reading them from environment variables lets you switch without editing code.
import os
from openai import OpenAI
# The same client code can target a hosted API or a self-hosted server that
# exposes an OpenAI-compatible endpoint (for example Ollama or vLLM).
client = OpenAI(
base_url=os.environ["LLM_BASE_URL"],
api_key=os.environ.get("LLM_API_KEY", "not-needed-for-local"),
)
MODEL = os.environ["LLM_MODEL"]
def ask(prompt: str) -> str:
response = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
temperature=0,
)
return response.choices[0].message.contentFor example, with Ollama running locally you might set LLM_BASE_URL=http://localhost:11434/v1 and LLM_MODEL to the name of a model you pulled. With vLLM the default address is typically http://localhost:8000/v1, and the model name is the one you passed when starting the server. Confirm the exact values in the documentation for your version.
Common errors
These problems come up often when you first self-host.
- Out-of-memory errors. The weights fit but the KV cache does not. Lower the maximum context length, reduce the number of concurrent requests, or use a smaller or more quantized model.
- Wrong model name. The server rejects the request because the
modelfield does not match what it loaded. List the available models from the server and copy the exact name. - Silent CPU fallback. The model runs but is very slow because the GPU was not detected. Check the driver and the tool's startup log to see where layers were placed.
- Different behavior from the hosted version. A quantized or differently prompted model can answer differently. Re-run your evaluation set on the self-hosted setup. Do not assume it matches earlier results.
- Prompt format mismatch. Models expect a specific chat template. Chat endpoints normally apply the right one, but raw completion endpoints may not. Prefer the chat endpoint.
- Exposed server. A local server bound to all network interfaces with no authentication can be reached by others. Bind to localhost, or put authentication and a firewall in front of it.
Operating costs that are easy to miss
Running a server is not free once the weights are downloaded. Plan for:
- Hardware or rental cost, paid whether or not requests arrive. GPU servers are usually billed per hour.
- Utilization. A GPU that sits idle at night still costs money. Self-hosting tends to pay off when the hardware stays busy.
- Operations work, such as monitoring, upgrades, scaling, and restarting failed processes.
- Model updates. You decide when to move to a newer model, and you must re-evaluate when you do.
These costs are weighed against hosted API token prices in the later chapter on hosted versus self-hosted trade-offs.
Summary of the working model
- Estimate weight memory, add headroom for the KV cache and overhead, and check it against your hardware.
- Choose a local tool for one user, or a server engine for many.
- Expose an OpenAI-compatible endpoint and keep model settings in environment variables.
- Re-run your evaluation on the actual setup you will deploy.
- Count hardware, utilization, and operations work as part of the cost.
Exercise
You want to run a 13B-parameter model at 4-bit precision on a machine with 8 GB of GPU memory. Estimate the weight memory, and say whether it is likely to fit and why.
Show answer
Weight memory is 13 × 4 / 8 = 6.5 GB. That is under 8 GB, but only 1.5 GB remains for the KV cache and runtime overhead, which is about 19 percent of memory and below the 20 to 30 percent headroom suggested here. It may load but is likely to run out of memory with long contexts or several concurrent requests. Reduce the context length, use a smaller model, or use a GPU with more memory.
Exercise
Your application code reads LLMBASEURL, LLMAPIKEY, and LLM_MODEL from the environment. Name the two things that make it possible to move from a local Ollama server to a vLLM server without code changes, and name one thing you still must do after the move.
Show answer
Both servers expose an OpenAI-compatible endpoint, and the application keeps its endpoint, key, and model name in environment variables instead of in code. After the move you must re-run your evaluation set, because the serving tool, quantization, or model version may change the outputs.