Tuning a 27B-Class Model to 256K Context on Two Consumer GPUs (16GB + 12GB): A Practical Recap
This article documents a hands-on deployment and tuning session that pushes a 27B-class, 4-bit quantized open LLM from a native 32K window to 256K context on two consumer GPUs with asymmetric memory (16GB + 12GB). It covers the full VRAM budget (~25GB total, against a 28GB ceiling), an 8-bit vs. 4-bit KV Cache comparison across instruction following, multi-step reasoning, and needle-in-a-haystack retrieval, measured prefill throughput decay up to 200K context, the trade-offs between `row` and `layer` split modes, and a ready-to-edit llama.cpp launch script with a parameter checklist. It also flags RoPE linear scaling limits, GPU split initialization via `--tensor-split`, PCIe topology checks, and minimum hardening for the inference endpoint. The results are directional guidance rather than universal conclusions for every model.
Quick Takeaways
- On a 16GB + 12GB consumer dual-GPU setup, 4-bit weights plus 4-bit KV Cache fit a 27B-class model with a 256K context into roughly 25GB of VRAM — workable, but close to the 28GB total ceiling and definitely a high-pressure configuration.
- 4-bit KV Cache is usable overall: instruction following and long-range retrieval are largely preserved, while deeper reasoning degrades slightly. If reasoning quality matters, evaluate K and V separately and keep V at higher precision.
- The real UX bottleneck for long context is usually not model weights but prefill latency. With the test setup used here, a full 200K prefill takes about 11 minutes, at roughly 300 tokens/s.
- There is no single right multi-GPU strategy:
rowsplitting gives more stable decode, whilelayersplitting delivers higher prefill throughput and suits read-heavy, one-shot workloads such as long-document Q&A and batch summarization.
1. Scope and Reproducibility
This article records a consumer dual-GPU long-context deployment and tuning exercise aimed at scenarios that need to ingest large amounts of context in a single pass: agent orchestration, long-document Q&A, and whole-repository code understanding. The goal was to extend a 27B-class model to a 256K context on asymmetric GPUs (16GB and 12GB) while keeping it usable.
One caveat up front: the specific model is not disclosed here. What follows is measured behavior for “27B-class, 4-bit quantized, native 32K, extended to 256K.” Treat the conclusions as tuning direction, not as universal findings for every model.
Baseline setup:
| Item | Configuration |
|---|---|
| GPUs | 2 × consumer GPU, 16GB + 12GB VRAM |
| RAM | 48GB DDR5 |
| CPU | Mainstream desktop multi-core |
| OS | Linux 64-bit |
| Inference framework | llama.cpp / llama-server, b7038 or similar |
| Model | 27B-class open LLM, 4-bit quantized weights |
| Native context | 32K |
| Target context | 256K |
| KV Cache precision | K and V both set to 4-bit |
Two constraints need emphasizing:
- The two cards are asymmetric (16GB vs. 12GB), so the load cannot simply be split 50/50. It must be skewed toward the larger card, but the exact ratio has to be validated against the observed OOM boundary.
- At a 256K target, 4-bit weights and 4-bit KV Cache are both required to bring total VRAM usage down to roughly 25GB. Reverting to 8-bit KV Cache brings the memory bottleneck straight back.
Separately, the 48GB of DDR5 RAM plays three roles in this kind of setup: hosting the model mmap and any layers not offloaded to GPU, supporting CPU threads that handle tokenization and scheduling, and absorbing some CPU offload when needed. It cannot substitute for VRAM, but it does affect system stability and startup time.
2. VRAM Budget: How ~25GB Adds Up
Total VRAM usage in this configuration lands around 25GB, broken down roughly as follows:
| Component | Approx. usage | Notes |
|---|---|---|
| 4-bit model weights | ~14GB | The main cost; distributed across both cards by the split strategy |
| 256K 4-bit KV Cache | ~9GB | Grows linearly with context length; the largest variable |
| Multimodal projector file | ~0.5GB | If an mmproj is loaded, usually placed entirely on the main GPU |
| Additional modules | ~0.3GB or negligible | Counted only if such modules are actually loaded |
| Driver, context headroom, runtime overhead | ~1GB+ | Not negligible at peak |
| Total | ~25GB | Corresponds to the 256K context target |
That “~25GB” is explicitly tied to a 256K context. Drop the context to 100K or 200K and KV Cache shrinks noticeably, easing the pressure. But since the target is 256K, peak estimates cannot be based on short-context headroom.
Because the model architecture is not disclosed here, the 9GB KV Cache figure was derived by back-calculating from post-startup VRAM usage. To check it yourself, estimate with:
KV Cache bytes ≈ context_length × 2 × num_layers × kv_heads × head_dim × bytes_per_element
K and V are each counted once; 8-bit is roughly 1 byte per element and 4-bit roughly 0.5 bytes per element, plus a small amount of quantization metadata. If the startup log shows KV Cache well over budget, check context length, KV precision, the number of KV heads, and whether an extra cache was enabled by accident.
For the dual-card split, this setup used the 16GB:12GB capacity ratio as a starting point. That is not a fixed ratio but an initial allocation based on card capacity. Under row splitting, weights and compute are distributed across cards. Under layer splitting, layers are assigned to different cards and KV Cache is distributed by layer. The two modes carry different meanings for allocation, and switching between them invalidates any intuition carried over from the other mode.
3. 4-Bit KV Cache: Usable, Not Lossless
With VRAM this tight, pushing KV Cache from 8-bit to 4-bit is close to mandatory. Quantization loses information; the question is whether the loss is acceptable. This test compared 8-bit and 4-bit KV Cache using the same set of prompts and the same random seed.
Instruction Following
Samples: 20 tasks covering format requirements, role/character constraints, and output restrictions.
Scoring: manual, focused on format violations, ignored roles, and failure to respect output boundaries.
Controlled conditions: identical prompts, identical seed, identical model weights; only cache-type-k and cache-type-v were switched.
Result: no clearly unusable degradation under 4-bit KV Cache. The model still handled surface-level constraints well, such as “output JSON only,” “do not explain,” and “answer following this template.”
Reasoning
Samples: 30 multi-step reasoning tasks, including conditional judgments, numeric calculations, table summarization, and causal-chain analysis.
Scoring: automatic answer validation plus manual review, focused on broken reasoning chains, drifting off target, and missed key conditions.
Result: compared with 8-bit, multi-step reasoning quality dropped under 4-bit. On some of the harder tasks, when the model tried to “think deeper,” the reasoning chain tended to get shorter, skip steps, or drift. Overall it stayed in an acceptable range, but 4-bit is not advisable without testing for high-reliability reasoning workloads.
Long-Range Retrieval
Samples: 50 needle-in-a-haystack retrieval tasks.
Method: target information was planted at depths from roughly 1/5 to 4/5 of a 200K sequence.
Result: the model recalled the target correctly at all of these positions. Even with KV Cache compressed to 4-bit, the “addressing” ability of long-range attention is essentially retained.
Risks of 4-Bit KV Cache
- Compare K and V separately. In practice, V quantization tends to be more sensitive, while K quantization tolerates loss more readily.
- If preserving accuracy is the priority, consider quantizing only K to 4-bit and returning V to 8-bit or fp16, trading a little VRAM for more stable reasoning quality.
- The claim “4-bit long context is usable overall” holds only for the hardware, model, quantization format, and test samples used here. Do not generalize it to every model.
- Before shipping to production, run regression tests on 4-bit output, especially JSON formatting, numeric calculations, compliance/regulatory Q&A, and multi-step reasoning.
4. Prefill Decay and Optimization
Once the KV Cache problem was solved, a second bottleneck surfaced: prefill throughput decays sharply as context grows. Because prefill compute grows superlinearly with sequence length, time-to-first-token on long sequences rises steeply.
Test conditions: llama.cpp b7038 or similar, batch-size 1024, ubatch-size 512, row splitting, flash attention enabled, chunked prefill not enabled, with timing measured from request dispatch to prefill completion. To reduce sporadic noise, it is worth fixing the same long prompt, running it three times and taking the median, and recording the PCIe/CUDA topology.
| Context length | Approx. prefill throughput | Approx. full prefill time |
|---|---|---|
| 10K | 700–800 tokens/s | 13 seconds |
| 100K | 480 tokens/s | 3.5 minutes |
| 200K | 300 tokens/s | 11 minutes |
Throughput falls from 700–800 tokens/s at 10K to about 480 at 100K, and to roughly 300 at 200K. Absolute throughput drops while the sequence itself keeps growing; the two effects compound, and a full 200K prefill ends up taking about 11 minutes.
This hits agent scenarios directly. When context approaches the limit, the outer orchestration layer triggers summarization, rolling windows, or compression — and the compressed result usually still needs a substantial prefill. If a single compression round costs ten-plus minutes, the whole interaction cadence slows down badly.
More precisely: with VRAM already squeezed to about 25GB against a 28GB total ceiling, prefill latency becomes the new primary bottleneck — but VRAM remains the hard constraint. Reverting to 8-bit KV Cache moves the bottleneck back to memory rather than automatically converting it into a latency problem.
How to Shorten a Full Prefill
- Increase batch and ubatch: raise them step by step within available VRAM, watching prefill throughput against the OOM boundary.
- Enable chunked prefill: total time may rise slightly, but peak memory per step drops and interaction stability improves.
- Improve prefix cache hit rate: do not re-send system prompts, fixed document headers, and tool descriptions on every call.
- Control context growth: more aggressive history compression reduces the size of each prefill.
- For read-heavy workloads, switch to
layersplitting: it generally raises prefill throughput, at the cost of decode speed. - Watch the PCIe lanes: if the link drops to x8 or x4, or cross-card traffic is heavy, both prefill and decode suffer. Check the topology first:
nvidia-smi topo -m
If the two cards are connected over PCIe rather than a high-speed interconnect, row mode pays a higher cross-card communication cost and needs to be stress-tested carefully.
5. Multi-GPU Splitting: row or layer
Against prefill decay, optimization comes from two directions: how the load is divided across the two cards, and how many tokens are fed per step.
row: Row Splitting / Tensor-Parallel Direction
In llama.cpp terms, --split-mode row typically splits large layers or tensor computations across multiple cards so they complete cooperatively. The advantage is more even per-card VRAM pressure and more stable token-by-token generation during decode. The drawback is that cross-card communication overhead limits parallel efficiency during prefill — and with insufficient PCIe bandwidth, row mode can itself become the prefill bottleneck.
In single-run observations here, row mode decoded at about 11–14 tokens/s versus about 8–11 tokens/s for layer. This is not a strict benchmark; it is only meant to indicate the trend. For read-heavy workloads — one-shot long-document Q&A, batch summarization, codebase retrieval — layer is the better fit. For workloads that “think as they speak” — multi-turn conversation, long-form generation, step-by-step agent execution — row is more stable.
layer: Layer Splitting
--split-mode layer places entire layers on different cards, with inter-card communication concentrated at layer boundaries. The advantage is that each card can complete its own portion of the layers independently, and prefill throughput is usually higher. The drawback is that during decode, activations must be passed between cards for every generated token, making the per-token pipeline slower.
How to Read tensor_split
This setup used --tensor-split 16,12 as the initial allocation for a 16GB + 12GB dual-card configuration. It should not be read as a fixed “2:1.5” ratio, but as one initial skew based on card capacity. Different llama.cpp versions may handle --tensor-split values as integers, ratios, or fractions differently, so it must be validated against the startup log and the OOM boundary.
Note in particular:
- Under
rowmode, it mainly governs how large layers/tensor computations are distributed; KV may also be spread across heads or related dimensions. - Under
layermode, it affects layer assignment and KV layout, and cannot be equated with a simple weight split ratio. - After switching
--split-mode, the meaning of the existing--tensor-splitvalues changes; re-observe the OOM boundary and throughput. - If startup fails or VRAM overflows, do not mechanically reuse 2:1.5 — try an even split, an integer ratio, or values re-derived from measured capacity.
6. Launch Script and Parameter Checklist
The script below is cleaned up and ready to run after editing the paths. It targets llama.cpp / llama-server, b7038 or similar; forks and other engine versions may use slightly different flag names.
#!/usr/bin/env bashset -euo pipefailMODEL_PATH="/models/27b-q4_k_m.gguf"CTX_SIZE=256000NGPU_LAYERS=999THREADS=8BATCH_SIZE=1024UBATCH_SIZE=512# row: row splitting / tensor-parallel direction; layer: layer splitting; none: single GPUSPLIT_MODE=rowMAIN_GPU=0# Initial allocation for 16GB:12GB dual cards, not a fixed 2:1.5 — validate per versionTENSOR_SPLIT="16,12"# Native 32K extended to 256K, linear RoPE scaling factor 8ROPE_SCALE=8llama-server \--model "${MODEL_PATH}" \--ctx-size "${CTX_SIZE}" \--n-gpu-layers "${NGPU_LAYERS}" \--threads "${THREADS}" \--batch-size "${BATCH_SIZE}" \--ubatch-size "${UBATCH_SIZE}" \--flash-attn \--cache-type-k q4_0 \--cache-type-v q4_0 \--rope-scaling linear \--rope-scale "${ROPE_SCALE}" \--split-mode "${SPLIT_MODE}" \--tensor-split "${TENSOR_SPLIT}" \--main-gpu "${MAIN_GPU}" \--keep -1 \--host 127.0.0.1 \--port 8080
Key Parameter Checklist
| Parameter | Purpose | Recommended value / guidance | Risks and verification |
|---|---|---|---|
--ctx-size 256000 |
Target context | Lower the context first if VRAM is short | Do not stack batch increases blindly just to keep the context |
--n-gpu-layers 999 |
Offload as much as possible to GPU | Use when VRAM allows | Lower it and observe if OOM occurs |
--flash-attn |
Long-context attention optimization | Recommended | Leaving it off may increase VRAM overhead |
--cache-type-k q4_0 |
4-bit K cache | Usable when VRAM is tight | Assess instruction following and retrieval quality |
--cache-type-v q4_0 |
4-bit V cache | Consider keeping 8-bit or fp16 if reasoning quality matters | V quantization may be more sensitive |
--split-mode row |
Row splitting / tensor parallel | Prefer for decode-first workloads | Prefill may slow down on weak PCIe |
--split-mode layer |
Layer splitting | Worth trying for read-heavy workloads | Decode may degrade |
--tensor-split 16,12 |
Initial dual-card allocation | Set from card capacity | Not a fixed ratio; requires empirical validation |
--rope-scaling linear |
Extend 32K to 256K | Factor 8 | Linear scaling can degrade quality |
--keep -1 |
Preserve initial context | Recommended | Otherwise long context may be truncated |
--host 127.0.0.1 |
Listen address | Prefer loopback | Do not default to binding 0.0.0.0 |
Limits of RoPE Scaling
This setup used --rope-scaling linear --rope-scale 8 because the model’s native context is 32K and reaching 256K requires 8× linear scaling. Linear RoPE is not free: the longer the context, the more pressure on position-encoding extrapolation, which can lead to degraded long-range quality, unstable numeric tasks, or abnormal attention distributions.
If long-context quality matters, evaluate these alternatives or checks:
- If the engine version supports it, try Yarn or another RoPE scaling scheme and compare it against linear.
- Test needle retrieval, numeric calculations, and multi-turn instruction following separately at 100K, 200K, and 256K.
- Watch for position drift, repetition, loss of mid-sequence information, or a tail bias.
- If quality degrades noticeably under linear, prefer reducing context, raising KV precision, or switching to retrieval augmentation instead of stuffing everything into a single pass.
Security Note
Binding the inference service directly to 0.0.0.0 exposes the endpoint to the LAN or the public internet. For a personal workstation or an internal corporate service, at minimum add the following:
- Bind to
127.0.0.1by default and use a reverse proxy for remote access. - Add an API key, authentication, or access token.
- Restrict source IPs and configure a firewall.
- Log access records and audit inference requests.
- Regression-test 4-bit output, especially JSON formatting, numeric calculations, and regulatory Q&A.
7. Conclusions and FAQ
This consumer dual-GPU setup with a 256K context yields four key conclusions:
- 4-bit KV Cache is usable overall, but not free. Instruction following and long-range retrieval are largely preserved while deeper reasoning degrades slightly, so evaluate K and V separately per workload.
- Prefill latency is the main bottleneck for putting long context into practice. A full 200K prefill takes about 11 minutes, directly slowing down agent compression, rolling-window, and retry flows.
- There is no single right split mode.
rowstabilizes decode,layerraises prefill throughput; choose based on whether the workload is read-heavy or think-as-you-speak. - Parameters must be tuned together.
tensor_splitneeds an initial allocation based on 16GB vs. 12GB capacity, batch and ubatch need to balance throughput against OOM, and RoPE scaling, flash attention, andkeepmust not be overlooked.
What If VRAM Is Not Enough?
Lower the context length first, then batch and ubatch, and only then consider trimming the projector, auxiliary modules, or CPU offload. If 256K must be preserved, 4-bit KV Cache is usually the floor. If quality is insufficient, keep V at 8-bit or fp16 rather than reverting KV Cache as a whole to 8-bit.
What If Long-Document Prefill Is Too Slow?
Raise the prefix cache hit rate first, then evaluate batch and ubatch. If the workload is a one-shot read of a long document, switch to layer splitting. If latency requirements are strict, reduce the single input length and move to a summarization, retrieval, and chunked-summarization pipeline.
How Should tensor_split Be Set?
On a 16GB + 12GB dual-card setup, --tensor-split 16,12 works as an initial value, but it should not be treated as a fixed 2:1.5. Different llama.cpp versions handle the parameter format and ratio semantics differently, so validate against the startup log, peak VRAM, and the OOM boundary. If startup fails, try an even split or a more conservative integer ratio.
Should V Precision Be Reduced at 256K?
Keep V at 8-bit or fp16 if VRAM allows. In practice V quantization tends to be more sensitive than K, with a more visible impact on numeric calculations, long-range retrieval, and deeper reasoning. Start with 4-bit K and 8-bit V as a comparison, then decide whether to compress everything.
What Are the Common Mistakes?
Common mistakes include: binding 0.0.0.0 with no authentication, leaving flash attention off, forgetting RoPE scaling, assuming 4-bit KV Cache is lossless, omitting keep and having context truncated, mechanically applying row-mode tensor_split intuition in layer mode, and expecting high row-mode throughput without checking the PCIe topology.
