Multi-Slot Local LLM Deployment: VRAM Planning and Tool Calling Practices
This article explores the practical aspects of deploying local large language models to handle concurrent requests. It covers VRAM budgeting across model weights, KV cache, and runtime overhead, along with quantization trade-offs, scheduling strategies for multi-slot and long-context scenarios, and methods for evaluating tool calling stability. Additionally, it discusses tiered model deployment and provides a deployment checklist to optimize resource allocation on limited hardware.
1. Background: Why Serve Concurrent Requests Locally
Deploying large language models (LLMs) on local hardware typically stems from three needs: keeping data in-house, maintaining controllable long-term inference costs, and adjusting inference parameters based on business requirements. A common setup for individual developers and small teams consists of two or more accelerator cards with about 32GB of VRAM each. This configuration can accommodate quantized models with 20 to 30 billion parameters, but the VRAM budget is quickly consumed by weights, cache, and runtime overhead.
Agent-based applications impose more specific requirements on inference services. Agents often inject over 10,000 tokens of system instructions and tool definitions at startup, with historical messages and tool results appended in subsequent turns. If the service only processes requests serially, different tasks will block each other. If multiple parallel slots are allowed, each slot requires an independent context space. Therefore, multi-slot and long context are two sides of the same coin: the more concurrent slots, the less context each slot can be allocated.
2. VRAM Planning: Calculating the Three Overheads
VRAM consumption can be divided into three parts:
- Model Weights: Directly related to parameter count and quantization bit-width.
- KV Cache: Grows linearly with context length, number of slots, and network layers; this is the most easily underestimated part in long-context scenarios.
- Compute Buffers and Runtime Overhead: Includes activation values, temporary tensors, and the runtime’s own memory management. A certain buffer must be reserved.
The calculation method for KV cache is: each token must save a Key and a Value in every layer. Therefore, the byte size per token is 2 × n_layers × n_kv_heads × head_dim × dtype_bytes. Multiply this by the context length per slot, and then by the number of slots, to get the total requirement.
def kv_cache_bytes(n_layers, n_kv_heads, head_dim, ctx_len, slots, dtype_bytes=2):"""Estimate total KV cache bytes (assuming KV cache is 16-bit float)."""per_token = 2 * n_layers * n_kv_heads * head_dim * dtype_bytesreturn per_token * ctx_len * slots# The following are hypothetical parameters for demonstration. Actual values should be read from the model's config file.total = kv_cache_bytes(n_layers=32, n_kv_heads=8, head_dim=128,ctx_len=65536, slots=3, dtype_bytes=2)print(f"KV cache is approximately {total / 1024**3:.2f} GiB") # Output is approx 24.00 GiB
The conclusion from this code is straightforward: the product of the number of slots and context length determines the cache scale. Models using Grouped-Query Attention (GQA) have fewer KV heads, resulting in significantly lower cache usage than full multi-head models of the same scale. Therefore, relying on empirical values instead of reading the actual configuration file is not advisable.
In practice, it is recommended to estimate using the formula first, then conduct a real test with a shorter context length to record the VRAM peak, and finally determine the maximum context length based on the remaining space.
3. Quantization Trade-offs: Treating Weights and Cache Separately
Weight quantization and KV cache quantization are independent matters. 8-bit weight quantization offers accuracy close to original 16-bit weights on most tasks while halving the footprint, making it a solid choice currently. 4-bit quantization can further compress VRAM usage, but errors are more easily amplified in tasks requiring strict format adherence, manifesting as occasional structural errors in the output.
When choosing a quantization scheme, you should not rely solely on a single perplexity metric. A more reliable approach is to build an evaluation set tailored to your business, comparing the pass rates of different quantization schemes on Q&A, code generation, structured output, and tool calling, and then making a decision combined with VRAM headroom.
4. Scheduling Strategies for Multi-Slot and Long Context
1. Trade-off between slots and context length. The total context capacity is approximately equal to the single-slot context length multiplied by the number of slots. If the business only has two or three long sessions concurrently, concentrating the remaining space on these sessions is usually more practical than distributing it evenly.
2. Prefix Reuse. System instructions and tool definitions remain unchanged across multiple interaction turns in a session. If the inference service supports prefix caching, recomputing this part for each turn can be avoided. For long instructions injected at startup, the benefit of this optimization is most significant.
3. Difference between Prefill and Token Generation. The prefill phase processes input tokens and can be computed in parallel, usually much faster than the token-by-token generation phase. Therefore, the initial processing time of long inputs is often acceptable; what truly affects user experience is generation speed. Specific values depend on hardware, batch size, and quantization method, requiring real-world testing in the target environment rather than applying others’ data.
4. Idle Slot Reclamation. Sessions without requests for a long time should release their cached space. Otherwise, VRAM will be held by idle sessions indefinitely, preventing new requests from being allocated space.
5. Evaluating Tool Calling Stability
Tool calling failures generally fall into three categories: output format mismatching the agreement, incorrect parameter names or types, and inability to correctly utilize results after a call returns. The causes and fixes for these three issues differ, so they should be tracked separately during evaluation rather than simply recording “success” or “failure”.
The following example demonstrates how to perform basic validation on a single output:
import jsondef check_tool_call(raw_output: str, schema: dict) -> dict:"""Check if the model output is a valid tool call and verify required parameters."""result = {"format_ok": False, "args_ok": False}try:call = json.loads(raw_output)except json.JSONDecodeError:return resultresult["format_ok"] = Trueargs = call.get("arguments", {})if isinstance(args, str): # Some outputs serialize arguments as a stringtry:args = json.loads(args)except json.JSONDecodeError:return resultrequired = schema.get("required", [])result["args_ok"] = all(key in args for key in required)return result
Evaluation should cover three scenarios: single-step calls, multi-step tasks requiring chained tools, and normal conversations where tools should not be called. The same set of test cases needs to be run repeatedly under different sampling temperatures and prompt templates to determine stability. Additionally, the absence of errors in one environment does not guarantee the model will be equally stable in others. Subtle changes in prompt templates, inference parameters, and tool descriptions can alter results, so evaluation outcomes should be recorded alongside the specific configuration used.
6. Tiered Deployment: Using Small Models for High-Frequency Lightweight Tasks
Tasks like heartbeat checks, status polling, and simple classification are called frequently but have low complexity per call. Assigning them to a smaller model can preserve the compute power of the large model for requests requiring deep reasoning.
ROUTES = {"heartbeat": {"model": "small", "max_tokens": 64, "timeout_s": 5},"planning": {"model": "large", "max_tokens": 2048, "timeout_s": 120},}
When implementing this, note three points:
- Route by task type. Routing rules should be based on task tags or input features, not ad-hoc judgments.
- Set VRAM limits separately. When large and small models share the same set of accelerator cards, each model must be configured with an independent VRAM limit to prevent one from exhausting the space and crashing the other.
- Structured validation and fallback mechanism. The output of the small model needs format validation. If validation fails, the request should automatically fall back to the large model or enter a manual processing queue.
7. Deployment Checklist
- Estimate weights, KV cache, and runtime overhead using the method in Section 2, and reserve a certain buffer. The buffer ratio must be determined based on test results.
- Conduct stress tests with stepped context lengths, recording the VRAM peak and generation speed at each tier.
- Build an evaluation set for tool calling and include it in version control. Re-run it after changing the model, quantization method, or inference parameters.
- Monitor the latency of the first token returned and the sustained generation speed. Changes in these two metrics often reflect configuration issues first.
- Set a timeout and reclamation policy for idle sessions, and confirm that new requests can be allocated slots normally after reclamation.
8. Conclusion
Running large models on limited accelerator cards relies on breaking down the VRAM budget and selecting the number of slots and context length based on business load. Quantization schemes, tool calling evaluation, and tiered small model deployment collectively determine service availability. Estimate first, test second, and schedule last—this is a reusable approach for most local deployment projects.
