4-Bit KV Cache on 28GB of Consumer VRAM: Running a ~27B Model at Full 256K Context
This article documents a practical experiment: running a ~27B parameter open-source model at full 256K context on two consumer GPUs with only 28GB of combined VRAM, using 4-bit weight quantization plus a 4-bit KV cache, at roughly 25GB peak VRAM. It breaks down the memory budget and where the KV cache cost per token lands, evaluates what 4-bit KV cache actually costs in instruction following, reasoning, and long-range retrieval, quantifies the severe prefill slowdown that appears as context grows toward 256K, and explains how to split the workload across mismatched GPUs with tensor or layer parallelism. Includes a generalized launch script, the pitfalls that are easy to hit, and deployment recommendations with an explicit list of caveats about generalizing the numbers.
1. Background and Goals
In document Q&A, code base comprehension, and multi-turn agent collaboration, long context has shifted from a nice-to-have to a baseline requirement. In practice, engineers run into a structural conflict: context windows keep growing, but available VRAM does not. For models of similar parameter count, moving from a few thousand tokens to hundreds of thousands multiplies the memory requirement several times over. A single card often cannot hold it at all, and heterogeneous compute across two devices only adds to the problem.
The goal of this experiment was specific: run a ~27B parameter open-source model at full 256K context on two consumer GPUs — no sliding window, no silently dropping history — and answer three questions:
- How should the memory budget be allocated, and is there room to optimize it?
- After 4-bit KV cache quantization, is the loss in model capability acceptable?
- How should a heterogeneous two-GPU setup be split to balance Prefill and Decode performance?
Test Environment
| Item | Configuration | Notes |
|---|---|---|
| GPUs | One 16GB + one 12GB consumer GPU | 28GB VRAM total; compute and memory bandwidth are mismatched |
| System RAM | 48GB | Weight loading, KV cache offload headroom, host-side buffers |
| CPU | Desktop-class 8-core | Tokenization, sampling, some CPU-side computation |
| OS | Debian 13 | — |
| Inference framework | General-purpose open-source inference engine | Exposes an HTTP server with an API compatible with mainstream calling conventions |
| Model | ~27B parameter open-source model (quantized) | Includes a vision projection module and multi-token prediction heads |
Key Parameters
- Context length: 256000
- GPU offloaded layers: all layers (offload layers set to 999, meaning no layers stay on the CPU)
- Quantization: model weights in a 4-bit low-bit format; both K and V cache at 4-bit
- Batch settings: logical batch 1024, physical batch 512
- Split strategy: tensor parallelism at a 2:1.5 ratio, roughly proportional to each card’s VRAM
- Device order: sorted by PCI bus ID, ensuring
cuda0maps to the 16GB card - Inference threads: 8
One caveat up front: all numbers below come from a single run on a single hardware configuration. They are meant to reveal trends and orders of magnitude, not to serve as a general performance baseline. Results can differ substantially with different memory bandwidth, driver versions, and model architectures.
2. The VRAM Budget: Where the 25GB Goes
At 256K context, measured VRAM usage for model weights, KV cache, the vision projection, and the multi-token prediction heads totals about 25GB, leaving roughly 3GB below the 28GB physical limit. That margin looks comfortable, but at runtime it is tight, for three reasons:
- Inference context cache: prompt caches and intermediate activations grow dynamically under long context, and at peak they can consume that 3GB;
- Multimodal input: if image input is added, the vision encoder’s intermediate activations take additional VRAM. This experiment did not stress-test the full multimodal path at long context;
- Driver and runtime overhead: the driver itself and compute graph buffers also consume memory that cannot be attributed cleanly to the model.
Roughly estimating from the typical weight size of a ~27B parameter 4-bit quantized model, weights land around 16–17GB, with the vision projection and multi-token prediction heads being a small fixed cost. Working backwards from there, the KV cache occupies about 8–9GB at 256K length, or roughly 30–35KB per token. That figure is the key to understanding long-context inference: doubling the context adds about 4GB of KV cache, while the weight cost stays constant.
The first engineering conclusion follows directly: in VRAM-constrained deployments, the KV cache deserves optimization attention ahead of the weights. The quality impact of weight quantization has been discussed extensively, but the payoff from KV cache quantization is just as direct and is often overlooked.
3. KV Cache Quantization: What 4-Bit Actually Costs
Instruction Following: Essentially Lossless
On instruction-following tasks, 4-bit KV cache showed no clear difference from the 8-bit (q8) version. Format constraints, multi-step instruction decomposition, and output structure all held up. This suggests instruction following depends mainly on the model’s parametric knowledge and output-layer behavior, and is not sensitive to the numerical precision of attention weights.
Reasoning: A Decline, but Within Acceptable Range
Compared with 8-bit, 4-bit KV cache showed a perceptible drop on reasoning tasks, though it stayed within an acceptable range overall. One notable pattern: the degradation seemed tied to the “thinking process” — longer reasoning chains, repeated self-confirmation, and occasional breaks in the chain. One plausible explanation is that the small numerical error introduced by KV cache quantization is amplified step by step through multi-step reasoning, lowering the model’s confidence at key decision points and producing visible hesitation.
Needle-in-a-Haystack Probe: Long-Context Retrieval Did Not Collapse
The test followed the widely used needle-in-a-haystack approach: insert several unique, verifiable pieces of information (specific IDs, specific facts) at different positions in a very long document, then ask about them within the 256K context to check whether the model can recall them accurately.
Probes placed between the 1/5 and 4/5 positions were all retrieved correctly. That is a fairly positive signal: 4-bit KV cache did not break the model’s long-range information retrieval ability, and the attention mechanism can still locate a target span accurately inside a massive context.
Overall Assessment: A Reasonable Trade of Precision for Capacity
Putting the three result sets together yields a fairly clear picture:
- Retrieval-style capabilities (search, localization, factual recall): insensitive to KV cache quantization;
- Instruction following: essentially no difference;
- Multi-step reasoning and long deductive chains: most sensitive, and the primary source of loss.
So if your workload is mainly long-document Q&A, code retrieval, and information summarization, 4-bit KV cache offers excellent value. If it is mainly complex logical deduction, multi-step math, and code generation, be careful: consider higher precision for K/V, or a shorter effective context length.
4. Prefill Degradation at Long Context: The Biggest Pain Point of This Experiment
Prefill processes the input prompt. It is compute-intensive and highly parallelizable. Decode generates tokens one at a time; it is memory-bandwidth-intensive and has low parallelism. Their performance characteristics are completely different, and so are the tuning strategies.
Measured Data
| Context length | Prefill throughput | Full Prefill time |
|---|---|---|
| 10K | 700–800 token/s | ~10 seconds |
| 100K | ~480 token/s | ~3.5 minutes |
| 200K | ~300 token/s | ~11 minutes |
| 256K | — | ~14 minutes |
Why the Throughput Falls
Throughput drops from 700+ to around 300 token/s, a decline of more than half. Three causes:
- Quadratic complexity of attention: during Prefill, every new token attends over all previous tokens, so the compute grows faster than linearly with context length;
- Linear growth in KV cache writes: the longer the context, the more KV data must be written each round, increasing pressure on memory bandwidth;
- Synchronization overhead on heterogeneous dual GPUs: the two cards are not compute-equivalent, so under tensor parallelism each card waits for the slower one to finish the round. Long sequences amplify that wait.
Direct Impact on Real Applications
The clearest victim of this decay is automated context management. When an agent framework hits the context limit and triggers automatic compaction — summarization, trimming, retrieval-based memory — the compaction pass itself requires the model to read the entire long context, which means another full Prefill. A 14-minute wait means one compaction blocks for over ten minutes, which is effectively unacceptable for an interactive experience.
Optimizations and Their Costs
| Approach | Effect on Prefill | Effect on Decode | Notes |
|---|---|---|---|
Layer split (layer mode) |
Improves | Degrades | More even VRAM distribution, less communication, but more pipeline bubbles |
| Larger batch | Improves | Essentially no effect | Raises parallelism, but limited by remaining VRAM |
Tensor split (tensor mode) |
Slightly worse | Better | Requires cross-card sync per token; friendlier to Decode |
| Trigger compaction earlier | Indirect improvement | — | Compress before hitting the limit instead of waiting for a super-long context |
The core trade-off: tensor split favors Decode, layer split favors Prefill. If the scenario is “load one very long document and then ask questions,” prioritize Prefill. If it is “multi-turn conversation with continuous generation,” prioritize Decode.
5. Splitting Across Heterogeneous Dual GPUs
The two cards in this experiment have 16GB and 12GB — a typical heterogeneous setup. Splitting evenly would make the smaller card overflow first.
Allocate VRAM Proportionally
Tensor split was set to 2:1.5, roughly proportional to each card’s VRAM capacity, to avoid an OOM on either card. In a heterogeneous environment this is the most basic and most important step.
Device Order Must Be Specified Explicitly
In multi-GPU environments, the device enumeration order is not guaranteed to match physical bus order. Set the order explicitly to sort by PCI bus ID, ensuring that logical cuda0 corresponds to the 16GB card. If the order is scrambled, the main card’s parameters apply to the smaller card, which causes load failures or a sharp drop in performance.
Choosing the Main Card
Set main_gpu to the card with more VRAM and stronger compute. The main card carries more of the compute graph and scheduling responsibility; choosing wrong clearly drags down overall throughput.
Trade-offs Between the Two Split Modes
- Tensor split: parallelism inside each layer. The per-token synchronization cost during Decode is relatively small, so generation is faster. During Prefill, communication is frequent and the synchronous wait becomes noticeable with long sequences.
- Layer split: different layers live on different cards, forming a pipeline. Prefill parallelism is higher and communication is lower. But Decode suffers pipeline bubbles, and the VRAM split must be balanced manually or one card ends up saturated while the other sits idle.
Recommendation: start with tensor split as the default, and evaluate switching only if Prefill becomes the bottleneck.
6. Launch Parameters You Can Copy
The configuration below is the one used in this experiment, generalized so it can be applied to similar deployments directly:
#!/usr/bin/env bashset -euo pipefail# ---------- Paths and basic configuration ----------SERVER_BIN="${SERVER_BIN:-/path/to/inference-engine/bin/server}"MODEL_PATH="${MODEL_PATH:-/path/to/model-4bit.gguf}"MMPROJ_PATH="${MMPROJ_PATH:-/path/to/mmproj-f16.gguf}" # Multimodal projection weightsHOST="${HOST:-0.0.0.0}"PORT="${PORT:-8080}"# ---------- Context and offloading ----------CTX_SIZE="${CTX_SIZE:-256000}" # Full contextGPU_LAYERS="${GPU_LAYERS:-999}" # Offload all layers to the GPU# ---------- Batching ----------THREADS="${THREADS:-8}" # CPU-side inference threadsBATCH_SIZE="${BATCH_SIZE:-1024}" # Logical batchUBATCH_SIZE="${UBATCH_SIZE:-512}" # Physical batch# ---------- KV cache quantization ----------CACHE_TYPE_K="${CACHE_TYPE_K:-q4_0}"CACHE_TYPE_V="${CACHE_TYPE_V:-q4_0}"# ---------- Multi-GPU split ----------GPU_IDS="${GPU_IDS:-0,1}"GPU_ORDER="pci_bus_id" # Sort by physical bus ID; specify explicitlySPLIT_MODE="${SPLIT_MODE:-tensor}" # tensor | layerMAIN_GPU="${MAIN_GPU:-0}" # Set main card to the one with more VRAMTENSOR_SPLIT="${TENSOR_SPLIT:-2,1.5}" # Proportional to VRAM capacity"$SERVER_BIN" \--model "$MODEL_PATH" \--mmproj "$MMPROJ_PATH" \--host "$HOST" --port "$PORT" \--ctx-size "$CTX_SIZE" \--n-gpu-layers "$GPU_LAYERS" \--threads "$THREADS" \--batch-size "$BATCH_SIZE" \--ubatch-size "$UBATCH_SIZE" \--cache-type-k "$CACHE_TYPE_K" \--cache-type-v "$CACHE_TYPE_V" \--device "$GPU_IDS" \--split-mode "$SPLIT_MODE" \--main-gpu "$MAIN_GPU" \--tensor-split "$TENSOR_SPLIT"
A few pitfalls that are easy to hit:
- Setting
UBATCH_SIZEto 512 rather than equal toBATCH_SIZEavoids intermediate activation overflow when physical VRAM is limited; GPU_LAYERS=999means offloading all layers. If VRAM is insufficient, lower it to keep some layers on the CPU, but Decode speed will drop noticeably;- The script exposes every key setting through environment variables, so configurations can be swapped quickly across machines without editing code.
7. Deployment Recommendations and Risks
Recommendations
- Choose quantization precision by workload. For search-, summarization-, and Q&A-heavy scenarios, 4-bit KV cache can go straight into production. For reasoning-heavy workloads, prefer higher K/V precision or a shorter context.
- Do not max out the context in one go. Since Prefill degrades significantly with length, context management should act early — compact proactively as you approach the limit rather than waiting for the threshold and then blocking.
- Build a VRAM budget table before picking parameters. List weights, KV cache (per-token cost × target length), multimodal activations, and driver overhead item by item, and reserve at least 10%–15% headroom.
- Always run probe tests before going live. Validate recall at the target length with a needle-in-a-haystack test. It is the cheapest way to detect whether quantization has quietly damaged long-range capability.
- Pick the split mode by scenario. For one-shot long document input, prefer layer split. For multi-turn continuous generation, prefer tensor split.
Risks
- These numbers come from one hardware configuration. Memory bandwidth, driver version, and model architecture differences can change the conclusions significantly, so they should not be extrapolated into a general baseline;
- Sustained full-load operation on two cards requires a separate thermal and power assessment. Consumer GPUs differ from data-center cards in stability under continuous heavy load;
- This experiment did not cover a full multimodal pipeline at long context. The VRAM peak when vision input is combined with very long text needs separate validation;
- A quantized model should go through a complete evaluation on your own business dataset before launch. Public leaderboards and probe tests cannot substitute for business acceptance.
