The Open Stack (AI Engg #6)
You want to try an open model tonight. You have no GPU budget, no cloud account, and forty minutes. By the end of this chapter you will have a 7B model answering questions on your laptop, exposed through the same API shape as OpenAI, and a one-line switch to route to a hosted provider when your laptop is not enough.
The open stack is three layers: weights (Hugging Face), runtime (Ollama, LM Studio, vLLM), and routing (OpenRouter, or a compatible gateway). The unifying trick is that almost everything now speaks the OpenAI-compatible REST shape, so your application code does not care which layer it is talking to.
The layers
- Weights & discovery — Hugging Face. The Hub hosts hundreds of thousands of models, datasets, and Spaces. Its “Tasks” pages tell you what a model is for (text-generation, embeddings, speech recognition). You download weights or use the Inference SDK for hosted calls.
- Runtime — how weights become a server. Ollama and LM Studio wrap a model behind an OpenAI-compatible HTTP endpoint on your machine. vLLM and TGI do the same for production GPUs with batching and higher throughput.
- Routing — one API to many providers. OpenRouter gives a single key and endpoint that fans out to dozens of models (open and closed), with fallbacks and spend caps. Your own gateway can do this too.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=3.0cm, minimum height=0.8cm, font=\rmfamily\small, align=center},
a/.style={->, thick}]
\node[b, fill=yellow!18] (h) at (0,1.7) {Hugging Face\\weights, datasets, tasks};
\node[b, fill=orange!16] (r) at (0,0) {runtime\\Ollama / LM Studio / vLLM};
\node[b, fill=green!12] (a2) at (0,-1.7) {your app\\(OpenAI-compatible API)};
\node[b, fill=blue!10] (o) at (4.2,0) {OpenRouter\\many providers, one key};
\draw[a] (h) -- (r); \draw[a] (r) -- (a2);
\draw[a, dashed] (o) -- (a2);
\end{tikzpicture}
Hugging Face: finding and running weights
The Hub is an index. Learn three things and you can navigate it:
- Model cards. Every repo has a card with the intended task, license, training data, and often a “use in Transformers” snippet. Read the license first.
- Tasks tab. Filter by
text-generation,sentence-similarity(embeddings),automatic-speech-recognition,text-to-image, and so on. This is how you find the right kind of model. - Formats.
safetensors(standard, safe),GGUF(quantized, for llama.cpp/Ollama/LM Studio),ONNX(cross-platform). Ollama wants GGUF; Transformers wants safetensors.
Two ways to run Hub models:
# 1) pull a GGUF build into Ollama (fastest path to a local chat)
ollama pull qwen2.5:7b
ollama pull llama3.2:3b
# 2) use Transformers in Python (full control, needs a GPU for big models)
pip install transformers torch
python - <<'PY'
from transformers import pipeline
gen = pipeline("text-generation", model="Qwen/Qwen2.5-1.5B-Instruct")
print(gen("Explain RAG in one sentence:", max_new_tokens=40)[0]["generated_text"])
PY
There is also Transformers.js, which runs supported models in the browser via WebGPU — useful for privacy-preserving demos and edge features with no server at all.
Ollama vs LM Studio vs vLLM
They all serve an OpenAI-compatible API; they differ in who they are for.
| Tool | Interface | Best for | Notes |
|---|---|---|---|
| Ollama | CLI + HTTP | dev, scripts, quick pulls | one command to run; model registry |
| LM Studio | GUI + lms CLI |
exploring, non-CLI users | visual model browser, GPU offload |
| vLLM | server (GPU) | production throughput | PagedAttention, batching |
| llama.cpp | C++ CLI | embedded/edge | the engine under many tools |
For a laptop, Ollama or LM Studio is the answer. For production open-weight serving on GPUs, vLLM is the usual default because it batches many concurrent requests efficiently — the single biggest throughput win for open models.
# Ollama exposes an OpenAI-compatible server on :11434
ollama serve # start the server (often already running)
ollama run qwen2.5:7b # interactive chat
ollama ps # check what is loaded and whether it is on GPU
# LM Studio alternative
lms server start # then point your client at http://localhost:1234/v1
One client, many backends
This is the payoff. Because the API shape is shared, the only thing that changes is base_url and model.
from openai import OpenAI
local = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
lms = OpenAI(base_url="http://localhost:1234/v1", api_key="lm-studio")
router = OpenAI(base_url="https://openrouter.ai/api/v1", api_key="sk-or-...")
def ask(client, model, prompt):
r = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
temperature=0.2,
)
return r.choices[0].message.content
print(ask(local, "qwen2.5:7b", "What is RAG in one line?"))
print(ask(router, "meta-llama/llama-3.3-70b-instruct", "What is RAG in one line?"))
Write your app against this interface and you can move from laptop → self-hosted GPU → hosted API without touching business logic. That portability is the entire point of the stack.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=4pt, minimum width=2.2cm, minimum height=0.7cm, font=\rmfamily\small, align=center},
a/.style={->, thick}]
\node[b, fill=green!12] (app) at (0,0) {your app};
\node[b, fill=orange!15] (ol) at (-3.0,-1.5) {Ollama\\:11434};
\node[b, fill=orange!15] (lm) at (-1.0,-1.5) {LM Studio\\:1234};
\node[b, fill=blue!10] (or) at (1.4,-1.5) {OpenRouter};
\node[b, fill=red!10] (cl) at (3.4,-1.5) {OpenAI/Anthropic};
\draw[a] (app) -- (ol); \draw[a] (app) -- (lm); \draw[a] (app) -- (or); \draw[a] (app) -- (cl);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0.2,-2.15) {same request shape; only base\_url + model change};
\end{tikzpicture}
Quantization: why the same model runs on your laptop
Open models are distributed in full precision (float16/bfloat16) or quantized to fewer bits. Quantization shrinks memory and speeds inference at some quality cost.
Q4_K_M— the common sweet spot: ~4 bits/weight, good quality, small.Q8_0— near-full quality, ~2× the memory of Q4.F16— full precision, largest, slowest on consumer hardware.
A 7B model is roughly 14 GB in F16, ~7 GB in Q8, ~4 GB in Q4. That is why an 8 GB laptop can run a 7B model at Q4 but not F16. Rule: start at Q4_K_M; if quality on your goldens is short, move to Q8; only then consider a bigger model.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
bar/.style={draw, thick},
a/.style={->, thick}]
\fill[green!30] (0,0) rectangle (1.0,0.8); \draw[bar] (0,0) rectangle (1.0,0.8);
\fill[orange!35] (1.5,0) rectangle (3.0,0.8); \draw[bar] (1.5,0) rectangle (3.0,0.8);
\fill[red!25] (3.5,0) rectangle (7.0,0.8); \draw[bar] (3.5,0) rectangle (7.0,0.8);
\node[font=\rmfamily\small, anchor=north] at (0.5,-0.05) {Q4 $\approx$4GB};
\node[font=\rmfamily\small, anchor=north] at (2.25,-0.05) {Q8 $\approx$7GB};
\node[font=\rmfamily\small, anchor=north] at (5.25,-0.05) {F16 $\approx$14GB};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (3.5,-0.75) {same 7B model, three memory footprints};
\end{tikzpicture}
OpenRouter: one key, many models
OpenRouter is not a model; it is an aggregator. You send the same OpenAI-shaped request with a model slug like qwen/qwen-2.5-72b-instruct or openai/gpt-4o, and it routes to the provider. Benefits:
- One key, one bill across many providers.
- Fallbacks — if a model is down or rate-limited, routing can fall through.
- Spend caps and analytics per key, useful for a team.
- Model comparison without new SDKs.
router = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key="sk-or-...",
default_headers={"HTTP-Referer": "https://yourapp.com", "X-Title": "My App"},
)
r = router.chat.completions.create(model="anthropic/claude-3.5-sonnet",
messages=[{"role": "user", "content": "Compare RAG and fine-tuning in 2 lines."}])
Caveat: aggregation adds a network hop and a dependency. For max control and privacy, run your own gateway over the providers you trust. OpenRouter is the fast path, not the mandatory one.
Hosted inference vs self-hosting: the trade
- Hosted (HF Inference, OpenRouter, Together, Fireworks): instant, no GPUs, pay per token, data leaves your network.
- Self-hosted (vLLM on your GPU/cloud): fixed cost, full privacy, model pinned, but you own uptime and scaling.
Start hosted to learn and validate. Self-host when volume makes the economics obvious or when compliance demands it. The code above is identical either way, which is why writing against the OpenAI shape now pays off later.
Pitfalls
- Wrong quantization. Q4 lets you run it, Q8 reasons better. Sweep the quant on your evals before concluding “open models are worse.”
- Forgetting GPU offload. Check
ollama ps; a model silently running on CPU can be 20× slower and feel broken. - Leaking API keys. An OpenRouter key in client-side JavaScript is a bill you did not authorize. Keep keys server-side.
- License blindness. “Open weights” is not “no license.” Some models restrict commercial use or redistribution. Read the card before shipping.
Why does the same Python client work for Ollama, LM Studio, and OpenRouter? What does quantization trade away?
ASolution
They all expose the OpenAI-compatible chat-completions REST shape, so only base_url and model change. Quantization trades numerical precision (and therefore some output quality) for much lower memory use and higher speed — Q4 runs a 7B model in ~4GB but may lag Q8 on your goldens.
Next: Serving LLMs at Scale (AI Engg #7) — quantization, the KV cache, batching, and prefix caching: the layer between your code and the model.