Running Large Language Models on Consumer GPUs: From VRAM Estimation to Concurrency Benchmarks
Deploying open-source LLMs on consumer GPUs often fails in three ways: the weights don't fit in VRAM, long contexts fill the remaining space with the KV cache, or the model repeats itself endlessly instead of stopping. This guide walks through all three: estimating VRAM requirements, choosing weight and KV cache precision, benchmarking concurrent throughput, and troubleshooting overthinking. Examples use llama.cpp; other frameworks use different parameter names, but the same checking logic applies. Community-published speed figures are rarely independently verified and usually lack complete scripts, so none are cited here—measure on your own hardware, models, and test conditions.
Introduction
Deploying open-source large language models on consumer GPUs typically runs into three problems: the weights don’t fit into VRAM, long contexts cause the KV cache to fill the remaining space, or the model repeats itself during generation and won’t stop. This article addresses these in order: first estimate VRAM, then choose quantization and KV cache precision, then benchmark concurrent throughput, and finally troubleshoot overthinking. Example commands use llama.cpp. Other frameworks use different parameter names, but the checking logic is the same.
Community-published speed figures are not independently verified, and most posts lack complete scripts, so this article does not cite them. Re-measure on your own hardware, models, and test conditions.
1. Estimate VRAM First to Check Whether Your Hardware Can Handle the Model
A VRAM budget consists of four parts: model weights, the KV cache, inference framework runtime overhead, and system/display usage.
1.1 Weight Memory
Weight memory (GB) ≈ parameter count (B) × bits per parameter ÷ 8.
A 30B model with INT4 quantization needs roughly 15 GB for weights. Actual files are usually somewhat larger. Formats like GGUF, EXL2, and AWQ add overhead for scale factors, group metadata, and layers kept at higher precision. Base your estimate on the actual model file size, and verify it in the logs after loading.
1.2 KV Cache Memory
The KV cache grows linearly with context length and the number of concurrent sequences. The formula:
KV cache bytes = 2 × layers × KV heads × head dim × context length × concurrency × bytes per element
The factor of 2 accounts for the K and V caches. The layer count, KV head count, and head dimension are in the model’s config.json, typically under num_hidden_layers, num_key_value_heads, and head_dim.
Some config files omit head_dim. In that case, derive it as hidden_size ÷ num_attention_heads. If the result conflicts with official documentation, trust the documentation.
The formula only estimates the main body of the KV cache. Frameworks also consume extra VRAM for paging, memory alignment, and fragmentation. It does not apply to models with special attention structures such as MLA. Sliding-window and hybrid attention make actual usage lower than the formula predicts.
Example with hypothetical parameters: 60 layers, 8 KV heads, head dim 128, 100K token context, single sequence:
- FP16 (2 bytes per element): ~24.6 GB
- INT8 (1 byte per element): ~12.3 GB
These numbers only demonstrate the calculation and do not represent any specific model. Substitute your model’s actual configuration.
1.3 Total Budget Checklist
- Weights + KV cache + framework overhead + system usage ≤ total VRAM
- Keep headroom for VRAM peaks. Reserve at least 10–15% of total VRAM; confirm the final figure through testing.
- Estimate long context and concurrency separately. As concurrency increases, the KV cache usually becomes the bottleneck before the weights do.
- Size MoE models by total parameters, not by active parameters per token. All expert weights must reside in VRAM or system memory. Experts that don’t fit in VRAM are offloaded to memory, requiring data transfer across the bus during inference, which significantly slows things down.
After loading, the startup logs list the memory used by weights, the KV cache, and compute buffers, which you can use to verify your estimates. Monitor VRAM during runs with:
nvidia-smi —query-gpu=memory.used,memory.total —format=csv -l 1
Example: on a GPU with 22 GB of VRAM, a 30B model with INT4 weights uses about 15 GB, leaving ~7 GB. Whether a 100K context fits depends on the model’s KV structure—confirm with the formula above or the loading logs rather than copying someone else’s results.
2. Choosing Weight and KV Cache Precision
Quantization affects VRAM usage, speed, and output quality simultaneously. Decide which matters most to you before choosing.
| Goal | Weight precision starting point | KV cache precision starting point | Main trade-off |
|---|---|---|---|
| Tight VRAM, need long context | INT4 | INT8 (q8_0 in llama.cpp) | Long-text quality needs dedicated validation |
| Ample VRAM, quality first | INT8 or higher | FP16 or BF16 | Higher VRAM usage, lower concurrency |
| High concurrency | INT4 or INT8 | INT8 | KV cache grows linearly with concurrency; throughput gains must be weighed against quality loss |
Selection principles:
- Fix weight precision first, then KV cache precision. Only consider more aggressive KV quantization if weights still don’t fit after dropping to your target precision.
- KV cache quantization usually affects long text more than weight quantization. Re-validate after any change.
- Change one variable at a time, and keep an FP16 baseline as a fallback.
Validation methods:
- Quality: compare perplexity across precisions on the same corpus. With llama.cpp, use llama-perplexity and specify the KV cache type via -ctk and -ctv. The corpus should resemble your use case, e.g., long documents or code.
- Tasks: prepare a fixed set of prompts, generate with temperature 0, and check whether key information is retained and formats are correct.
- Fallback: if long-text tasks start missing information or making reference errors, revert the KV cache to FP16 while keeping weight precision unchanged, and see if the problem disappears.
3. How to Benchmark Concurrent Throughput
Throughput tests must record the full test setup; otherwise results cannot be reproduced or compared with others. Record at least the following for each test:
- llama.cpp version (commit or release tag)
- Model file name, quantization format, and file size
- GPU model, driver version, and total VRAM
- Context length -c, parallel slots -np, and batch parameters -b and -ub
- Input length, output length, concurrency level, and number of repetitions
- Metrics: generation speed (tokens/s), time to first token (TTFT), and peak VRAM
Start with a single-sequence baseline using llama-bench. It doesn’t simulate concurrency but gives reference values for prompt processing and generation speed:
llama-bench -m model.gguf -p 512 -n 128 -b 2048 -ub 512 -ngl 99 -r 5 -o json
Then start the server:
llama-server -m model.gguf -c 32768 -np 4 -ngl 99 -fa on -ctk q8_0 -ctv q8_0 —port 8080
Two caveats. First, by default -c is the total context shared by all slots, so each slot gets roughly -c divided by -np. With -c 32768 and -np 4, each slot has only about 8192. Second, quantized V cache requires Flash Attention to be enabled. Parameter syntax varies across versions—check the —help output of your build.
The script below sends requests at different concurrency levels with fixed input. It disables prompt caching (cache_prompt set to false) to avoid inflated results.
import jsonimport timefrom concurrent.futures import ThreadPoolExecutorimport requestsURL = "http://127.0.0.1:8080/completion"PROMPT = "Explain in English what the KV cache does."N_PREDICT = 256CONCURRENCY = [1, 2, 4]REPEAT = 3def one_request(prompt):payload = {"prompt": prompt,"n_predict": N_PREDICT,"temperature": 0,"stream": True,"cache_prompt": False,}t0 = time.perf_counter()ttft = Nonetokens = 0with requests.post(URL, json=payload, stream=True, timeout=600) as r:r.raise_for_status()for line in r.iter_lines():if not line or not line.startswith(b"data: "):continueif ttft is None:ttft = time.perf_counter() - t0data = json.loads(line[6:])if data.get("stop"):tokens = data.get("tokens_predicted", 0)return ttft, tokensdef run_level(level):t0 = time.perf_counter()with ThreadPoolExecutor(max_workers=level) as pool:results = list(pool.map(one_request, [PROMPT] * level))wall = time.perf_counter() - t0total_tokens = sum(t for _, t in results)ttfts = sorted(x for x, _ in results)return {"concurrency": level,"wall_s": round(wall, 2),"total_tokens": total_tokens,"agg_tps": round(total_tokens / wall, 2),"ttft_median_s": round(ttfts[len(ttfts) // 2], 3),}if __name__ == "__main__":one_request(PROMPT) # Warm-up to exclude first-load overheadfor level in CONCURRENCY:for _ in range(REPEAT):print(json.dumps(run_level(level), ensure_ascii=False))
The script relies on the server returning the tokens_predicted field on completion. If your version uses a different field name, adjust based on the actual JSON response.
Meanwhile, record peak VRAM in another terminal:
nvidia-smi —query-gpu=memory.used —format=csv,noheader,nounits -l 1 > vram.log
After the test, take the maximum value from vram.log.
When interpreting results, note these patterns: if total throughput rises as concurrency increases but TTFT also rises, requests are queuing. If peak VRAM approaches the limit, reduce concurrency or context length. Take the median of several repetitions per concurrency level and report the min–max range.
4. Troubleshooting Overthinking
Overthinking means the model keeps generating, repeats the same passages, or extends its reasoning indefinitely until it hits the token limit. Check the following items in order:
- Model type. Confirm you’re using the instruct or chat version. Base models often fail to emit the end token at the right point.
- Chat template. Verify that the rendered template’s system, user, and assistant markers match the format the model was trained with. A wrong template prevents the end token from being recognized.
- EOS and stop sequences. Confirm the tokenizer’s EOS matches the end token the model actually outputs. Role-ending tokens in the chat format should be added to the stop sequence.
- Generation length limit. Set n_predict to a reasonable positive integer. In llama-server, n_predict = -1 means unlimited; a looping model will then occupy a slot until timeout.
- Prompts. Check that system prompts and task descriptions clearly specify output length and format, and that instructions don’t contradict each other.
- Sampling parameters. Near-zero temperature means greedy decoding, which can get stuck in loops; too high a temperature causes drift. Adjust top_p and min_p together rather than changing one alone.
- Repetition penalty. repeat_penalty = 1.0 means it’s disabled. If enabled, start with a mild value around 1.05. Too strong a penalty breaks code, tables, and list formatting.
- Reasoning tokens. If the model outputs thinking tags, confirm the framework parses them as expected and that reasoning content isn’t counted in the final output.
- Quantization effects. Compare FP16 or INT8 weights against the same prompts. If only the low-bit version loops, quantization is likely the cause.
- Log sampling. Save raw outputs, token counts, and stop reasons for 20–50 prompts. The proportion of runs ending with reason length directly reflects the severity of overthinking.
Working through these ten items usually locates the problem. Once found, change only one parameter and re-validate with the same sample set.
