Local LLM Deployment: A Practical Guide to Automatic VRAM and Inference Parameter Tuning
Running large language models locally often underperforms because inference tools ship with conservative defaults. This article explains how to tune local LLM deployments methodically: offloading MoE expert layers to the CPU, choosing KV cache precision based on measured trade-offs, using binary probing instead of rule-of-thumb formulas to find the maximum context length, matching parallel session counts to actual usage, benchmarking micro-batch sizes, and handling long-context compression without blocking the main conversation. A step-by-step tuning workflow is included.
1. Why Default Parameters Waste Your GPU
Local inference tools typically ship with conservative defaults designed to ensure the model launches, not to extract maximum performance from your hardware. Three problems are common. First, frameworks try to place as many layers as possible into VRAM, but when VRAM runs short, the system degrades into memory swapping and speed collapses. Second, multiple parallel sessions are enabled by default, splitting VRAM evenly across sessions—so in single-user scenarios, each session’s cache space is unnecessarily compressed. Third, context length, cache precision, and batch size constrain one another, so tuning any single parameter in isolation rarely yields the optimal result.
The core of tuning is therefore to define the constraints first (VRAM capacity, model architecture, usage scenario), then let measured data determine each parameter’s value. The sections below go through them one category at a time.
2. MoE Models: Layer-Wise Split Offloading
A Mixture of Experts (MoE) model consists of many expert sub-networks plus a routing module. Each token activates only a few experts, so the total parameter count is large while per-step computation stays small. This structure means its offloading strategy differs from that of dense models.
Attention layers participate in every step and are accessed frequently, so they belong on the GPU. Expert weights are bulky but only partially used on each pass, so keeping them in host memory with CPU-side computation has a relatively contained impact on overall speed.
On an 8GB GPU, a 30B-total-parameter MoE model has two typical configurations:
| Configuration | VRAM Usage | Generation Speed |
|---|---|---|
| All layers in VRAM | 7549 MB (~93%) | 3 tok/s |
| Attention layers on GPU, expert layers on CPU | 2603 MB (~32%) | 21 tok/s |
The second approach is roughly 7x faster while using about 65% less VRAM. The reason: the first configuration keeps VRAM near saturation, and frequent allocation and swap-in/swap-out operations slow down the entire pipeline.
Implementing this strategy takes two steps. First, identify which tensors are expert weights—usually by matching an expert identifier in the tensor names. Then, at load time, assign those tensors to the CPU. Below is illustrative pseudocode; the exact syntax depends on your inference framework:
def build_offload_rules(tensor_names):rules = {}for name in tensor_names:# Expert weights are large and sparsely accessed; keep them in host memoryif "expert" in name or "exps" in name:rules[name] = "cpu"else:# High-frequency layers like attention and normalization go to the GPUrules[name] = "gpu"return rules
In practice, enumerate the tensor list first and confirm the naming convention before writing match conditions, to avoid misclassification.
3. KV Cache: Trading Precision for VRAM
The KV cache stores the key and value vectors of historical tokens for every layer; the longer the context, the larger the cache. Its VRAM footprint can be estimated as:
KV_MB = 2 × layers × kv_heads × head_dim × ctx × bytes / 1024²
Here, the factor of 2 accounts for keys and values, layers is the layer count, kv_heads is the number of key-value heads, head_dim is the per-head dimension, ctx is the context length, and bytes is the size of each element (2 bytes for half precision).
Cache precision affects both VRAM usage and speed. Measured results for an 8B dense model on the same 8GB GPU:
| Cache Precision | Parallel Sessions | Context | Generation Speed |
|---|---|---|---|
| Low-bit quantized | 4 | 8K | 19.4 tok/s |
| 8-bit/4-bit mixed | 1 | 8K | 38.2 tok/s |
| Half precision | 1 | 8K | 51.7 tok/s |
| Half precision | 1 | 64K | 26.2 tok/s |
Because the table mixes several variables, the speed differences cannot be attributed to cache precision alone. Still, it demonstrates one fact: low-bit caching saves limited VRAM but can cost significant speed. When VRAM is sufficient, half-precision cache is usually the better choice.
A practical strategy follows: first compute the half-precision cache footprint with the formula—if it fits, use half precision. If not, step the precision down one level at a time and re-benchmark after each downgrade.
4. Use Binary Probing Instead of Rule-of-Thumb Formulas for the Context Limit
The community circulates VRAM estimation formulas, typically fitted for a specific precision. When the cache uses low-bit quantization, these formulas significantly overestimate VRAM requirements. In one case, an estimate suggested an 8B model could only handle a 4K context, while the actual loaded model ran at 64K.
A more reliable approach is to let the inference engine tell you directly what it can run. The binary probing idea: start from the smaller of the native context length and 65536; if loading or the first inference run hits out-of-memory, halve the context, up to 5 attempts.
def probe_max_ctx(try_load, native_ctx, cap=65536, max_probes=5):"""try_load(ctx) returns True if that context runs stably"""ctx = min(native_ctx, cap)for _ in range(max_probes):if try_load(ctx):return ctxctx //= 2 # Halve on failure and reloadreturn None
Two caveats when implementing this. First, fully release allocated VRAM after each failure, or residual allocations will interfere with later probes. Second, a successful probe only proves the model can load and complete one inference pass—under real workloads, still observe peak VRAM and leave headroom.
5. Match Parallel Session Count to Your Usage Scenario
Most inference servers default to multiple parallel sessions to support concurrent users. But as session count rises, VRAM is divided across sessions, each session’s available cache shrinks, and per-request throughput may drop.
On identical hardware and model, reducing parallel sessions from 4 to 1 raised generation speed from 18.5 tok/s to 38.2 tok/s—nearly double. If only one person uses the service, set it explicitly to 1. If you serve multiple users, trade off concurrency against per-request speed and determine the right value through load testing.
6. Micro-Batch Size Must Be Determined by Measurement
Micro-batch size (the number of tokens processed per chunk) affects prefill-stage efficiency. Its impact depends on model architecture and GPU model; there is no universal optimum. One set of measurements compared 128 versus 512:
- 8K context: 512 was about 7.6% faster than 128
- 64K context: 512 was about 21.6% faster than 128
This shows rules of thumb are unreliable. The safer approach is to benchmark both candidate values at your target context length and pick the faster one. Fix prompt length and generation length during the test, and average across multiple runs to reduce variance.
7. Don’t Compress Context with Synchronous Summaries from the Same Model
When a long conversation exceeds the context window, an intuitive fix is to have the current model summarize the history. In single-session scenarios this has an obvious problem: summary generation competes with the live conversation for the same session, requests queue up and block, and eventually time out.
Three more reasonable alternatives:
- Rule-based compression: keep the system instructions, the most recent turns, and key conclusions; drop small talk and repeated content in the middle.
- Sliding window: keep only the most recent window, store earlier content externally, and retrieve it by relevance when needed.
- Asynchronous summarization: give the summarization task its own service or background queue so it never blocks the main conversation.
Which option to choose depends on conversation length, how much information completeness you require, and the latency you can tolerate.
8. Recommended Tuning Workflow
Combining the above, tune in this order:
- Record hardware specs (VRAM capacity, system RAM) and model architecture (layer count, KV head count, expert count).
- Set the parallel session count to the minimum consistent with your usage scenario.
- For MoE models, first try placing only attention layers in VRAM; observe speed and VRAM usage.
- Estimate half-precision cache footprint with the formula to pick an initial cache precision.
- Use binary probing to determine the maximum usable context length.
- Benchmark the two candidate micro-batch sizes at your target context and choose the faster one.
- Under real load, observe peak VRAM, leave headroom, then lock in the configuration.
The essence of tuning is replacing guesses with measurements. Change one variable at a time, record the result, then decide the next step. The resulting configuration is both explainable and easy to reproduce when hardware or models change.
