Skip to main content

Run LLMs Locally: Ollama, LM Studio, and llama.cpp Compared (2026 Guide)

By Pashalis LaoutarisUpdated: Category: AI & LLM Development25 min read

Cloud AI is convenient, but it comes with strings attached. Your prompts leave your machine, the meter runs on every token, and the service can change or vanish. Running a model locally flips each of those. The data stays home, the marginal cost is electricity, and the model file is yours.

The trade is quality and speed. A model that fits on a laptop is far smaller than the frontier models behind cloud APIs, and it runs on hardware you already own. For many jobs that is a good trade. For others it is not, and this guide tries to help you tell the difference.

I cover the three tools most developers meet first: Ollama, LM Studio, and llama.cpp. You will get the memory math that decides what you can run and the commands and APIs that matter. You will also see how to wire a local model into your own code and into coding assistants, and which security mistakes have already exposed real servers.

A word on what I tested. I have Ollama installed on my Windows laptop, but its server would not start when I tried it for this article, so I did not run any model. Everything below comes from the official documentation of each project, which I read on November 19, 2026. The code samples are therefore untested here. Treat them as starting points and check the version-specific details against your install.

This is the second article in my AI and LLM series. It follows my guide to MCP servers and builds on my guides to Claude Code and AI-powered IDEs.

Table of Contents

  1. The Short Answer
  2. Why Run Models Locally, and When Not To
  3. How Local Inference Works
  4. Hardware Reality
  5. Ollama in Practice
  6. LM Studio in Practice
  7. llama.cpp: The Engine Underneath
  8. Which Tool Should You Pick?
  9. Wiring Local Models Into Your Tools
  10. Choosing a Model
  11. Security and Privacy
  12. Common Mistakes
  13. Frequently Asked Questions
  14. Conclusion
  15. References

1. The Short Answer

Pick the tool that matches how you work, then match the model to your memory.

If you… Start with
Live in the terminal and want a simple API Ollama. One command pulls and runs a model, and a local REST API starts with it.
Prefer a graphical app to browse and chat LM Studio. It offers model search, a chat window, and a one-click local server.
Want maximum control or run on servers llama.cpp directly, or LM Studio’s headless daemon.
Need a drop-in replacement for an OpenAI client Any of the three. Each exposes an OpenAI-compatible endpoint.
Handle sensitive data that cannot leave Run locally, bind to localhost only, and keep authentication on if you ever share it.

Three rules cover most of the value.

  • Memory decides everything: If the model and its context do not fit in fast memory, speed collapses. Do the arithmetic in section 3 before you download anything.
  • Local does not mean secure by default: A server that listens on every network interface is an open door. Keep the default of localhost.
  • Test on your own tasks: A model that tops a leaderboard may fail at your job. Run a small set of real prompts before you commit.

2. Why Run Models Locally, and When Not To

Good reasons to go local:

  • Privacy: Prompts and documents never leave your machine. Ollama’s documentation states that it does not see your prompts or data when you run locally.
  • Cost at volume: Batch jobs such as summarizing thousands of files cost nothing per token once the model is downloaded.
  • Offline work: Planes, trains, and locked-down networks stop mattering.
  • Control: You pick the exact model file, and nobody swaps it underneath you.
  • Learning: Nothing teaches you how inference works like watching memory fill up.

Good reasons to stay in the cloud:

  • Peak quality: The strongest models do not fit on consumer hardware.
  • Long context: Large context windows need a lot of memory, and local machines run out quickly.
  • Speed on hard tasks: Cloud GPUs generate tokens much faster than a laptop.
  • Zero maintenance: No drivers, no model files, no updates.

A common pattern is hybrid. Use a local model for private, bulk, or offline work, and a cloud model for the hard problems. My guide to AI-powered IDEs shows how several editors let you mix both.

3. How Local Inference Works

Weights, formats, and quantization

A language model is a very large file of numbers called weights. To run it, your machine loads those weights into memory and does math on them for every token it generates. The size of the file decides the minimum memory you need.

