Deploying a MoE LLM on Two 32GB GPUs: Context, Throughput, and Tool Calling

    This article shares a practical method for deploying a Mixture-of-Experts large language model with 26B total parameters and 4B active parameters in 8-bit quantization on two 32GB GPUs. It covers hardware and model selection, VRAM budgeting, KV cache estimation, long-context and concurrency configuration, prefill and decode behavior, prefix caching, tool-calling stability, co-hosting auxiliary heartbeat tasks, and building a portable architecture for rapid model iteration.

    Introduction

    As agentic applications become more common, large language model deployment is shifting from “calling a cloud API” to “locally controllable inference.” For individual developers and small teams, local deployment is attractive for three main reasons: data stays on premises, long-term costs are more predictable, and the inference path can be customized to specific requirements. However, local deployment also comes with hard constraints: limited VRAM, limited compute and bandwidth, and limited power and cooling. At the same time, requirements such as long context, multi-turn tool calling, and concurrent sessions keep increasing resource consumption.

    How can limited hardware provide enough context, fast token generation, sufficient concurrency, and stable tool calls? This is a typical systems-engineering problem. This article describes a practical deployment of a Mixture-of-Experts model with 26B total parameters and 4B active parameters, quantized to 8-bit on two 32GB VRAM accelerators. It covers:

    • Hardware and model selection
    • VRAM budgeting
    • Context and concurrency configuration
    • Inference performance characteristics
    • Tool-calling stability
    • Co-locating auxiliary tasks
    • Architecture portability

    1. Hardware and Model Selection: Why MoE Suits Limited VRAM

    The hardware used in this practice was two previous-generation accelerators with 32GB VRAM each, for a total of 64GB. This combination is not aimed at peak compute. Compared with newer hardware, it has generational gaps in compute, memory bandwidth, and inter-card interconnects. However, its advantages are relatively low VRAM cost per unit, generous VRAM capacity, and manageable acquisition and operation thresholds. For local inference services that are not extremely latency-sensitive, this kind of “older hardware” still offers strong cost-effectiveness.

    Choosing a sparse MoE model fits this hardware well because MoE decouples VRAM usage from compute:

    • VRAM usage depends on total parameters: no matter which experts are activated by a token, the weights of all experts must remain resident in VRAM because any of them may be called at any time.
    • Compute and memory access depend on active parameters: each token only reads the weights of the activated experts, so the compute and memory access per token are much lower than those of a dense model with the same total parameter count.

    A simple estimate helps explain this. Under 8-bit quantization, 26B parameters occupy roughly 26–27GB of weight space, about 13–14GB per GPU. But each token only needs to read the weights corresponding to about 4B active parameters. This means the bottleneck during decoding is not compute but memory bandwidth. For previous-generation hardware without large high-bandwidth caches or high-compute units, this structure of “more weights, less computation” can actually make better use of the hardware.

    Hardware selection should also consider the following points:

    1. Multi-GPU partitioning method: if high-speed interconnects are unavailable, layer-wise partitioning is preferable. Different layers are placed on different GPUs, and data is passed only between layers. By contrast, tensor parallelism introduces multiple inter-GPU communications within each layer and requires higher interconnect bandwidth. Without high-speed interconnects, it can easily become the bottleneck.
    2. Software ecosystem maturity: whether older hardware is fully supported by mainstream inference frameworks and quantization formats determines whether key features such as long context, KV cache quantization, and prefix caching can be used. If necessary, a community-maintained or custom-built runtime may be used, but the version must be pinned and a rollback plan recorded.
    3. Quantization format: 8-bit quantization, such as common Q8-style formats, offers a balanced tradeoff between precision loss and inference speed, making it a good primary deployment format. 4-bit quantization uses less VRAM but should be evaluated with tool calling, long-context, and other targeted tests to confirm that quality is acceptable.
    4. Power and cooling: older accelerators often have high full-load power consumption. Under sustained heavy load, cooling and throttling need attention because they can directly affect variability in decoding speed.

    2. VRAM Budget: Weights, KV Cache, and Concurrency

    VRAM planning is the foundation of the whole deployment. A single inference request mainly consumes three parts of VRAM:

    • Model weights: proportional to total parameters and quantization bit width; fixed after deployment.
    • KV cache: proportional to context length; independent for each session.
    • Compute buffer: used for intermediate activations, sampling, and batching overhead; generally reserved based on peak concurrency.

    The KV cache contains the Key and Value vectors generated by every token at every layer. Attention computation needs the K/V of all historical tokens, so they must remain in VRAM. The estimation formula is:

    1. KV VRAM ≈ context tokens × 2 × layers × KV heads × head_dim × bytes per element

    The factor 2 represents K and V. Bytes per element depends on KV quantization precision (1 byte for 8-bit). For example, with 2 KV heads per layer, head dimension 256, and 8-bit KV cache, each token needs about 26KB. A single 262144-token (256K) slot therefore requires about 6.5GiB. Three slots total about 768K context (262144 × 3 = 786432), corresponding to about 19.5GiB. The following function can estimate this quickly:

    1. def kv_cache_gib(tokens, layers, kv_heads, head_dim, bytes_per_elem=1):
    2. """Estimate KV cache VRAM usage in GiB; bytes_per_elem=1 indicates 8-bit quantization."""
    3. per_token = 2 * layers * kv_heads * head_dim * bytes_per_elem
    4. return per_token * tokens / 1024 ** 3
    5. # Illustrative values; actual values depend on the target model's layers, KV heads, and head dimension.
    6. slot = kv_cache_gib(262144, 26, 2, 256) # ≈ 6.5 GiB
    7. print(slot, slot * 3) # One slot ≈ 6.5; three slots ≈ 19.5

    A typical VRAM budget can be referenced as follows (indicative values):

    Component Estimation method Indicative usage
    Model weights (8-bit) 26B parameters × 1 byte ≈ 24.2 GiB
    KV cache (8-bit, 3 slots × 256K) about 26KB per token × 786432 ≈ 19.5 GiB
    Compute buffer and headroom Reserved based on peak concurrency Several GiB
    Co-located auxiliary small model See Section 5 About 10–12 GiB
    Available VRAM 2 × 32GB ≈ 59.6 GiB

    The budget is quite tight and needs careful allocation. When VRAM is insufficient, the following measures can be adopted in order of cost-effectiveness:

    • KV cache quantization: reducing KV from 16-bit to 8-bit saves about half of the KV VRAM. Going further to 4-bit saves another half, but the impact on long-context recall and instruction following should be evaluated.
    • Use grouped-query attention (GQA): fewer KV heads mean a smaller KV cache.
    • Adjust slots × slot length: for long-document processing, reduce the number of slots and increase context per slot. For high-concurrency short conversations, do the opposite.
    • Lower weight precision: switch to a lower-bit quantization format, but more rigorous evaluation is needed as a safeguard.
    • Offload temporarily idle slots: some inference frameworks support on-demand allocation and reclamation of KV cache.

    3. Long Context and Multi-Session Concurrency

    3.1 The Essence of Multi-Slot Concurrency

    Mainstream local inference frameworks usually provide a “parallel slots” mechanism: multiple sessions maintain their context and KV cache independently, and the framework dynamically batches them during decoding. Their relationship can be summarized as:

    1. Total context capacity = number of slots × maximum context per slot

    This setup uses “3 slots × 262144 tokens per slot,” for about 768K total context. This number can be misread as “the model can read 760,000 tokens at once.” A more accurate statement is: the system can serve at most 3 sessions simultaneously, and each session can accumulate up to about 260,000 tokens. The total is the sum of the three.

    In addition, total capacity is an upper limit, not a normal state. A newly started agent session usually has only tens of thousands of tokens. Only in scenarios such as long-document analysis and multi-turn tool calling will it gradually approach the limit. Therefore, when capacity is fixed, there is a tradeoff between the number of slots and the length of each slot:

    • To support longer single-session input: reduce the number of slots and increase context per slot.
    • To support more concurrent users: increase the number of slots and reduce context per slot.

    3.2 Prefill and Decode: Two Very Different Performance Profiles

    LLM inference is generally divided into two phases, with completely different performance bottlenecks:

    • Prefill: processes all input tokens in parallel; it is compute-intensive and mainly limited by compute.
    • Decode: generates output tokens one by one; every step must read all weights and all historical KV cache, making it memory-bandwidth-intensive and mainly limited by memory bandwidth.

    In this setup, initializing an intelligent coding tool requires prefilling a context of tens of thousands of tokens, usually including system prompts, tool definitions, and project background. Prefill speed is close to 1000 tokens/s, while decode speed is about 50 tokens/s. This means:

    • If initialization needs to prefill about 15K tokens, prefill alone takes about 15 seconds before the user sees the first token (TTFT, time to first token).
    • Generating a 1000-token response takes about 20 seconds.

    The optimization approaches are different. If prefill is slow, prioritize:

    • Enable prefix caching so repeated initialization content hits cache in subsequent requests.
    • Enable chunked prefill, splitting long input into smaller chunks and scheduling it together with decode tasks, preventing one long request from monopolizing inference resources and slowing down other sessions.
    • Check whether batching and long context are interfering with each other and preventing prefill from saturating compute.

    If decode is slow, consider:

    • Check whether the GPU model has mature weight-reordering optimizations that allow matrix multiplication to use cache efficiently.
    • Use quantization formats that are more friendly to memory bandwidth.
    • Control the context length of a single request, because a larger KV cache means more data to read at every decode step.

    The above speeds are measured in this environment and depend on hardware generation, quantization format, and framework version. They should be treated as order-of-magnitude references and not directly applied to other environments.

    3.3 Prefix Caching: A Key Lever for Agent Workloads

    Agentic applications have a notable characteristic: every request carries a highly repetitive prefix, such as system prompts, tool definitions, project background, and long conversation history. Without prefix caching, the prefill cost of this content is paid again in every turn. For contexts of tens of thousands of tokens, the cumulative cost is considerable.

    Mainstream inference frameworks generally support reusing KV cache by token prefix. When enabled, the KV cache for the same prefix can be reused directly, and subsequent requests only need to process new content. In an environment where tens of thousands of tokens can be prefilled at close to 1000 tokens/s, enabling prefix caching can typically reduce TTFT in subsequent turns from tens of seconds to one or two seconds or even lower. This is one of the highest-value optimizations for long-context local deployment.

    3.4 Context Length Is Not the Same as Effective Context Usage

    Supporting a long context and actually using that context well are two different issues. Common “long-context failures” include:

    • Insufficient position extrapolation: attention position encoding degrades significantly beyond the training length. Even if the inference framework extends context by adjusting position-encoding scaling factors, the result must be tested.
    • Middle information missed: relevant information located in the middle of a long context may be ignored.
    • Instructions diluted: system instructions and tool constraints placed later are more easily overwhelmed by large amounts of historical content, appearing as “forgetting what it is supposed to do” or degraded tool-call formatting.

    Before production, validate real capability with three types of tests:

    • Long-document retrieval: insert several key facts at random positions in a long document and test whether the model can locate them accurately.
    • Multi-turn consistency: repeatedly change constraints during a conversation and check whether the model follows the latest instruction.
    • Long-context tool calling: measure tool-call success rates in multi-turn scenarios that approach the context limit.

    In engineering, it is not necessary to “stuff everything into context.” Combining retrieval-augmented generation with long context is often more stable and more VRAM-efficient.

    4. Tool-Calling Reliability: More Important Than Model Size

    In scenarios such as intelligent coding and automated operation, a model needs to output structured tool-call requests. External programs parse and execute them, then feed execution results back to the model, repeating the cycle. The reliability of tool calling directly determines whether an agent succeeds. The most common failures in practice are:

    • Format errors: incomplete JSON, field names inconsistent with tool definitions, or missing required parameters.
    • Semantic errors: calling a nonexistent tool, or “forgetting” available tools after multiple turns.

    An observation from this practice is representative: in the same dual-GPU environment, a MoE model with 26B total parameters and 4B active parameters did not produce tool-calling errors, while another MoE model with 35B total parameters and 3B active parameters frequently reported errors. This shows at least two things:

    1. Total parameters do not equal tool-calling capability: the actual behavior of a MoE model depends more on active parameters, training data, and post-training strategies than on total parameter count.
    2. The problem may come from the combination of “long context + quantization + tool definitions”: longer context and lower quantization bit width can degrade format-following ability. Therefore, before switching to a different model, rule out environmental configuration factors first.

    To improve tool-calling reliability, consider the following layers:

    1. Structured output constraints: in inference frameworks that support constrained decoding, apply output-format constraints during the tool-calling stage to force legal JSON and required fields. This is more reliable than repeatedly emphasizing format in prompts.
    2. Prompts and tool descriptions: tool definitions should be clear and mutually exclusive. Parameter descriptions should explicitly state types and allowed ranges. If there are too many tools, group them and inject only relevant tools into the current context.
    3. Sampling parameters: tool calling requires higher determinism. Lower the temperature and narrow nucleus sampling ranges to reduce format errors caused by randomness.
    4. Runtime validation and fallback: validate the structure and parameters of model-generated call requests. If validation fails, return structured error information to the model and allow limited retries. If retries fail, fall back to prompting the user for manual operation.

    The following is an example of a call loop with validation and limited retries:

    1. import json
    2. def run_agent_turn(model, messages, tools, max_retry=2):
    3. """Execute one agent turn and return the final text or structured call result."""
    4. for attempt in range(max_retry + 1):
    5. # 1. Constrained decoding and lower temperature improve format stability.
    6. resp = model.chat(
    7. messages=messages,
    8. tools=tools,
    9. response_format="json_schema", # Illustrative: restrict tool-call output structure.
    10. temperature=0.2,
    11. )
    12. try:
    13. payload = json.loads(resp)
    14. name, args = payload["tool"], payload["arguments"]
    15. except (json.JSONDecodeError, KeyError, TypeError):
    16. # 2. Parse failure: return a structured error and allow limited retries.
    17. messages.append({"role": "user",
    18. "content": "The output is not valid tool-call JSON. Please output according to the tool definitions."})
    19. continue
    20. spec = tools.get(name)
    21. if spec is None:
    22. messages.append({"role": "user",
    23. "content": f"Tool {name} does not exist. Available tools: {list(tools)}"})
    24. continue
    25. # 3. Parameter validation: types, required fields, and allowed ranges.
    26. err = spec.validate(args)
    27. if err:
    28. messages.append({"role": "user",
    29. "content": f"Parameter error: {err}. Please correct it and call again."})
    30. continue
    31. # 4. Validation passed: execute the tool and feed the result back into context.
    32. result = spec.execute(args)
    33. messages.append({"role": "tool", "name": name, "content": result})
    34. return {"tool": name, "args": args, "result": result}
    35. # 5. Retries exhausted: hand off to upper-layer fallback handling.
    36. return {"error": "tool_call_failed_after_retries"}
    1. Evaluation baseline: build a call-sample set with real scenarios, covering single-tool calls, multi-tool calls, parameter boundaries, and multi-turn modifications. Continuously track call success rate, parameter accuracy, and format compliance. Every model or quantization-format change should be judged against this baseline rather than individual impressions.

    5. Co-Hosting a Small Model on the Same Machine for Heartbeat Tasks

    In always-on agent systems, “heartbeat” tasks are common, such as periodically checking task status, evaluating trigger conditions, and generating short progress summaries. These tasks typically have short inputs, short outputs, and frequent calls, but they are not sensitive to latency. If they share the same inference instance as the core model, two problems arise:

    • Heartbeat requests consume valuable session slots and compete with real business requests for VRAM and compute.
    • Heartbeat requests still require loading all weights of the core model, which is inefficient for such small tasks.

    In this practice, besides the core model, the remaining VRAM on the same machine hosted a dense model around 20B parameters specifically for heartbeat tasks. This reflects a useful resource-planning approach:

    1. VRAM partitioning: the core MoE model weights plus three slots of KV cache occupy about 43–44 GiB. After reserving several GiB for compute buffers, the remaining space can accommodate a 20B-scale model quantized to 4-bit, about 11GB. Its heartbeat requests have short context and small KV cache overhead.
    2. Instance isolation: the small model runs as an independent process with its own context and scheduling queue. Heartbeat tasks do not occupy core session slots, and long-context requests of the core model are not interrupted by frequent heartbeat calls.
    3. Limit context and output length: set a shorter context limit for the small model and limit generation length to prevent heartbeat tasks from unexpectedly consuming VRAM.
    4. Prioritize core inference: perform VRAM budget checks before startup. If the core model needs more slots or longer context, compress or pause the small model first to protect core inference.
    5. Task tiering: assign lightweight tasks such as heartbeats, status decisions, and simple rewrites to the small model; assign complex reasoning, long-context understanding, and multi-step tool calling to the core model.

    This “core model + auxiliary small model” pattern is common under limited hardware. If VRAM is extremely tight, heartbeat tasks can be degraded further: use scheduled tasks and rules whenever possible; if model participation is necessary, write heartbeat results to local files or message queues and consume them asynchronously from the main flow, avoiding blocking core inference.

    6. From Trying a Model to Building a Portable Architecture

    In later updates, the author of this practice mentioned that newer models quickly made a previously promising model less attractive. This detail reveals a reality of LLM applications: model iteration is much faster than hardware refresh cycles. Today’s best choice may be surpassed in a few months. If the whole system is deeply customized around one model, every upgrade may require rewriting a large amount of code.

    Therefore, local deployment architecture should treat model replaceability as a design premise:

    1. Unified interface layer: provide a standardized inference interface externally. Business code depends only on a unified request/response structure, while model names, quantization, and inference parameters are injected through configuration.
    2. Capability evaluation baseline: establish repeatable evaluation processes for tool calling, long context, and instruction following. A new model should replace the old one only after passing baseline tests.
    3. Configuration as code: manage quantization methods, slot counts, context lengths, sampling parameters, and other settings in version control so that any change is auditable and rollbackable.
    4. Progressive rollout: introduce a new model through a side-by-side path first, run it in parallel with the existing model, compare outputs, and switch main traffic only after stability is confirmed.

    When productizing local inference services, general cloud capabilities can also fill gaps:

    • Use object storage to distribute and manage model weight files.
    • Use container platforms to deploy inference services, making elastic scaling and version rollout easier.
    • Use logging services and monitoring alerts to continuously track TTFT, decode speed, and VRAM usage.

    For example, on cloud platforms that provide container, object storage, monitoring, and alerting services, a self-hosted inference service can be containerized and integrated with these capabilities. No matter how fast models evolve, what remains stable is engineering capability rather than any specific model.

    7. Deployment Checklist

    1. VRAM budget: are weights, KV cache, and compute buffers all included? Is there headroom for sudden concurrency spikes?
    2. Concurrency capacity: are target values for “number of slots × context per slot” defined and aligned with real business scenarios?
    3. Performance characteristics: are prefill and decode speeds measured separately? Are prefix caching and chunked prefill enabled?
    4. Tool calling: are structured output constraints enabled? Are validation, limited retries, and fallback plans in place?
    5. Auxiliary tasks: are lightweight tasks such as heartbeats isolated from core inference?
    6. Portability: are interfaces, evaluations, and configurations decoupled from a specific model, supporting gradual rollout and fast rollback?
    7. Observability: are TTFT, decode speed, VRAM usage, context utilization, and call failure rates monitored?

    Conclusion

    The core value of this approach is demonstrating how to run a “good-enough” local LLM service on hardware that is not cutting-edge: two 32GB VRAM accelerators, an 8-bit quantized MoE model with 26B total parameters and 4B active parameters, three slots totaling about 768K context, plus a co-hosted small model for heartbeat tasks. Prefill of nearly 1000 tokens/s and decode of about 50 tokens/s are enough for basic interaction needs of local agent applications.

    More valuable than the specific parameters is the methodology behind them:

    • Start with a VRAM budget and understand how weights and KV cache consume resources.
    • Treat prefill and decode separately and optimize each according to its bottleneck.
    • Use prefix caching to amortize the repeated cost of long context.
    • Use evaluation and fallback mechanisms to protect tool-calling reliability.
    • Use architectural decoupling to cope with rapid model iteration.

    As hardware improves and model capabilities continue to evolve, specific configurations will keep changing. But the engineering approach of “budget first, then partition responsibilities, and evaluate before deployment” will remain applicable to local LLM deployment.