Local LLM Inference Practices on Multi-GPU Accelerators

    This article explores practical strategies for deploying large language models locally using multi-GPU accelerators. It covers memory budget estimation, quantization strategies, multi-concurrency context allocation, prefill and decode throughput measurement, tool calling stability, and the division of labor between main and lightweight models, along with a comprehensive pre-deployment checklist.

    1. Background and Problem Definition

    There are three common motivations for deploying large language models locally. First, keeping data within the local network meets compliance requirements for internal code and business documents. Second, long-term API invocation costs are controllable, as high-frequency tasks do not require per-call payments. Third, service parameters such as context length, concurrency, and sampling strategies can be adjusted according to business needs.

    The memory of a single accelerator is often insufficient to simultaneously accommodate model weights, intermediate caches during inference, and multiple concurrent sessions. Therefore, many teams combine multiple GPUs, using tensor parallelism or pipeline parallelism to fit the model. The cost of this approach is increased inter-GPU communication overhead and greater tuning complexity.

    In such deployments, four metrics constrain each other: memory capacity determines how large a model and context can fit; memory bandwidth determines decoding speed; the number of concurrency slots determines the number of requests served simultaneously; and the single-request context length determines whether long document tasks can be completed. Adjusting any one affects the other three. The following sections proceed in the order of “budget first, then quantization, then context allocation, and finally measurement and validation.”

    2. Memory Budget Estimation

    Before deployment, estimate memory usage to avoid loading failures or out-of-memory errors during runtime. Memory consumption consists of two main parts.

    1. Model Weights

    Weight consumption can be estimated by multiplying the number of parameters by the bytes per parameter. In a Mixture of Experts (MoE) architecture, the total parameter count determines the weight volume, while the parameters actually involved in a single inference (activated parameters) determine the computational load. These two should not be confused: all weights must fit into memory, but decoding speed mainly depends on the read volume of the activated part.

    2. KV Cache

    Each concurrency slot must save the key-value vectors of historical tokens during generation. The size of the KV cache is proportional to the number of layers, KV heads, head dimension, context length, and concurrency. The estimation formula is as follows:

    1. def kv_cache_bytes(layers, kv_heads, head_dim, ctx_len, slots, dtype_bytes):
    2. # Coefficient 2 indicates saving both K and V
    3. return 2 * layers * kv_heads * head_dim * ctx_len * slots * dtype_bytes

    When storing the KV cache in 16-bit floating-point, dtype_bytes is 2; if the framework supports quantized KV cache, a smaller value can be used. Note that this formula is only a lower-bound estimate. In actual runtime, temporary compute buffers, alignment overhead, and the framework’s own memory usage must be added. It is recommended to reserve a 10% to 20% margin.

    After estimation, compare “weights + KV cache + margin” with the available memory of each GPU. If the total exceeds single-GPU capacity, weight partitioning is required, and the KV cache must be distributed across GPUs.

    3. Quantization Strategy

    Quantization is the primary method to reduce weight volume. 8-bit integer quantization typically compresses weights to about half the size of half-precision (FP16) while maintaining acceptable quality on most general tasks. 4-bit quantization further compresses memory but is more prone to degradation in mathematical reasoning, code generation, and strict format output.

    When choosing a quantization scheme, follow these steps:

    1. Determine the business’s key metrics, such as code pass rate, legal rate of structured output, or Q&A accuracy.
    2. Run the original precision and the quantized version on the same evaluation set and record metric differences.
    3. If the difference is within an acceptable range for the business, choose the scheme with the lowest memory footprint; otherwise, increase the quantization bit-width.

    For MoE models, quantization also needs to consider the stability of the routing layer. Selecting the wrong expert by the router directly affects output quality, so some frameworks retain higher precision for routing-related weights. Confirm how the inference backend handles this before deployment.

    4. Multi-Concurrency Context Allocation

    Inference services typically divide memory into several “slots,” each carrying an independent session. The total context budget equals the context length per slot multiplied by the number of slots, constrained by the memory limit.

    For example, if the total budget is about 780,000 tokens, several combinations are possible:

    • 3 slots, each about 260,000 tokens, suitable for a few long document tasks.
    • 6 slots, each about 130,000 tokens, balancing long documents and medium concurrency.
    • 12 slots, each about 65,000 tokens, suitable for high concurrency short requests.

    The actual choice should depend on request distribution. If long-context requests are rare but all slots are set to maximum length, a large amount of memory will sit idle, wasting concurrency capacity. A feasible approach is tiering by load: reserve a few large slots for long tasks, set multiple standard slots for regular Q&A, and route requests by length at the gateway layer.

    A sample configuration is as follows:

    1. server:
    2. parallel_slots: 3
    3. ctx_per_slot: 262144
    4. kv_cache_dtype: f16
    5. batch_threads: 8

    After configuration, stress test with a request stream close to the real distribution, observe queueing time, memory peaks, and the ratio of rejected requests, and then decide whether adjustments are needed.

    5. Prefill and Decode Throughput Measurement

    A generation request consists of two phases. The prefill phase processes the input prompt at once, involving high computational intensity and utilizing parallel computing well, so throughput is usually high. The decode phase generates output tokens one by one, requiring reading a large amount of weights and KV cache at each step, mainly limited by memory bandwidth, resulting in significantly lower throughput than prefill.

    This means that when describing performance in “tokens/s,” you must specify which phase is being measured. Filling a large context during system initialization measures near prefill performance; the output speed in a normal conversation reflects decode performance. Mixing the two leads to misjudgment of service capacity.

    Recommended measurement methods include:

    • Fix the input length and output length to avoid variations between requests interfering with results.
    • Separately record Time to First Token (TTFT, including prefill time) and steady-state decode speed.
    • Repeat each group of parameters multiple times, take the median, and exclude cold start data from the first load.
    • Record memory peaks simultaneously to determine if it is approaching the limit.

    Sample code is as follows:

    1. import time
    2. def measure(generate, prompt, max_new_tokens):
    3. t0 = time.perf_counter()
    4. first_t = None
    5. count = 0
    6. for _ in generate(prompt, max_new_tokens):
    7. if first_t is None:
    8. first_t = time.perf_counter()
    9. count += 1
    10. t1 = time.perf_counter()
    11. ttft = first_t - t0
    12. decode_tps = (count - 1) / (t1 - first_t)
    13. return ttft, decode_tps

    The obtained data should be compared with business goals. For interactive applications, TTFT is more important than peak throughput; for offline batch processing, total throughput and unit cost deserve more attention.

    6. Tool Calling Stability

    In agentic applications, the model needs to output tool names and parameters according to an agreed format. Common failure modes include missing parameters, invalid JSON structures, incorrect field types, answering directly when a call should be made, and repeated calls within the same step.

    These issues usually have multiple causes. Inconsistency between the chat template and the training format, high sampling temperature, and parsers not handling edge cases strictly can all amplify the error rate. Different models also vary in this capability, so it is necessary to evaluate on your own business data rather than relying solely on general leaderboards.

    Common methods to improve stability include:

    1. Grammar-constrained decoding: Restrict output to conform to a specified structure during generation, reducing illegal formats at the source.
    2. Schema validation: Perform field and type checks on parsed parameters, prompting the model to correct if validation fails.
    3. Limited retries and fallback: Set a maximum number of retries, transitioning to manual or default workflows if exceeded.
    4. Offline replay test set: Collect historical failure samples and replay them after changing models or parameters to observe error rate changes.

    Sample validation logic is as follows:

    1. import json
    2. def validate_call(raw, schema):
    3. try:
    4. call = json.loads(raw)
    5. except json.JSONDecodeError:
    6. return False, "Invalid JSON"
    7. for key in schema["required"]:
    8. if key not in call.get("arguments", {}):
    9. return False, f"Missing parameter {key}"
    10. return True, "Passed"

    When validation fails, feed the error message back to the model so it can correct in the next generation round, rather than discarding the result directly.

    7. Division of Labor between Main and Lightweight Models

    Not all tasks require the largest model. Low-complexity tasks such as heartbeat detection, status inspection, intent classification, and log summarization can be handled by smaller models, which occupy less memory and respond faster.

    A common practice is to keep a small model resident for high-frequency lightweight tasks while reserving the main model for complex reasoning and long-context tasks. This fully utilizes remaining memory and reduces scheduling pressure on the main model.

    When implementing, note the issue of resource contention. If two models share the same set of compute units, a long request from one will slow down the other. The following measures can be taken:

    • Bind independent devices or device subsets to each model.
    • Limit their respective thread counts and maximum concurrency.
    • Set independent timeouts and priorities for lightweight tasks to avoid being blocked by long tasks.

    8. Pre-Deployment Checklist

    Before going live, it is recommended to confirm the following items one by one:

    • Memory estimation includes weights, KV cache, and margin, and has passed real testing at maximum context.
    • The quantization scheme has been validated on the business evaluation set, with metric degradation within an acceptable range.
    • Context slot configuration matches the actual request length distribution.
    • The performance report distinguishes between the prefill and decode phases.
    • Tool calling has integrated schema validation, retry mechanisms, and replay testing.
    • Resource isolation between the lightweight model and the main model is complete and has passed concurrency stress testing.
    • Monitoring covers memory peaks, queueing time, error rate, and TTFT.

    After completing these checks, the local inference service has the foundation for stable operation. During subsequent iterations, change only one variable at a time and retain comparison data to facilitate judging the actual effect of the change.