Most local tools use a format called GGUF. According to Hugging Face, GGUF stores both the tensors and a standard set of metadata, and it was designed for fast loading. The format was created by the author of llama.cpp, and LM Studio, Ollama, and llama.cpp all work with it.

Original models store each weight in 16 bits. Quantization shrinks them by storing each weight in fewer bits, at some cost in accuracy.

Names like Q4_K_M add a size suffix. The _M files keep some tensors at a higher precision, so they are larger than the pure types in the Hugging Face documentation. A pure Q4_K is 4.5 bits per weight. The Q4_K_M file you actually download is closer to 4.9.

I measured this on December 4, 2026. I divided the size of each GGUF file on Hugging Face by the model’s parameter count, for Llama 3.1 8B and Qwen2.5 14B. The two models agreed within 0.04 bits.

Type Measured bits per weight Notes
Q4_K_M 4.9 The usual starting point for local use.
Q5_K_M 5.7 A bit more accurate and a bit larger.
Q6_K 6.57 Close to full quality for many tasks.
F16 16 Unquantized, and large.

The memory formula

Here is a rule of thumb you can compute in your head. The weights take roughly parameters in billions × bits per weight ÷ 8 gigabytes. I computed the table below from that formula and the bit counts above.

Model size Q4_K_M (4.9 bits) Q5_K_M (5.7 bits) Q6_K (6.57 bits) F16 (16 bits)
3B 1.8 GB 2.1 GB 2.5 GB 6 GB
8B 4.9 GB 5.7 GB 6.6 GB 16 GB
14B 8.6 GB 10 GB 11.5 GB 28 GB
32B 20 GB 23 GB 26 GB 64 GB
70B 43 GB 50 GB 57 GB 140 GB

These numbers cover the weights only. You also need room for the context cache, which grows with every token in your conversation, plus runtime overhead. Budget a few extra gigabytes at small context sizes and much more at large ones. My free local LLM memory calculator does that arithmetic for you, including the cache for your chosen context length.

Context length

The context window is how much text the model can consider at once. Longer contexts cost memory. Ollama’s documentation says its default context length depends on your video memory: 4k tokens under 24 GiB, 32k from 24 to 48 GiB, and 256k at 48 GiB or more. It recommends at least 64,000 tokens for web search, agents, and coding tools.

That recommendation matters a great deal. A coding assistant that sends a large repository summary will silently lose information if the context is too small. If your agent behaves strangely on a local model, check the context length first.

4. Hardware Reality

Generating text is mostly limited by memory bandwidth, so where the weights live matters more than raw compute.

  • A discrete GPU with enough video memory gives the best speed. If the model fits entirely in VRAM, generation is fast.
  • Partial offload splits layers between GPU and CPU. It works, but speed drops toward CPU levels as more layers spill over.
  • CPU only works for small models and patience.
  • Unified memory machines, such as Apple Silicon Macs, let the GPU use the same pool as the system. LM Studio documents an extra runtime for them, MLX, alongside GGUF.

To turn that into numbers for your own card, use my Local LLM Speed Estimator. It shows which models fit and an honest range of tokens per second, and it explains how far off the estimate can be.

Ollama’s GPU documentation lists what it supports.

  • NVIDIA: Compute capability 5.0 or newer with driver 550 or newer. The list covers GTX 10-series up through RTX 50-series cards.
  • AMD: ROCm v7 on Linux, and a supported range of Radeon RX 7000-series and PRO cards on Windows.
  • Apple: GPU acceleration through Metal.
  • Vulkan: Enabled by default on Windows and Linux when the backend is installed, with environment variables to select or disable GPUs.

To see where a running model landed in Ollama, run ollama ps. The PROCESSOR column shows values like 100% GPU or a CPU and GPU split, and the CONTEXT column shows the allocated context length. A model that shows a heavy CPU share is spilling out of video memory, and you should pick a smaller model or a smaller context.

5. Ollama in Practice

Ollama packages model download, storage, and serving behind a small CLI and a local API. Install it from the official download page for Windows, macOS, or Linux.

Core commands

