Deploying a Local MoE Model on Two 32GB GPUs
A practical guide to running a local mixture-of-experts model with llama.cpp on two 32GB GPUs. Learn how to budget VRAM, choose quantization formats, configure parallel sessions and KV caches, benchmark inference, validate tool calls, and plan a secondary model without exhausting GPU memory.
1. Why MoE Models Work Well with Limited Compute
Mixture-of-experts (MoE) models divide their parameters among multiple experts, activating only a subset for each token. For example, a model with roughly 26 billion total parameters and about 4 billion active parameters per token can have a per-step compute cost close to that of a 3B–4B dense model, while retaining more knowledge capacity than a dense model with a comparable compute budget.
During decoding, each token accesses fewer weights. This can give MoE models a decoding advantage over dense models with similar total parameter counts, particularly on older GPUs with limited memory bandwidth.
However, MoE does not inherently reduce VRAM requirements. In the fully GPU-resident deployment described here, all expert weights must remain in VRAM, because the experts selected by the router depend on the input. You cannot budget memory as though only the active experts need to be loaded.
MoE reduces compute and weight-access bandwidth requirements, but weight memory must still be calculated from the total parameter count. That distinction drives the deployment plan.
2. Start with a VRAM Budget
Two 32GB GPUs provide 64GB of nominal combined VRAM. For a 26B model, Q8_0-quantized weights occupy approximately 27GB. Break the budget into the following components:
- Model weights: Approximately 27GB, split between the two GPUs.
- KV cache: Determined by context length, cache precision, and model architecture, as discussed in Section 6.
- Compute buffers and activations: Reserve approximately 3–5GB across both GPUs.
- Safety margin: Leave at least 10% of total VRAM unused to reduce the risk of out-of-memory errors caused by fragmentation or peak allocations.
Only the remaining space is available for the KV cache.
Drivers and the runtime also consume VRAM. Use the memory actually available after initialization rather than relying solely on the cards’ advertised capacity.
3. Choose a Quantization Format
Q8_0 is an 8-bit quantization format. Compared with FP16, it roughly halves weight storage, usually with a small quality loss. Small does not mean nonexistent, however: validate it against your own tasks.
If VRAM is tight, consider lower-bit formats such as Q6_K or Q5_K_M, accepting the possibility of additional quality degradation. Long-document question answering and structured output can be particularly sensitive to quantization, so regression tests should determine whether the trade-off is acceptable.
A practical process is to establish a Q8_0 baseline first, record the results, and then reduce precision incrementally. Run the same test suite at every step. Without a baseline, you cannot reliably judge whether a degradation is acceptable.
4. Select an Inference Backend and Pin the Version
llama.cpp supports multiple backends, including CUDA, ROCm/HIP, Vulkan, and SYCL. Whether a particular backend works with your accelerator depends on the GPU model, driver version, and the project’s current support.
Before compiling, check the official documentation to confirm that the target backend is available in the version you intend to use. Do not assume every backend supports every accelerator.
If you need to modify source code or build options, take a conservative approach:
- Pin a specific commit and record its hash.
- Make one change at a time, keeping an unmodified version available for rollback.
- After each change, run the same
llama-benchtests. Deploy the modification only after confirming that it provides a measurable benefit.
Avoid patches from unverified sources. They may alter numerical results or introduce errors that are difficult to diagnose.
5. Configure Parallel Slots and Long Contexts
A slot is an independent session that the server can process concurrently. In the default llama-server configuration described here, the total context specified by -c is divided among the slots.
For example, a total context of 786,432 tokens with three parallel slots gives each slot approximately 256K tokens.
The following command is a reference configuration, not a guarantee that this context size will fit in memory. Check the output of llama-server --help for your installed version, and calculate the KV cache budget before using it:
llama-server \-m /models/model-Q8_0.gguf \-ngl 99 \-ts 1,1 \-c 786432 \--parallel 3 \--host 127.0.0.1 --port 8080 \--jinja \--slots
The main options are:
-ngl 99: Requests GPU offloading for as many layers as possible.-ts 1,1: Requests an equal weight split across the two GPUs.--parallel 3: Configures three parallel slots.--jinja: Enables Jinja chat-template processing.--slots: Enables the slots monitoring endpoint.
After startup:
- Check the context sizes and KV cache allocation reported in the logs.
- Visit
http://127.0.0.1:8080/slotsto inspect slot status and context lengths. - Visit
http://127.0.0.1:8080/healthto confirm that the service is ready, then send a short test request.
6. Estimate KV Cache Memory
For a model with the attention structure assumed below, estimate KV cache storage as:
KV bytes per token =2 × number of layers × number of KV heads × head_dim × bytes per element
The factor of two accounts for both keys and values. FP16 uses two bytes per element. Q8 uses slightly more than one byte per element because quantization blocks include some metadata.
Total KV memory is approximately:
Total KV bytes = total context tokens × KV bytes per token
Consider a hypothetical model with:
- 48 layers
- 8 KV heads
- A head dimension of 128
With FP16, the cache requires approximately 192KiB per token. A 128K-token context therefore needs about 24GiB. With Q8 KV quantization, the estimate falls to roughly 12GiB, before allowing for quantization overhead.
At a total context of 768K tokens, the same hypothetical architecture would require approximately:
- 144GiB with FP16 KV
- 72GiB with Q8 KV
Neither fits in the VRAM remaining on two 32GB GPUs after loading the weights.
This is why parallel-session memory must be calculated from the total context allocation, not just the context available to one slot.
Read the actual layer count and KV head count from the model’s config.json. Grouped-query attention (GQA) models typically have fewer KV heads than attention heads, so their cache requirements can be much smaller than an estimate based on all attention heads. Do not reuse another model’s numbers without checking its architecture.
If the cache exceeds your budget, you can:
- Reduce the total context length.
- Reduce parallelism and lower the total context allocation accordingly.
- Use
q8_0for the KV cache. - Choose a model with fewer KV heads.
At a fixed total -c allocation, reducing the slot count alone should not be treated as a proportional reduction in KV memory.
Quantizing the V cache also requires flash attention. Check your version’s help output for the exact options.
7. Measure Performance Reproducibly
Figures such as approximately 1,000 tokens/s for prefill and 50 tokens/s for single-stream decoding are not useful deployment conclusions without the GPU model, quantization format, context length, concurrency, and software version. Treat measurements from your own environment as the basis for planning.
The llama-server timing data includes:
prompt_per_second: Prefill throughput.predicted_per_second: Decode throughput.
For throughput benchmarks, you can use llama-bench:
llama-bench -m /models/model-Q8_0.gguf -p 4096 -n 128 -ngl 99
Use a consistent testing process:
- Fix prompt lengths and test short, medium, and long inputs—for example, 4K, 64K, and 128K tokens.
- Test single-stream inference separately from concurrent workloads, such as two or three simultaneous requests.
- Record the llama.cpp commit, driver version, quantization format, and startup arguments.
- Repeat each test at least three times and report the median.
As concurrency increases, per-stream decode speed will often fall, while aggregate prefill throughput may improve because of larger batches. Longer contexts increase attention work, and performance can decline substantially beyond a certain length. Confirm these trends on your hardware rather than assuming a particular result.
For contexts beyond 256K tokens, consider KV cache quantization and evaluate sliding-window strategies where supported. A sliding window discards information outside the window, however. Tasks that require precise recall of earlier content, such as long-document question answering and codebase retrieval, may degrade significantly.
Validate those workloads before deployment. Throughput alone is not a sufficient acceptance criterion.
8. Troubleshoot Tool-Calling Reliability
In agent workloads, tool-call format compliance directly affects whether the system works correctly. Common failures include:
- Comments or trailing commas in JSON arguments.
- Calls to unregistered function names.
- Malformed output when multiple tools are called in parallel.
Investigate these issues in the following order.
1. Check the chat template
Confirm that the template matches the tool-calling format used during model training. Enable the model’s embedded template with --jinja, or specify a template with --chat-template-file when needed.
Check the tool-call markers in the template rather than assuming that any chat template will work.
2. Apply structural constraints
Use a GBNF grammar or JSON Schema to constrain output. Server interfaces also support JSON Schema in requests; consult the documentation for your version to confirm the relevant fields.
3. Tune sampling parameters
A temperature below 0.2 can reduce randomness in structured output. Very low temperatures may also encourage repetition, so observe the results on real tasks.
4. Enforce a tool allowlist
Accept only function names present in the tool registry. Treat unknown functions as errors and never execute them.
5. Parse and validate every response
Parse tool arguments as JSON and validate them against the schema. Count failed responses in the error rate rather than silently ignoring them.
6. Maintain regression tests
Build a test set around your actual tools. Include single-tool calls, multiple-tool calls, missing arguments, and boundary values. Record the pass rate for each model and after every configuration change.
The following minimal regression test checks whether the model calls the expected registered function and whether its arguments can be parsed. It is a basic smoke test, not a replacement for full schema validation:
import jsonimport requestsURL = "http://127.0.0.1:8080/v1/chat/completions"TOOLS = [{"type": "function", "function": {"name": "get_weather","parameters": {"type": "object","properties": {"city": {"type": "string"}},"required": ["city"],},}}]REGISTERED = {"get_weather"}CASES = [{"prompt": "Check the current weather in Shanghai.", "tool": "get_weather"},{"prompt": "Write a short poem about spring.", "tool": None},]def run(case):body = {"messages": [{"role": "user", "content": case["prompt"]}],"tools": TOOLS,"temperature": 0.1,}msg = requests.post(URL, json=body, timeout=120).json()["choices"][0]["message"]calls = msg.get("tool_calls") or []if case["tool"] is None:return not callsif not calls:return Falsefn = calls[0]["function"]if fn["name"] not in REGISTERED:return Falseargs = json.loads(fn["arguments"]) # Parsing errors are counted as failures.return fn["name"] == case["tool"] and "city" in argsif __name__ == "__main__":results = []for case in CASES:try:results.append(run(case))except Exception:results.append(False)print(f"Pass rate: {sum(results)}/{len(results)}")
A model with a lower tool-call error rate may perform better in production even if its general capabilities are slightly weaker. Choose based on your own regression results, not general-purpose benchmark scores alone.
9. Use Remaining VRAM for an Auxiliary Model
A rough primary-model budget on two GPUs with 64GB of nominal combined VRAM might look like this:
- Model weights: Approximately 27GB.
- Q8 KV cache for one 128K-token slot: Approximately 12GiB under the hypothetical architecture above.
- Compute buffers: Approximately 5GB.
That gives a rough total of about 45GB and a nominal remainder of about 19GB. These are planning estimates, not an exact allocation: GB and GiB differ, and runtime overhead and the safety margin still need to be accounted for.
An auxiliary model must fit within the usable remainder, not merely the nominal free space. For example, a quantized 20B-class model might have approximately 12GB of weights, with an additional estimated 3–4GB for its KV cache and buffers. Reserve another 1–2GB per inference process for runtime overhead.
These estimates can leave little headroom. Confirm actual consumption using startup logs and GPU memory monitoring before keeping both models resident.
Typical uses for a primary-plus-auxiliary setup include:
- Periodic status checks: Delegate lightweight recurring tasks to the smaller model.
- Summarization and preprocessing: Compress long conversations or rerank retrieval results.
- Fallback service: Let the smaller model take over when the primary model reaches its context limit or encounters an error.
Plan out-of-memory recovery in advance:
- If the primary model fails to start: Lower
-cprogressively, and reduce--parallelas needed to match the revised context allocation. - If memory runs out during operation: Have the gateway route new requests to the auxiliary model and trigger an alert.
- If the auxiliary model does not fit: Reduce
-nglso that some layers remain on the CPU. Performance will fall, but the service may remain available.
A shared API gateway can route requests by task type while hiding the two-model arrangement from upstream applications. This provides a relatively low-cost way to combine a primary local model with a smaller supporting model.
10. Key Takeaways
- MoE reduces compute and weight-access bandwidth demands, but weight memory still depends on total parameter count.
- Budget weights, KV cache, compute buffers, and a safety margin before deployment. Calculate cache requirements from the actual model architecture.
- Parallel slots share model weights, while the total context allocation is divided among them. Calculate KV memory across the full allocation.
- Pin inference-framework versions and preserve a rollback path. Validate changes using the same benchmarks.
- Reliable tool calling requires constraints, validation, and regression tests. General benchmark scores cannot replace application-specific testing.
- Performance figures need deployment details. Record the GPU model, quantization, context length, concurrency, and software version so results can be reproduced.
For teams with limited budgets that need reliable local agent infrastructure, two used professional GPUs can be a viable foundation. Success depends on calculating memory realistically, measuring performance on the intended workload, and treating tool-call reliability as a deployment requirement.
