Skip to content

Running a 7B Model on 8 GB VRAM: Five Fixes for CUDA Out-of-Memory Errors

Scope: Ollama on a consumer 8 GB GPU (such as an RTX 4060 or an 8 GB RTX 3060) where ollama run fails to load a 7B-class model with an out-of-memory error, or runs but shows 100% CPU / a mixed ratio in ollama ps with a steep slowdown. Organized as "identify the error layer - do the VRAM math - five fixes", each with copyable commands and interpretation notes.

Short answer: an 8 GB card failing on a 7B model is rarely a broken GPU or a lack of Ollama support - it is almost always "looking only at the model file size and forgetting the KV cache and runtime overhead". The VRAM budget is the sum of weights, KV cache, and runtime overhead; any one of them growing can push total demand past the hard 8 GB ceiling. The Ollama official FAQ and hardware support page are the sources every command, parameter name, and causal claim here was checked against. Wherever a concrete number appears, it is marked "verify against your environment" because it varies with model, quantization tier, context, and concurrency - copying it blindly is pointless.

1. First, identify which layer is throwing the OOM

The first troubleshooting step is not to change a parameter but to confirm who is actually saying "out of memory". Different software stacks word this completely differently, and mixing them up sends you down the wrong path.

The PyTorch layer: in a Python script, Hugging Face Transformers, or a framework such as vLLM, a failed tensor allocation raises torch.cuda.OutOfMemoryError, usually with CUDA out of memory. Tried to allocate ... and a mention of PYTORCH_CUDA_ALLOC_CONF. This is a Python-level allocator error unrelated to Ollama; debug it against that framework's memory docs, since the num_ctx and KV cache notes below do not transfer to PyTorch. Wording changes by version - verify against your environment.

The Ollama / llama.cpp layer: Ollama goes through its own scheduler plus the llama.cpp GGML backend. The official FAQ says Ollama compares required with available VRAM at load time: a model that fits on one GPU loads there (best performance, less PCI traffic), and only then is splitting considered, with a single-GPU machine falling back to CPU. So on Ollama you usually see a scheduler-level "does not fit" message rather than the PyTorch Tried to allocate exception, or 100% CPU / a mixed ratio in ollama ps with a low offloaded numerator in the log. Wording evolves by version - verify against your environment.

Making this distinction matters: if the error contains Tried to allocate, do not read the Ollama parameters below yet; if it comes from the ollama run loading phase or from an abnormal ollama ps state, continue.

2. Do the VRAM math first: weights + KV cache + overhead

The official FAQ gives a revealing example in its concurrency section: parallel requests multiply the context by the number of requests, so a 2K context with 4 parallel requests results in an 8K context and additional memory allocation. That is about concurrency, but it exposes a general fact: the KV cache is not fixed - it grows with context length and concurrency together. The FAQ also has a dedicated section on K/V cache quantization, noting that the KV cache occupies a significant amount of memory and can be reduced through quantization.

So on an 8 GB card the budget goes like this:

total VRAM needed ~= model weights + KV cache + runtime overhead
weights: determined by parameter count and the model's own quantization tier (a property of the model file)
KV cache: grows with num_ctx context length and parallel request count; quantizable via OLLAMA_KV_CACHE_TYPE
runtime overhead: backend, compute buffers and other fixed/floating parts - verify against your environment

Even at a low tier, a 7B model's weights are substantial - check the file you pulled. Add the KV cache inflated by context and concurrency and crossing 8 GB is easy. That is why "the file looked small enough, but loading failed". The five fixes then aim to shrink weights, shrink the KV cache, or reduce what occupies VRAM at once. See LLM Quantization in Practice for how tiers affect weight size.

3. Fix 1: lower the weight quantization tier

Quantization compresses weights to lower precision: the lower the tier, the smaller the size, at the cost of precision. An Ollama model's weight tier is part of the model file, usually reflected in the tag (suffixes such as q4 or q8) - it is not a runtime switch, which is the distinction from the KV cache quantization in section 6. In practice you pull a tag with a lower tier; which tiers exist depends on the publisher, so verify against your environment.

ollama pull <model>:<lower-quant-tag>
ollama ps

After the swap, reload and check whether ollama ps PROCESSOR moved from 100% CPU or a mixed ratio to 100% GPU. When a lower tier lets the whole model fit in VRAM, speed usually improves qualitatively, since the FAQ states a whole model on one GPU reduces data transferring across the PCI bus. Caution: lower is not always better - aggressive tiers degrade output quality, especially on complex reasoning. The table in the Ollama Deployment Handbook helps judge a tier's magnitude; the real choice balances your task and the 8 GB ceiling.

4. Fix 2: shrink the context (num_ctx)

The second route is to press on one source of the KV cache: context length. The official FAQ confirms num_ctx controls context length and gives two ways to set it: /set parameter num_ctx <number> in an interactive session, and num_ctx inside the options object of an API request. The right value varies by model and version, so verify against your environment.