ollama pull gemma4:e4b      # download a model
ollama run gemma4:e4b       # chat in the terminal (type /bye to exit)
ollama serve                # start the server if it is not already running
ollama ps                   # show loaded models and where they run

The quickstart also shows ollama launch claude, ollama launch codex, and ollama launch opencode, which start a coding agent from your project directory using Ollama as the backend. Model tags change often, so browse the official library for current names. When I checked on November 19, 2026, the most pulled entries included llama3.1, deepseek-r1, qwen3, gemma3, gemma4, and qwen3.5, along with embedding models such as nomic-embed-text.

The REST API

The server listens on port 11434 and binds to 127.0.0.1 by default. The main chat endpoint is POST /api/chat.

curl http://localhost:11434/api/chat -d '{
  "model": "gemma4:e4b",
  "messages": [{ "role": "user", "content": "Explain GGUF in one sentence." }],
  "stream": false
}'

Streaming is on by default, and the response arrives as newline-delimited JSON. Set "stream": false to get one object. The response includes useful measurements in nanoseconds, such as load_duration, prompt_eval_duration, and eval_duration, plus token counts prompt_eval_count and eval_count. Divide the token count by the duration to get your own tokens-per-second figure on your own hardware.

You can pass generation settings in an options object, including temperature, seed, and num_ctx for the context length. The keep_alive field controls how long the model stays loaded, and the default is five minutes.

Structured outputs

Ollama can constrain replies to a JSON Schema. Pass the schema in the format field.

curl http://localhost:11434/api/chat -d '{
  "model": "gemma4:e4b",
  "stream": false,
  "messages": [{ "role": "user", "content": "Extract: Ana is 31 and lives in Athens." }],
  "format": {
    "type": "object",
    "properties": { "name": { "type": "string" }, "age": { "type": "integer" }, "city": { "type": "string" } },
    "required": ["name", "age", "city"]
  },
  "options": { "temperature": 0 }
}'

The documentation gives two tips. Include the schema in the prompt as well, so the model understands the fields, and set the temperature to zero for consistent results. In Python you can generate the schema from a Pydantic model, and in JavaScript from a Zod schema. Validate the reply with the same schema before you trust it.

OpenAI compatibility

Ollama also serves an OpenAI-style API at http://localhost:11434/v1/. The supported endpoints include chat completions, completions, models, and embeddings. A non-stateful /v1/responses endpoint arrived in version 0.13.3. Supported features include streaming, JSON mode, tools, and vision with base64 images. The documented gaps include tool_choice, logprobs, and image URLs.

from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:11434/v1/",
    api_key="ollama",  # required by the client but ignored by the server
)

reply = client.chat.completions.create(
    model="gemma4:e4b",
    messages=[{"role": "user", "content": "Say hello in Greek."}],
)
print(reply.choices[0].message.content)

That drop-in behavior is the biggest practical win. Code written for a hosted API can often switch to a local model by changing a base URL.

Modelfiles

A Modelfile packages a base model with your own settings.

FROM gemma4:e4b
PARAMETER temperature 0.2
PARAMETER num_ctx 8192
SYSTEM You are a concise code reviewer. Point out bugs first, style second.

Build and run it with ollama create reviewer -f ./Modelfile and then ollama run reviewer. The documentation lists the other instructions: TEMPLATE, MESSAGE, LICENSE, CAPABILITY, and REQUIRES. It also says the Modelfile default for num_ctx is 2048, which differs from the VRAM-based defaults described earlier. Set the value explicitly so you always know what you are getting.

Environment variables worth knowing

Variable What it does
OLLAMA_HOST Changes the bind address. Setting 0.0.0.0:11434 exposes the server to the network.
OLLAMA_MODELS Moves model storage. The Windows default is C:\Users\<name>\.ollama\models.
OLLAMA_CONTEXT_LENGTH Sets the default context length for the server.
OLLAMA_KEEP_ALIVE Sets how long models stay loaded. The default is five minutes.
OLLAMA_NUM_PARALLEL Sets parallel requests per model. The default is 1, and memory use scales with it.
OLLAMA_MAX_LOADED_MODELS Caps loaded models. The default is three per GPU, or three for CPU inference.

