# How to Run Qwen4 Locally: VRAM Requirements, GGUF Quantization, llama.cpp and Ollama Setup

> AI Release · @ai_releaseorg · https://ai-release.org/guides/kak-zapustit-qwen4-lokalno-trebovaniya-k-vram-kvantizat_en.html

## AI summary

Time to complete: 45–60 minutes (most of it is the llama.cpp build and the model download) Difficulty: Intermediate

### Key facts

1. Time to complete: 45–60 minutes (most of it is the llama.cpp build and the model download) (source: #tldr; status: заявление источника)
2. Difficulty: Intermediate (source: #tldr; status: заявление источника)
3. You will need: a machine with a discrete GPU (NVIDIA with CUDA, or Apple Silicon with Metal), Python 3 with huggingface-cli, git, cmake + a C++ compiler, Ollama, and the Qwen4 GGUF file from its Hugging Face repository (source: #tldr; status: заявление источника)
4. OS: Linux or macOS (the commands below are bash). On Windows use WSL2 or adjust the paths to .\build\bin\llama-server.exe. (source: #requirements; status: заявление источника)
5. GPU: NVIDIA with a current driver — verify with nvidia-smi; or Apple Silicon. A CPU-only run works but is slow, so plan a smaller quantization. (source: #requirements; status: заявление источника)
6. Build tools: cmake, make or ninja, and a C++17 compiler. Check with cmake --version. (source: #requirements; status: заявление источника)

### Direct answers

**What is required?** — OS: Linux or macOS (the commands below are bash). On Windows use WSL2 or adjust the paths to .\build\bin\llama-server.exe.; GPU: NVIDIA with a current driver — verify with nvidia-smi; or Apple Silicon. A CPU-only run works but is slow, so plan a smaller quantization.; Build tools: cmake, make or ninja, and a C++17… (#requirements)
**How to do it?** — Step 1. Size the model against your VRAM and pick a quantization → Step 2. Build llama.cpp and start the OpenAI-compatible server → Step 3. Import the same GGUF into Ollama and verify GPU offload (#step-1)
**Which topics does it cover?** — Qwen4 запуск локально, Qwen4 VRAM требования, Qwen4 GGUF квантизация (#entities)
**What are the key points?** — Time to complete: 45–60 minutes (most of it is the llama.cpp build and the model download) Difficulty: Intermediate (#tldr)

- Canonical: https://ai-release.org/guides/kak-zapustit-qwen4-lokalno-trebovaniya-k-vram-kvantizat_en.html
- Markdown: https://ai-release.org/guides/kak-zapustit-qwen4-lokalno-trebovaniya-k-vram-kvantizat_en.md
- JSON: https://ai-release.org/guides/kak-zapustit-qwen4-lokalno-trebovaniya-k-vram-kvantizat_en.json

## TL;DR

- **Time to complete:** 45–60 minutes (most of it is the llama.cpp build and the model download)
- **Difficulty:** Intermediate
- **You will need:** a machine with a discrete GPU (NVIDIA with CUDA, or Apple Silicon with Metal), Python 3 with `huggingface-cli`, `git`, `cmake` + a C++ compiler, Ollama, and the Qwen4 GGUF file from its Hugging Face repository

## What you will get

- A running `llama-server` on `http://127.0.0.1:8080` that answers OpenAI-compatible requests at `/v1/chat/completions`.
- The same GGUF file imported into Ollama under a local tag (example: `qwen4-local`), so you can call it with `ollama run` and through the API on port `11434`.
- A VRAM sizing table plus a filled-in `Modelfile`, so you can re-tune context length and offload without guessing.

## Quick start

```bash
huggingface-cli download <hf-repo> <gguf-file> --local-dir ./models
cmake -B build -DGGML_CUDA=ON && cmake --build build --config Release -j
./build/bin/llama-server -m ./models/<gguf-file> -c 8192 -ngl 99 --host 127.0.0.1 --port 8080
curl http://127.0.0.1:8080/v1/chat/completions -H "Content-Type: application/json" -d '{"messages":[{"role":"user","content":"Hello"}]}'
```

Details and checks are in the steps below.

## Requirements and setup
![Illustration: Requirements and setup](https://ai-release.org/guides/img/kak-zapustit-qwen4-lokalno-trebovaniya-k-vram-kvantizat-en-1.jpg?v=1796460506)


- **OS:** Linux or macOS (the commands below are bash). On Windows use WSL2 or adjust the paths to `.\build\bin\llama-server.exe`.
- **GPU:** NVIDIA with a current driver — verify with `nvidia-smi`; or Apple Silicon. A CPU-only run works but is slow, so plan a smaller quantization.
- **Build tools:** `cmake`, `make` or `ninja`, and a C++17 compiler. Check with `cmake --version`.
- **Python tooling:** `pip install -U "huggingface_hub[cli]"` gives you the `huggingface-cli` command used to download GGUF files.
- **Ollama:** installed and serving on `127.0.0.1:11434`. Check with `ollama --version` and `curl http://127.0.0.1:11434/api/tags`.
- **Disk:** free space equal to at least twice the GGUF file size — you need room for the download and for Ollama's copy of the same weights.
- **Filenames are not guessed here.** The exact GGUF filenames and the list of available quantizations for Qwen4 live in its Hugging Face repository — open the repo's file list and copy the name verbatim. If you have never picked a GGUF file before, the filter-and-quantization walkthrough in [How to download a model from Hugging Face and run it locally](https://ai-release.org/guides/kak-skachat-model-s-hugging-face-i-zapustit-lokalno-fil.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide) explains what the `Q4_K_M` / `Q8_0` suffixes mean before you commit to a multi-gigabyte download.

**Check:** `huggingface-cli whoami` prints your username, and `nvidia-smi` prints a table with your GPU name and total memory.

## Step 1. Size the model against your VRAM and pick a quantization

**What to do:** Compute the memory budget before downloading, then choose the largest quantization that fits.

**Why:** A GGUF file is loaded almost entirely into VRAM when you offload all layers. If the file plus the context cache exceeds your GPU memory, llama.cpp falls back to system RAM or aborts with an allocation error. Sizing first saves a second download.

The budget is:

```
VRAM ≈ model file size + KV cache + runtime overhead (~0.5–1 GB for the CUDA/Metal context)
KV cache ≈ 2 × n_layers × n_kv_heads × head_dim × ctx_len × 2 bytes (f16 cache)
```

Rough file size from the parameter count, for any N-billion-parameter model: 4-bit ≈ 0.5 bytes/parameter, 5-bit ≈ 0.65, 6-bit ≈ 0.75, 8-bit ≈ 1.0. So a 7B model at 4-bit lands near 3.5–4 GB. These are definitional bit-widths, not measured benchmarks.

| Quantization | Approx. bytes/param | Use it when |
|---|---|---|
| `Q8_0` | ~1.0 | VRAM is plentiful; you want the closest match to the original weights |
| `Q6_K` | ~0.75 | You have headroom and want better quality than 4-bit |
| `Q5_K_M` | ~0.65 | The middle ground when `Q4_K_M` fits but leaves little room for context |
| `Q4_K_M` | ~0.5 | Default choice for consumer GPUs; best size/quality trade-off |
| `Q3_K_M` and below | <0.5 | Only when nothing larger fits — quality drops noticeably |

**Example:** you have a 12 GB GPU. A 4-bit file of about 8 GB leaves roughly 3 GB for the KV cache and overhead — enough for a moderate context, not for a very long one. Verify the real numbers from the file itself.

**How to check:** load the model with generation disabled and read the metadata llama.cpp prints on startup:

```bash
./build/bin/llama-cli -m ./models/<gguf-file> -n 0 2>&1 | grep -E "block_count|head_count_kv|head_count|embedding_length|file type"
```

You should see lines such as `llama_model_loader: - kv ... block_count u32 = <N>` and `... head_count_kv ...`. Put those values into the KV-cache formula above with your intended `-c` value.

## Step 2. Build llama.cpp and start the OpenAI-compatible server
![Illustration: Step 2. Build llama.cpp and start the OpenAI-compatible server](https://ai-release.org/guides/img/kak-zapustit-qwen4-lokalno-trebovaniya-k-vram-kvantizat-en-2.jpg?v=1796460510)


**What to do:** Compile llama.cpp with GPU support, then serve the GGUF over HTTP.

**Why:** `llama-server` gives you an OpenAI-style endpoint, so existing client code that talks to `/v1/chat/completions` works by changing only the base URL.

```bash
git clone https://github.com/ggml-org/llama.cpp
cd llama.cpp
cmake -B build -DGGML_CUDA=ON # macOS: -DGGML_METAL=ON instead
cmake --build build --config Release -j
```

Start the server:

```bash
./build/bin/llama-server \
 -m ./models/<gguf-file> \
 -c 8192 \
 -ngl 99 \
 -fa \
 --host 127.0.0.1 \
 --port 8080
```

- `-ngl 99` offloads every layer to the GPU. If you get an out-of-memory error, lower it (for example `-ngl 20`) to keep some layers on the CPU.
- `-c 8192` is the context window in tokens — the single biggest lever on KV-cache size.
- `-fa` enables Flash Attention where the build supports it; the flag name and availability vary between builds, so confirm with `./build/bin/llama-server --help | grep -i flash`.

**Example:** on a machine where the file fits comfortably, the server prints `llama server listening at http://127.0.0.1:8080` and stays in the foreground. In a second terminal, `curl http://127.0.0.1:8080/health` returns `{"status":"ok"}`.

If you are tuning this on a laptop with a discrete GPU and shared system memory, the layer-offload and context trade-offs are covered in more depth in [How to Run a Local LLM on a Ryzen 9 8940HX + RTX 5060 Laptop](https://ai-release.org/guides/kak-zapustit-lokalnuyu-llm-na-noutbuke-s-ryzen-9-8940hx.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).

**How to check:** send a real completion and confirm you get text back:

```bash
curl -s http://127.0.0.1:8080/v1/chat/completions \
 -H "Content-Type: application/json" \
 -d '{"model":"local","messages":[{"role":"user","content":"Reply with the word: ready"}],"max_tokens":16}'
```

Expected: JSON containing `"choices"` with a `message.content` field. In parallel, `nvidia-smi` should show the `llama-server` process holding VRAM close to your calculated budget.

## Step 3. Import the same GGUF into Ollama and verify GPU offload
![Illustration: Step 3. Import the same GGUF into Ollama and verify GPU offload](https://ai-release.org/guides/img/kak-zapustit-qwen4-lokalno-trebovaniya-k-vram-kvantizat-en-3.jpg?v=1796460514)


**What to do:** Create a Modelfile that points at the GGUF you already downloaded, register it locally, and check that Ollama runs it on the GPU.

**Why:** Ollama manages the server, model registry and context for you, which is convenient for scripting. Importing from a local file avoids downloading the weights a second time.

Create a file named `Modelfile` in the directory that contains your GGUF:

```
FROM ./models/<gguf-file>
PARAMETER num_ctx 8192
PARAMETER num_gpu 99
PARAMETER temperature 0.7
```

`num_ctx` sets the context window, `num_gpu 99` requests full GPU offload, and `temperature` controls sampling randomness. Then register and run it:

```bash
ollama create qwen4-local -f Modelfile
ollama run qwen4-local "Reply with the word: ready"
```

**Example:** the first command prints progress lines and ends with `success`. The second prints the model's answer to your prompt and drops you into an interactive session (exit with `/bye`).

**How to check:**

```bash
ollama ps
```

Expected: a row for `qwen4-local` with a SIZE column and a PROCESSOR column reading `100% GPU`. If it says `100% CPU`, the offload did not happen — see Troubleshooting. The API check is:

```bash
curl -s http://127.0.0.1:11434/api/generate \
 -d '{"model":"qwen4-local","prompt":"Say: ready","stream":false}'
```

Expected: JSON with a `"response"` field containing the answer.

Checklist before you call it done:

- [ ] `curl http://127.0.0.1:8080/health` returns `{"status":"ok"}`
- [ ] A chat completion on port 8080 returns non-empty content
- [ ] `ollama ps` shows `100% GPU` for `qwen4-local`
- [ ] `nvidia-smi` shows VRAM usage at or below your calculated budget

## Troubleshooting

**Problem. The server dies during model load with an allocation failure**

- Error: `ggml_backend_cuda_buffer_type_alloc_buffer: allocating 4096.00 MiB on device 0: cudaMalloc failed: out of memory`
- Cause: file size + context cache + overhead exceeds free VRAM. A larger `-c` value makes this worse because the KV cache grows linearly with context.
- Solution: cut the context first (`-c 4096`), then reduce offload (`-ngl 20`), then move to a smaller quantization. Confirm the new figure with `nvidia-smi` before retrying.

**Problem. The model refuses to load after a fresh build**

- Error: `llama_model_load: error loading model: unknown model architecture: 'qwen4'`
- Cause: your llama.cpp build predates support for this architecture — the loader does not recognize the architecture string stored in the GGUF metadata. This is common with new model families.
- Solution: update the source tree (`git pull`) and rebuild, then confirm the architecture is listed in the project's support matrix in the repository docs. If it is not listed yet, you cannot run this GGUF in llama.cpp — the model card for the supported runtimes. Do not patch around it by renaming files.

**Problem. Ollama rejects the model name or the import**

- Error: `Error: pull model manifest: file does not exist`
- Cause: `ollama run qwen4` was used with a tag that has no entry in the Ollama model library. Qwen4 may not be published there.
- Solution: always go through your local tag created in Step 3 — `ollama run qwen4-local`. If `ollama create` itself fails, check that the `FROM` path in the Modelfile is a real path relative to the Modelfile's directory, and that the file really is GGUF (`invalid magic characters` in the error means it is not).

## Summary and next steps

You now have the same Qwen4 GGUF served two ways — `llama-server` on port 8080 and Ollama on port 11434 — with a VRAM budget you can recompute for any context length or quantization. Next, wire one of these endpoints into your client code by pointing the base URL at `http://127.0.0.1:8080/v1` and keeping the API key field set to any non-empty string.

## FAQ

**How much VRAM do I need to run Qwen4 locally?**
It depends on the parameter count and the quantization you pick. Compute it: file size + KV cache (2 × layers × kv-heads × head-dim × context × 2 bytes) + roughly 1 GB of runtime overhead. Read the real layer and head counts from the load log as shown in Step 1, and take the file size from the Hugging Face repo listing.

**Does Ollama have an official Qwen4 model?**
Check `ollama.com/library` before assuming. If there is no entry, download the GGUF yourself and import it with a `Modelfile` as in Step 3 — that path works with any GGUF file.

**Is Q4_K_M good enough, or should I use Q8_0?**
Use the largest quantization that fits in your VRAM with room for the context you need. `Q8_0` is about twice the size of `Q4_K_M` for the same model, so on consumer GPUs `Q4_K_M` is usually the practical choice.

**Can I run it without a GPU?**
Yes — build without CUDA/Metal and leave `-ngl 0`. It works, but tokens per second drop sharply, so prefer a smaller quantization and a smaller context.
