How Ollama KV cache quantization and Flash Attention free GPU memory for longer contexts
When a shared Ollama server runs out of VRAM because users send long prompts or several parallel requests at once, two server settings can reduce the memory it holds: Flash Attention and KV cache quantization. Both free headroom for longer contexts on the same GPU, and both trade some output quality and speed for that headroom. The KV cache stores the attention keys and values for every token already processed in a conversation or prompt, so it grows with context length and again with each parallel slot, since each slot keeps its own history. A model that fits comfortably at a short context can exhaust VRAM once several users send long documents. Teams should consider these settings before buying more hardware, especially when the bottleneck is context and concurrency rather than model size.
Flash Attention changes how attention is computed so the server needs less working memory during processing. KV cache quantization stores the cache at a lower precision, with q8_0 and q4_0 as the common reduced types, which saves more memory at the cost of more quality loss, especially at the smaller type. The effect differs by model architecture and by task, so test the chosen setting against your own prompts and a quality baseline before rollout. Because the setting applies to the whole server rather than to one model or one request, a change affects every model loaded on that instance. Confirm the exact variable names, accepted values and supported model architectures against the Ollama FAQ and the release notes for the version you run, since these details change between releases.
How model weights, KV cache and context fit together in VRAM
The diagram starts with the model weights, which load once per model and take a fixed share of GPU memory. The KV cache grows with each request's context length and with the number of parallel slots set by OLLAMA_NUM_PARALLEL, so it is the part you can shape. Flash Attention and the KV cache type act on that cache and the attention computation, while compute buffers sit alongside both. This is a simplified planning model, not an exact memory calculator: check actual usage with ollama ps and the server logs on your own hardware.
Simplified planning model of GPU memory consumers for one loaded model.
When Flash Attention turns on and what it changes
Flash Attention is a way of computing the attention step of a transformer model so that it uses less memory during inference. Instead of holding a full set of intermediate attention scores in memory at once, the computation works through the data in smaller blocks. The result is intended to be the same, while the memory needed for long inputs is lower. Whether it is active on your server is not a fixed property of Ollama. It depends on the Ollama version you run, the GPU backend that version uses for your card, and the architecture of the specific model you load. The same server can therefore enable it for one model and not another, so treat it as something to verify, not a default you inherit.
Start by reading the server log at startup and after loading each model you plan to serve. Look for an explicit line stating whether Flash Attention is enabled, and record the Ollama version next to it. Then check the Ollama GitHub releases page for the version you have pinned, because release notes are where changes to backend support and default behavior are announced. If the log does not confirm the setting for your combination of version, GPU and model, do not plan a longer context target around it. Ask the vendor or the project maintainers to confirm support for that exact combination, and document the answer in your change record so the next upgrade is checked against it.
Before you rely on Flash Attention to reach a longer context target, run a test on the same GPU, the same Ollama version, the same model and quantization, and the context length you intend to serve. Measure memory use under that load, using ollama ps and your GPU's own monitoring tools, and confirm the model stays fully on the GPU without spilling to CPU. Then measure response speed with the setting on and off where you can control it. A memory saving does not guarantee faster responses on your hardware, and the effect on throughput can be neutral or can differ between prompt processing and token generation. Record the results against the target so the decision to rely on the setting rests on your measurements rather than on general claims.
Which KV cache type and Flash Attention setting fit each goal
This table compares the default f16 KV cache, the q8_0 and q4_0 cache types, and Flash Attention on or off against the memory effect, quality risk, fitting workload and test you should run before adopting each setting. Read each row as a trade between context length and output fidelity, and confirm accepted values in the Ollama FAQ and the release notes for your installed version before you change anything.
| Setting | Memory effect | Quality risk | Fits this workload | Test before adopting |
|---|---|---|---|---|
| f16 KV cache (default) | Largest KV cache for a given context length, so it limits how much context fits on a GPU | Lowest risk, since it is the baseline most models are evaluated against | Quality-sensitive work such as clinical summaries, legal drafting or code review where context is modest | Record baseline answers on your own prompts so later changes have something to compare against |
| q8_0 KV cache | Reduces KV cache memory relative to f16, allowing a longer context or more parallel slots on the same GPU | Usually small for many models, but it varies by model and task, so it needs checking | Long document Q&A or retrieval prompts where moderate context growth matters more than exact wording | Compare factual accuracy, citations and formatting on a fixed test set at your target context length |
| q4_0 KV cache | Largest reduction in KV cache memory among these options, with the biggest context gain | Highest risk of degraded recall, instruction following and long-context accuracy | Experimental or low-stakes workloads such as drafting or triage where errors are cheap to catch | Run long-context recall tests and adversarial prompts, and check outputs against human review before any production use |
| Flash Attention off | Uses the standard attention path, so memory use is higher at long context | No quality change from the attention path itself | Hardware or model combinations where Flash Attention is unsupported or causes errors | Confirm the baseline runs cleanly and record memory use with ollama ps on your model |
| Flash Attention on | Lower attention memory at long context, and it is a prerequisite for some quantized KV cache types | Generally low on its own, but driver or model combinations can produce errors or slowdowns | Long-context serving on supported NVIDIA or AMD GPUs after the driver and version are confirmed | Verify the server log shows the setting applied, then repeat your baseline tests and compare throughput |
Where q8_0 and q4_0 cache quality loss tends to appear
Quantizing the KV cache saves memory by storing attention state at lower precision, and the loss is not uniform. The cards below name the workloads where output drift is most likely to show, the failure pattern to look for and a test to run on your own prompts before enabling q8_0 or q4_0 on a shared server.
Long-document retrieval
Quantized cache can blur exact recall when the answer sits deep in a long context, so the model cites the wrong clause, number or name while sounding confident. This is the workload where a longer window is most tempting, which makes it the one to check first. Build a set of questions whose answers sit at the start, middle and end of your longest real documents, then compare answers at f16 and at each quantized type. Count exact-match failures, not just overall fluency.
Code generation
Small syntax slips, such as a missing bracket, a renamed variable or an import that no longer matches earlier code, can appear only in longer sessions where earlier context is referenced. A fluent-looking answer can still fail to compile. Test with your own repositories: give the model a multi-file task, run the generated code or its unit tests, and record pass rates by cache type. Treat any drop in test results as a reason to keep the higher-precision setting.
Structured or JSON output
Quantization often shows up as a broken schema rather than a wrong sentence. A missing comma, a dropped required key or a changed enum value can break every downstream parser. Because the output looks plausible, this failure is easy to miss in spot checks. Run your real extraction prompts against a schema validator and measure the share of responses that parse and validate, for each model and cache type.
Multilingual text
Languages with less representation in a model's training data, or with non-Latin scripts and long compound words, can degrade more than English under lower-precision cache. Watch for shifted terminology, dropped diacritics, or answers that drift into another language mid-response. Build a test set in each language your users write in, include domain terms, and have a native speaker score the outputs. Do not assume a result in English carries over.
Small models
Smaller models have less redundancy, so the same cache precision reduction can cost more accuracy than it does on larger models. Quality loss is therefore not predictable from the cache type alone. Compare a small model at each cache type against its own full-precision baseline, and do not transfer a result from a larger model in the same family. Confirm the behavior for each model and quantization you plan to serve.
How to enable and verify KV cache quantization on an Ollama server
This sequence turns KV cache quantization from a setting you have read about into a measured change on your server. It records a baseline, applies one global configuration, confirms the server actually picked it up, and checks memory and output quality on a fixed prompt set before you rely on it.
Record a memory and output baseline
Before changing anything, the platform or inference engineer loads the target model with the current server settings and sends a request at the context length you need. Record VRAM use from nvidia-smi or rocm-smi, the processor split shown by ollama ps, and the response to a fixed set of prompts saved to a file. You are done when the baseline numbers and saved responses are written down with the model tag, Ollama version and date, so later results have something to be compared against.
Set Flash Attention and KV cache type
Confirm the configuration method for your install (Linux service override, container environment or workstation app settings) in the Ollama FAQ, then set the Flash Attention and KV cache type values there, such as q8_0 or q4_0. Confirm the exact variable names in the same documentation for your version. Both settings apply to the whole server, so every model loaded afterward uses them. You are done when the saved configuration shows both values, for example through systemctl show or docker inspect, and nothing else in the server environment has changed.
Restart the server and clear loaded models
The administrator restarts the Ollama service with the service manager in use, for example by restarting the systemd unit on Linux or the container on Docker. Stop any loaded models first so the new environment is applied to a clean start. Check that ollama ps reports no loaded models after the restart and that the API still answers on the address you expect, which is localhost on port 11434 by default. If the service fails to start, roll back the environment change before continuing.
Confirm the settings in the startup log
Read the server log from the restart using journalctl for a Linux service, the container log for Docker, or the app log for a workstation install. Look for entries that show Flash Attention and the KV cache type were read at startup, and compare the wording against the log format for your Ollama version, since messages change between releases. You are done when the log confirms both values. If the log does not show them, the setting did not take effect, and you should not treat any later memory figure as the result of quantization.
Load the target model at the planned context
Load the target model and send a request at the context length you plan to serve, the same length used for the baseline. Run ollama ps and the GPU monitoring tool again to record VRAM use and the processor split. Check that the model is fully on the GPU and has not spilled to CPU, because offloading can cost more speed than the memory saved by quantization. You are done when you have a second set of memory figures recorded side by side with the baseline at the same context length.
Compare output against the fixed prompt set
Run the same saved prompt set against the quantized configuration and compare each response with the baseline. Review factual accuracy, instruction following, formatting, and any answers that drift on long-context prompts, since quality effects differ by model. Record which prompts changed and how, then have a second reviewer sign off. You are done when the comparison is documented with the model, the KV cache type, the memory result and the reviewer decision, and the outcome is kept with the server configuration for future changes.
Why the KV cache setting applies to every model on the server
The Flash Attention and KV cache type settings are read by the Ollama server process when it starts, so they apply to every model that process loads, not to one model or one API call. A client cannot choose a cache type per request, and changing the setting for one model means changing it for all of them. Before you enable or change either setting, list every model the server will load, including embedding and vision models, and treat the server as one memory budget shared by all of them.
The same server-wide scope applies to the concurrency controls. OLLAMA_NUM_PARALLEL, OLLAMA_MAX_LOADED_MODELS and OLLAMA_MAX_QUEUE also apply to the whole server. Context memory is multiplied by the number of parallel slots, so a cache type that frees room for a longer context on one model also changes how many requests and models fit on the card. Size these settings together, because a gain in context length can be spent quickly if parallel requests or loaded models are not capped. Confirm the exact variable names and defaults for your installed version in the Ollama FAQ.
Teams that serve mixed models should test each model they plan to run, using their own prompts and a fixed evaluation set, before they change the server. A cache type that holds quality for one model family may reduce output quality for another, and the effect is not visible in memory numbers alone. Schedule a maintenance window for the change, since a restart unloads every loaded model and affects queued requests. Record the previous settings so you can roll back, and tell users which models will be retested before the change goes live.
Security and operational risks of changing memory settings on a shared server
Memory settings such as Flash Attention and KV cache type are server-wide environment changes, so their risks land on every user of the shared API at once. The cards below cover the controls to put in place before changing them, and the evidence to keep afterward.
Change control for server environment settings
Flash Attention and the KV cache type are set as environment variables on the Ollama server process, not per request. Treat each change as a production change: write down the variable, the old and new values, the reason, the approver and the window in which it took effect. Confirm with your team how the server is started (systemd unit, container, or shell) so you edit the file that actually governs the process, and restart it through your normal change path.
The local API has no authentication
The local API on port 11434 does not require authentication, so anyone who can reach the server can send requests, and every caller shares whatever memory settings the server was started with. A change that lowers output quality or shifts memory use affects all of them at once. Confirm the bind address and network exposure before any change, using the Ollama FAQ guidance on exposing the server through a proxy.
Ollama FAQKeep logs of active settings
Record which values the running server actually used, not only what the configuration file says. Keep server logs from each start, and note the Ollama version and environment at that time. Without this record, you cannot tell whether a complaint about answer quality or a failed load came from a memory change, a model update, or a different client. Check that log retention meets your own audit policy before you rely on it.
Silent output changes after upgrades
A new Ollama release can change how a setting behaves, and a model that loads fine may return different answers than before. Because the cache type and Flash Attention affect numerical results, a version change and a memory change can overlap in the same window. Pin the version you tested, schedule upgrades separately from memory changes, and rerun your reference prompts after each one.
Rollback planning
Before changing a setting, write the exact previous configuration and the steps to restore it, then confirm someone other than the author can execute them. Test the rollback on a staging server with the same model and GPU class. Define the signals that trigger a rollback, such as failed loads, out-of-memory errors in the logs, or quality complaints from a defined set of prompts.
Linking results to settings
Every evaluation run should record the model tag, quantization, Ollama version, Flash Attention state, KV cache type and context length used. Without those fields, results from before and after a change cannot be compared, and a quality regression can be attributed to the wrong cause. Store these alongside the evaluation output so a later audit can reproduce the result.
What to confirm before relying on these settings in your environment
On NVIDIA hardware, the settings depend on the GPU generation, the driver and the Ollama release running on the server. Support for a given feature can change between releases, so the behavior you tested last quarter may not match the server you deploy today. Confirm the current behavior before you standardize a configuration across a fleet.
- Flash Attention support: Confirm that your GPU family and Ollama version enable Flash Attention on your server, and check the server log after restart to see whether it was activated.
- KV cache type behavior: Confirm that the q8_0 and q4_0 cache types apply to the model architectures you run, since some models may ignore them or fall back.
- GPU selection: Confirm which devices the runtime sees when several NVIDIA cards are installed, so the memory you measured is the memory that is actually used.
- Driver and CUDA compatibility: Confirm the minimum driver version listed for your Ollama release against the driver installed on the host.
- CPU offload: Confirm with
ollama psthat the loaded model sits fully on the GPU at your target context length.
Check the Ollama GitHub releases and the Ollama FAQ for current behavior before you rely on these settings.
AMD deployments run through the ROCm stack, and the ROCm path may not support every feature the CUDA path supports. Treat AMD as a separate verification exercise rather than assuming NVIDIA results carry over. Confirm each point on the exact card and driver combination you plan to use.
- Backend support: Confirm that Flash Attention is available on your Radeon or Instinct family with the ROCm version your Ollama release uses.
- Supported GPU families: Confirm that your specific card appears in the supported list, and note any LLVM target override your team would need to apply.
- KV cache types: Confirm that q8_0 and q4_0 cache types are honored on ROCm for your model architectures, and test output quality on each one.
- Permissions and groups: Confirm that the service account running Ollama can access the GPU device files, or the runtime will silently fall back to CPU.
- Multi-GPU behavior: Confirm how the runtime splits models across AMD cards, since known multi-GPU issues may affect memory accounting.
Verify all of this against the Ollama GitHub releases notes for the version you deploy, and retest after every upgrade.
On CPU-only hosts, or on servers where some models run on the GPU and others spill into system RAM, the GPU-oriented settings may have little or no effect. Memory savings from a smaller KV cache only matter if the cache lives in the memory that is actually constrained. Confirm where each model is placed before you count on any saving.
- Placement check: Confirm with
ollama pswhether each loaded model runs on the GPU, the CPU or a split of both at your intended context length. - Flash Attention on CPU: Confirm whether Flash Attention changes anything on your CPU path, since the benefit is tied to the GPU backend.
- Mixed workloads: Confirm that a large model loaded for one team does not push a smaller model into offload, since loaded models compete for memory.
- Quality impact: Confirm output quality with your own prompts before you accept a quantized cache, because the quality trade-off varies by model.
- Logs: Confirm in the server log which backend initialized, and treat a CPU fallback you did not expect as a blocker for capacity planning.
When the placement check fails, the cache setting is not the fix. Re-check model size and context length against available memory, and confirm the current behavior in the Ollama FAQ.
In containers, the runtime variables must reach the process inside the container, and the GPU must be passed through with the correct driver libraries. A setting that works in a shell on the host may never reach the Ollama process in a container. Confirm the full path from your orchestration file to the running server.
- Environment passing: Confirm that the variables controlling Flash Attention and the KV cache type are set on the container itself, not only in the host shell or an unrelated config file.
- GPU passthrough: Confirm that the container runtime exposes the GPU devices and matching driver libraries, and that the container image version matches the host driver.
- Image version: Confirm which Ollama release your image tag contains, and compare it against the release notes for behavior changes.
- Restart behavior: Confirm that a restart or redeploy keeps the same settings, since the server reads them at startup.
- Verification inside the container: Confirm the active settings from the container logs and the loaded model placement with
ollama psexecuted inside the container.
Repeat these checks after every image update, and record the results with the release you tested.
Common questions about Ollama memory tuning and outside help
Does enabling KV cache quantization or Flash Attention cost money or need a license?
No separate license is needed to change these settings on Ollama itself. Ollama is open source under the MIT license, and its pricing page states that running models on your own hardware is always unlimited. The costs that remain are the staff time to test and document the change, the hardware you already own or buy, and any paid cloud plan you choose for hosted models, which is outside this topic. Model weights carry their own licenses, so check the terms of each model you run, since those terms are separate from the runtime license. Confirm the current license text in the Ollama GitHub repository before you write it into a policy.
How long does a memory tuning exercise take?
Duration depends on how much you need to prove, not on the setting itself, which is a few environment variables. The main drivers are the number of models you serve, because each model and quantization pair behaves differently, the evaluation scope, meaning how many tasks and languages you test for quality, and the volume of production traffic you replay to check latency and memory under load. A single model with a small prompt set can be tested quickly. Several models with domain-specific evaluations, plus a rollback plan and a maintenance window, take considerably longer. Ask any partner for a written plan that lists the models, test sets and replay volume before agreeing a timeline.
What does the work need from our team?
You need four things before testing starts. First, a representative set of test prompts drawn from real workloads, with expected answers or grading criteria where possible. Second, a GPU host that matches your production hardware, so memory numbers carry over. Third, a maintenance window for restarts, since changes to server environment variables take effect when the Ollama server restarts. Fourth, a named owner for evaluation who can accept or reject quality results. Without that owner, test results tend to stall. Your security team should also review which prompts and outputs are stored during testing, because those files may contain sensitive data.
Can our own engineers do this without outside help?
Yes, a capable platform or ML engineer can enable Flash Attention, test a q8_0 or q4_0 cache type, and measure memory use on one server. The setup is documented and reversible. Outside help becomes more useful when several models share one server, since the setting applies globally to every model on that server, or when you need a written evaluation record for an internal review. Teams with no spare capacity for test design often find the evaluation the slowest part, not the configuration. Start with one model and a fixed prompt set, and expand only after the first results are reviewed.
When should we hire a partner for evaluation design and rollout?
Consider a partner when the quality decision carries business or compliance weight, or when several teams depend on the same server. A partner can help design the evaluation, choose test sets that reflect your workloads, document the results and plan the rollout with a rollback path. DeployOpen plans and implements self-hosted open-source platforms in infrastructure you control, and prepares systems and evidence for compliance assessments, but it does not issue audit reports or certifications. Engagements are normally fixed-scope, with scope, deliverables and timelines agreed in writing before work starts, and a quote follows from that written scope. Ask for the evaluation method, the list of models, and the acceptance criteria in the scope document.
How do we detect a quality regression after enabling a quantized KV cache?
Detect it with a fixed evaluation run, not by spot checks. Build a baseline by running the same prompts against the default cache type and saving the outputs. Then run the same prompts against the candidate setting and compare results with an agreed grading method, such as exact-match checks for structured output, rubric scoring for free text, and human review for a sample. Include long-context prompts, because quantization effects can differ as the context grows. Track memory use and latency alongside quality. Repeat the run after any model update or Ollama version change, since behavior can shift between releases.
Do these settings change how sensitive data is handled?
The settings change memory use and output behavior, not where data is sent. When Ollama runs locally, it states that it does not see your prompts or data, so the risk lies in how your team stores test prompts, logs and outputs during evaluation. Keep test data under the same access rules as production data, restrict who can read server logs, and decide retention before testing starts. Confirm the current data handling statements in the Ollama FAQ and check that cloud features are disabled on servers that must stay local, for example with OLLAMA_NO_CLOUD=1.
How DeployOpen scopes and delivers Ollama memory tuning
DeployOpen treats KV cache type and Flash Attention as configuration decisions to test against your models, context lengths and quality requirements, not as defaults to switch on. We run the work on Ollama servers inside infrastructure you control, then hand over settings, measurements and a runbook your team can maintain.
How we scope
- We inventory the models, context lengths and concurrency targets the server must serve before choosing any cache setting.
- The written scope names the GPUs, Ollama version, model list and quality checks that define acceptable KV cache trade-offs.
- Engagements are fixed-scope, with deliverables and timelines agreed in writing before work starts, and a quote follows from that scope.
How we build
- We measure VRAM use and loaded model memory at baseline, then test Flash Attention and q8_0 or q4_0 cache types against that baseline.
- We compare answers from each configuration on your own prompts, flagging quality loss by model before any setting reaches production.
- We apply the chosen values to the server service configuration and confirm they hold after restart and under parallel load.
How we hand over
- You receive the final environment settings, the reasoning for each choice and the measured memory results for each tested model.
- The runbook explains that the Flash Attention and KV cache settings are server-wide, so changing one model's cache affects every model on that server.
- We document how to repeat the tests after an Ollama upgrade, since release notes and behavior can change between versions.
How we support
- Ongoing support, upgrades and continuous testing are available as retainers, including retesting when you add models or change context targets.
- Support covers checking memory behavior after Ollama releases, so a version change does not silently alter the quality trade-offs you accepted.
- Ask any provider to confirm in writing which Ollama versions, models and hardware the retest and support cover.