6. LM Studio in Practice

LM Studio is a desktop application for macOS, Windows, and Linux. It lets you search and download models from Hugging Face, chat with them, and serve them over a local API. It runs GGUF models through llama.cpp on all platforms, and it runs MLX models on Apple Silicon.

Features that set it apart

  • A graphical model browser: You can see file sizes and quantization levels before you download.
  • A built-in MCP client: According to its documentation, LM Studio can install MCP servers and use them with local models. My MCP servers guide explains what those are and how to judge their risk.
  • Document chat: You can attach documents to a message and work with them offline.
  • A headless mode: llmster is LM Studio’s core packaged as a daemon for servers and CI, without the GUI.

The lms CLI and the server

The lms command-line tool manages models and the server.

lms get <model>              # download a model
lms ls                       # list models on disk
lms load <model> --gpu=max --context-length=16384
lms ps                       # list models loaded in memory
lms server start --port 1234 # start the local server
lms unload --all             # unload everything

The documented load options include --gpu with values max, auto, or a fraction from 0.0 to 1.0, plus --context-length, --identifier, and --ttl. The headless daemon starts with lms daemon up.

The server exposes an OpenAI-compatible API at http://localhost:1234/v1 with chat completions, completions, embeddings, models, and responses endpoints. It also has an Anthropic-compatible POST /v1/messages endpoint and its own REST API, which the documentation marks as beta.

Model loading and memory

LM Studio loads models on demand. The first request to a model loads it, which is called just-in-time loading and is on by default. JIT-loaded models unload after an idle time of 60 minutes unless you set a different ttl in the request or in the app. Models loaded with lms load have no timeout by default and stay until you unload them. Auto-evict is also on by default, which keeps at most one JIT-loaded model in memory at a time.

Authentication

By default, LM Studio does not require authentication for API requests. You can turn on a required token in the server settings, create tokens with chosen permissions, and send them as a standard bearer token. Turn this on before you serve LM Studio to anyone else on your network.

Licensing

LM Studio announced on July 8, 2025 that using it at work no longer requires a separate commercial license or a form. The company’s own blog post is the source for this. Read the current terms yourself if your legal team needs certainty, and remember that each model you download carries its own license.

7. llama.cpp: The Engine Underneath

llama.cpp is the open-source C and C++ inference project behind much of the local LLM world. Its stated aim is inference with minimal setup on a wide range of hardware. LM Studio’s documentation says its GGUF runtime uses llama.cpp. Many other tools build on it too.

Using it directly gives you the newest features first and the most control. The cost is more manual setup. The project README currently shows install scripts, prebuilt binaries on GitHub, Docker, and building from source. It runs a model straight from Hugging Face with a -hf flag.

llama cli -hf ggml-org/Qwen3.5-0.8B-GGUF     # chat in the terminal
llama serve -hf ggml-org/Qwen3.5-0.8B-GGUF   # start an OpenAI-compatible server

These command names match what the README shows today. Older builds shipped separate llama-cli and llama-server binaries, so use whichever names your downloaded version provides. I did not run either.

Choose llama.cpp when you want to tune low-level settings, run on unusual hardware, or deploy a small inference service without a desktop app.

8. Which Tool Should You Pick?

Question Ollama LM Studio llama.cpp
Main interface CLI and a small desktop app Full desktop app plus a CLI Command-line programs
Model discovery Official library with short tags Hugging Face browser inside the app Hugging Face through -hf
Local API port 11434 1234 Set when you start the server
OpenAI-compatible API Yes, under /v1/ Yes, under /v1 Yes
Authentication by default None, localhost only Off by default, tokens available Check your version’s options
Customization Modelfiles App settings and lms load flags Every flag
Headless and server use Yes Yes, through llmster Yes
MCP client built in Not documented in what I read Yes Not in what I read

My advice is simple. Try LM Studio first if you want to explore models visually. Use Ollama when you want scripts, containers, and a stable local API. Move to llama.cpp when you hit a limit that the friendlier tools hide.