# inside an interactive session
/set parameter num_ctx 2048

# in an API request body
# "options": { "num_ctx": 2048 }

Shrinking context trades "how much it remembers" for VRAM: shorter context means a smaller KV cache, making it more likely total demand drops below 8 GB. This hurts long-document workloads most, so do not crush it to a tiny value - too little context makes the model lose earlier turns, trading correctness for VRAM. The method: return to the default or a conservative value to confirm loading, then raise it step by step until ollama ps starts showing a mixed ratio or loading fails - that is your local boundary. This fix often goes together with Fix 3, because concurrency multiplies the context again.

5. Fix 3: cut concurrency and resident models

The third route is to reduce "how many things are in VRAM at once". The official FAQ gives three related settings: OLLAMA_MAX_LOADED_MODELS caps how many models load concurrently (default 3 times the number of GPUs, or 3 for CPU inference); OLLAMA_NUM_PARALLEL caps how many parallel requests each model handles at once (when unset or zero, backends other than MLX default to 1; more parallel requests require more memory); and OLLAMA_MAX_QUEUE caps how many requests queue when busy (default 512). The same section notes that if a model is already resident and available memory is insufficient for a new one, new requests queue until prior models go idle and are unloaded.

ollama ps          # see exactly how many models are resident right now
ollama stop <name> # unload a resident model you do not need

Start with ollama ps and unload anything unused; then bring parallel requests back to 1 or a small number to avoid the 2K-times-4-becomes-8K amplification. Counterintuitively, the FAQ says under GPU inference a new model must fit entirely in VRAM to allow concurrent loading, so keeping two 7B models resident on an 8 GB card is almost guaranteed to fail - unloading one beats any parameter tweak. Queuing is not an error, but if the queue never drains, concurrency exceeds VRAM capacity. Defaults change with the version - verify against your environment.

6. Fix 4: quantize the KV cache (OLLAMA_KV_CACHE_TYPE)

The fourth route is the KV cache quantization switch the official FAQ explicitly documents: OLLAMA_KV_CACHE_TYPE. It sets the quantization type of the K/V context cache, default f16; options are q8_0 (8-bit, about half the memory of f16, very small precision loss) and q4_0 (4-bit, about a quarter, small-to-medium precision loss that may be more noticeable at larger contexts). The FAQ specifically notes that K/V cache quantization takes effect only when Flash Attention is enabled, and that it is a global option affecting all models.

# systemd service example: add to the [Service] section, then restart
Environment="OLLAMA_KV_CACHE_TYPE=q8_0"

This is the right fix for the "weights are already as low as they go, but opening a context still blows up" scenario, because it cuts the KV cache block directly. The cost: models with a high GQA count (the FAQ cites Qwen2) may see a larger precision impact, so experiment between VRAM and answer quality. Remember it does not touch weight size: use Fix 1 for weights and this one for the KV cache. The official text also says the impact depends on the model and task and needs experimentation - verify against your environment.

7. Fix 5: switch to a smaller model or a different inference engine

If all four fixes still do not fit, then a 7B at the scale you need on this 8 GB card plus your context is genuinely too large, and changing models is more honest than further tuning. Choose a model with fewer parameters, or a similar-sized one whose publisher offers a more compact quantization tier; the method is still to compare weight size plus estimated KV cache against 8 GB, with figures verified against your environment.

If your stack already runs GGUF directly through llama.cpp, you can bypass the Ollama scheduler and control context and GPU offload layers in startup flags, giving more room to maneuver; a Python stack can even move to a different inference engine. The choice depends on your memory budget, concurrency pattern, and ease-of-use requirements - see Inference Engine Selection on this site. Weigh the benefit of a stack switch yourself: do not introduce a whole new operational complexity just to save a few hundred MB.

8. Acceptance checklist before calling it done

  • Identified whether the error came from the PyTorch allocator or the Ollama scheduler; the two were not mixed
  • Did the "weights + KV cache + runtime overhead" math, with figures verified against your environment
  • ollama ps PROCESSOR reads 100% GPU or an acceptable high GPU share, not 100% CPU
  • Weights use an appropriate quantization tier, with output quality confirmed acceptable by the business
  • num_ctx was lowered only as far as recall still suffices; long-conversation cases were regression-tested
  • No extra resident models, and parallel requests reduced to what VRAM can sustain
  • If OLLAMA_KV_CACHE_TYPE is enabled, Flash Attention was confirmed active and precision impact evaluated
  • Recorded the model tag, Ollama version, and the ollama ps output at the time, for later comparison at the "verify against your environment" boundaries

One last principle: OOM is not a single fault but a budget problem. Determine whether weights, KV cache, or concurrent residency is overspending, then treat that cause - far faster than trying knobs at random. Walk these five steps manually once before automating; otherwise the script has no interpretation baseline.