You do not have to pick only one. All three can read GGUF files, though each keeps its own model storage, so downloading the same model twice wastes disk space.

9. Wiring Local Models Into Your Tools

Any OpenAI-style client

Because Ollama and LM Studio speak the OpenAI dialect, most libraries work with a base URL change. Use http://localhost:11434/v1/ for Ollama and http://localhost:1234/v1 for LM Studio. Pass any placeholder string as the API key if the client demands one.

Claude Code with a local model

Both tools document an Anthropic-compatible path, which lets Claude Code talk to a local model. For Ollama, the simplest route is ollama launch claude. The manual route sets three environment variables.

export ANTHROPIC_AUTH_TOKEN=ollama
export ANTHROPIC_API_KEY=""
export ANTHROPIC_BASE_URL=http://localhost:11434
claude --model qwen3.5

For LM Studio, the documentation says to set ANTHROPIC_BASE_URL to the local server address and ANTHROPIC_AUTH_TOKEN to lmstudio, then launch Claude Code with a model you have loaded.

Ollama’s guide adds important caveats. Pick a local model that supports tools and has a context window of at least 64k. Hosted web search and some advanced tool controls do not work through the compatible API. Claude Code still asks for permission on most actions, so unattended use needs permission rules, and the guide only recommends skipping permissions inside an isolated environment. My Claude Code deep dive covers those permission settings in detail.

I have not run this setup, and I would expect a small local model to feel noticeably weaker than a frontier model for agentic coding. Try it on a throwaway project first.

Embeddings and retrieval

Both tools serve embedding models through their OpenAI-style /v1/embeddings endpoint. That lets you build private search over your own notes with no cloud calls. Pair an embedding model with a chat model, and keep the same embedding model for indexing and querying.

MCP

LM Studio can act as an MCP client for local models, as noted above. If you build your own tools, my MCP servers guide shows how to expose them once and use them from any compatible host.

10. Choosing a Model

I will not name a winner, because the field changes monthly and any ranking I wrote would age badly. Here is a method that does not.

  1. Start from your memory budget. Use the table in section 3 to find the largest size that fits with room for context.
  2. Prefer recent releases from established labs. Check the capability tags in the library, such as tools, vision, and thinking, against what your task needs.
  3. Try two sizes of the same family. The difference shows you what extra parameters buy for your task.
  4. Write ten real prompts and keep them. Use the same set for every candidate. Score the answers yourself.
  5. Measure speed on your hardware. Use the timing fields from the API, and note the speed at your intended context length, not an empty chat.
  6. Read the license carefully. Some models restrict commercial use.

Thinking models produce long internal reasoning before the answer. That can improve results on hard problems, and it also costs time and tokens. Ollama’s chat API has a think parameter for models that support it.

11. Security and Privacy

Running locally removes one class of risk, which is sending data to a vendor. It also adds new risks of its own.

Do not expose the server

Ollama binds to 127.0.0.1 by default, and LM Studio’s authentication is off by default. Both are fine on localhost. Trouble starts when people set OLLAMA_HOST=0.0.0.0 for convenience, or forward a port, and leave the API open.

Cisco researchers scanned the internet with Shodan in 2025 and found 1,139 publicly reachable Ollama endpoints. Of those, 214 answered model queries without asking for credentials. Cisco warned that Shodan gives only a partial picture, so the true number is probably higher. An open model server lets strangers spend your electricity and probe your system.

If you must share a server:

  • Put it behind a reverse proxy or a private network such as a VPN.
  • Require authentication, such as LM Studio’s tokens or a proxy with credentials.
  • Never publish the port directly to the internet.
  • Keep the software updated.

Treat model files as untrusted input

A model download is a large file from the internet. GGUF is a data format, but parsers and runtimes have had bugs, and the tools around them have had security flaws like any other software. Download from the official library or from publishers you trust, and keep Ollama, LM Studio, and llama.cpp updated. The habits in my guides to supply chain security and dependency scanning apply to model files as much as to packages.

Agents are still agents

A local model that can run shell commands or read files has the same risks as a cloud one. Prompt injection from a web page or a document still works. Smaller models are often easier to trick, so keep approval prompts on and limit what tools can touch. My MCP servers guide covers the tool-side risks in depth.

Secrets

Do not paste API keys or credentials into prompts, even for a local model, because chat history is often stored on disk. My secrets management guide explains safer patterns.

12. Common Mistakes

  • Downloading before doing the math: A 70B model on a machine with 16 GB of memory will be painfully slow or fail to load.
  • Ignoring context length: The default may be far smaller than your agent needs, and the model will quietly forget instructions.
  • Judging speed on a short chat: Generation slows as the context fills. Test at the length you will actually use.
  • Leaving the Modelfile num_ctx unset: The documented default of 2048 is easy to forget.
  • Exposing the API for convenience: Use a private network, not an open port.
  • Comparing models by leaderboard alone: Your task is the benchmark that counts.
  • Using the highest precision by default: A 4 or 5 bit quantization is usually the better trade on limited hardware.
  • Forgetting that idle models hold memory: Check the keep-alive and time-to-live settings if your machine feels slow after a session.
  • Expecting cloud-level agent performance: Small models can make more tool-calling mistakes, so verify results.

13. Frequently Asked Questions

What is the easiest way to run an LLM locally?

Install Ollama or LM Studio and pull a small model. Ollama needs one command, such as ollama run followed by a model tag. LM Studio lets you click a model in its built-in browser and start chatting.

Is Ollama or LM Studio better?

Neither is better in every case. Ollama suits scripts and a simple local API. LM Studio suits visual exploration and has a built-in MCP client. Many developers install both.

How much RAM or VRAM do I need?

Estimate the weights as parameters in billions times bits per weight divided by eight, then add a few gigabytes for context and overhead. An 8B model at about 4.9 bits needs roughly 4.9 GB for weights. Section 3 has the full table.

Can I run a local model without a GPU?

Yes, with small models. Generation will be slow compared with a GPU, and large models may be impractical. Use ollama ps to see whether a model is running on the CPU.

Are local models private?

The prompts do not leave your machine when you run a model locally, according to Ollama’s documentation. Privacy still depends on your setup. An exposed server, a synced chat history, or a leaky plugin can undo it.

Can I use a local model with the OpenAI SDK?

Yes, it works well. Ollama serves an OpenAI-compatible API at http://localhost:11434/v1/, and LM Studio does the same at http://localhost:1234/v1. Change the base URL, pass any placeholder key, and use the model name from the tool.

Can I use Claude Code with a local model?

Both tools document a way to do it. Ollama offers ollama launch claude, and both accept Claude Code through an Anthropic-compatible endpoint. Expect weaker results than with a frontier model, and use a model with tool support and at least 64k of context.

What is quantization?

Quantization stores model weights in fewer bits to shrink the file and the memory needed. It trades a little accuracy for a lot of space. Four to six bits per weight is the usual range for local use.

Is LM Studio free for commercial use?

According to LM Studio’s July 2025 announcement, a commercial license is no longer required for use at work. Check the current terms for your situation, and check each model’s own license separately.

Should I use llama.cpp directly?

Use it when you need low-level control, the newest features, or a small server deployment. For everyday use, Ollama or LM Studio hides the setup and is easier to live with.

14. Conclusion

Local models have become practical for everyday developer work. You can download one in minutes, serve it through an API your existing code understands, and keep your data on your own machine. The three tools in this guide cover the range from friendly to hands-on.

The limits are just as real. Memory sets a hard ceiling, small models trail frontier ones, and a careless setup can expose your machine. Do the memory math first, set the context length on purpose, and keep the server on localhost.

Start with something small. Pull one model, call it from a script, and measure its speed at your real context length. Then decide which jobs belong at home and which still belong in the cloud. The next article in this series compares the agent frameworks that sit on top of both.

15. References

Official Ollama project documentation:

Official LM Studio documentation:

Inference engine and formats:

Security research and reporting:


Back to All Posts
Share this post:
Share on X
Share on LinkedIn
Share on Reddit
Share on Facebook
Copy Link
Copied!