Deploying a Long-Context MoE on Two Legacy 32GB GPUs: VRAM Budgeting, KV Cache Sizing and Tuning Guide
This article walks through a real deployment of a ~26B-parameter MoE model (about 4B activated per token) with 8-bit weights on two used 32GB GPUs, covering how to build a closed VRAM budget, estimate KV cache under mixed sliding-window/global attention with GQA, balance slot count against per-slot context (3 × 256K ≈ 786K tokens), profile prefill versus decode, exploit concurrent batching, add engineering guardrails for tool calling, and decouple the stack so models can be swapped cheaply. It includes the filled-in budget table, sizing formulas, observed performance numbers with the conditions behind them, and a pre-launch checklist.
1. Scope and Boundaries: Define What You Need and What You Have
Deploying a long-context LLM on limited VRAM is one of the most common engineering problems when self-hosting AI applications. This article follows one real setup from practice: the hardware was anything but luxurious — two used 32GB professional GPUs, roughly 64GB of VRAM in total. This was not a peak-number lab benchmark, but a production configuration built around an AI coding agent tool.
The configuration had three core goals:
- Provide long-context capacity for coding agents. Tools like this inject project rules, code snippets, and tool descriptions as system prompts at startup, typically in the low tens of thousands of tokens.
- Support multiple concurrent session slots, so several independent conversations and tasks can run in parallel.
- Preserve usable compute for always-on background tasks while keeping a safety margin.
The final setup runs a MoE model with roughly 26 billion total parameters, activating about 4 billion per token. It uses 8-bit weight quantization, is split into 3 slots, and carries a combined 786,432 tokens of context — 3 × 256 × 1024, or about 256K tokens of context per session on average.
In the reference deployment, prefill for a system prompt in the low tens of thousands of tokens ran at close to 1,000 token/s, and generation at roughly 50 token/s. These numbers are not a universal promise: they depend on hardware, model architecture, quantization format, inference backend, batch size, and warm-up strategy. Change the hardware or the backend and the results can shift substantially.
2. VRAM Budget: Feasibility Comes From Closing the Loop
Before deploying, complete a full VRAM budget. The rough formula is:
total VRAM ≈ weights + KV cache for all slots + activations and scratch buffers + framework/driver overhead + safety margin
2.1 Weights: 8-Bit Is the Balance Point Between Capacity and Precision
Common weight quantization options are 32-bit, 16-bit, 8-bit, and 4-bit. At 8 bits, each parameter takes about one byte, plus a small amount of metadata such as group scale factors. For many inference scenarios, 8-bit is the tier where precision loss is modest and capacity savings are substantial.
For a ~26B-parameter model, 8-bit weights are about 26GB, and close to 28GB with metadata — already most of a single 32GB card. You cannot expect one GPU to comfortably hold the model plus long context. More reliable options include:
- Split the model across both GPUs layer by layer to reduce per-GPU weight pressure;
- Pin the main model and an auxiliary model to different GPUs, allocating VRAM by role;
- If VRAM is not fully used, do not blindly chase higher precision — in long-context scenarios, KV cache growth usually matters more than the weight precision delta.
2.2 KV Cache: The Real Cost of Context Length
The KV cache is approximately:
KV bytes ≈ layers × KV heads × head dim × 2 (K and V) × bytes per element × tokens
Without sliding-window attention, GQA, and paged KV management, the KV cache for a single 256K-token slot could reach tens or even hundreds of gigabytes — clearly infeasible. Long-context models become practical usually because they rely on:
- A mix of sliding-window local attention and a small number of global attention layers;
- Grouped-query attention (GQA) to reduce the number of KV heads;
- Paged KV management to cut fragmentation and pre-allocation waste;
- Prefix sharing, so an identical system prompt is computed only once.
Using the parameters from this article, here is a closed budget example: assume 48 layers, 8 KV heads, head dimension 128, and both K and V stored in 16-bit. Of those, 42 layers are sliding-window local layers with a window of 1024 and the remaining 6 are global layers; one slot carries 256K tokens. That gives roughly 6.2GB of KV cache per slot, or about 18.6GB for 3 slots. With 8-bit KV quantization, this drops to about 9.3GB.
2.3 The Budget Filled In With These Parameters
| VRAM item | Reference estimate | Notes |
|---|---|---|
| Main model weights | ~28GB | 26B params, ~26GB at 8-bit, plus metadata |
| KV cache, single slot | ~6.2GB | 42 sliding layers (window 1024) + 6 global, GQA, FP16 KV |
| KV cache, 3 slots | ~18.6GB | 3 × 256K tokens; ~9.3GB with 8-bit KV |
| Activations and scratch buffers | ~3.5GB | Covers prefill peaks and temporary tensors |
| Framework and driver overhead | ~2.5GB | Compute libraries, communication buffers, runtime overhead |
| Safety margin | ~4.0GB | Guards against fragmentation and peak spikes |
| Total | ~56.6GB | Below 64GB across two GPUs, leaving ~7.4GB of headroom |
This table shows that 3 × 256K is not unconditional. It requires the sliding-to-global layer ratio, KV precision, activation buffers, and framework overhead all to stay within controlled bounds. Change any of these and the budget quickly falls out of balance.
3. Context and Slots: From Nominal Limits to Usable Capacity
786,432 tokens is a nominal ceiling; it does not mean every session can reliably use 256K. Planning has to answer four questions.
3.1 Trading Slot Count Against Per-Slot Limits
With a fixed total budget:
- Many short slots suit a large volume of short tasks, such as code completion or single-file Q&A;
- Few long slots suit a small number of long sessions, such as understanding a large codebase.
This deployment chose 3 slots to balance concurrency against per-task context length. If the budget falls short, cut in this order: reduce slot count first; then shorten the per-slot limit; then enable KV quantization or drop global layers; and only then consider changing hardware.
3.2 Long Context Is Not the Same as Effective Context
A model’s retrieval and reasoning quality degrades as context grows very long, and information buried in the middle is especially likely to be overlooked — the familiar “lost in the middle” effect. For agent tools, the system prompt, current task instructions, and most recent turns sit at the two ends of the context, so the impact is comparatively small.
A more practical way to organize context:
- Keep stable system instructions in a fixed prefix;
- Inject task material by relevance instead of dumping everything in;
- Keep tool definitions and recent turns close to the current instruction.
3.3 Prefill Cost Accumulates as Sessions Grow
In incremental multi-turn interactions, every turn may need to re-prefill the history. With a 100K-token context and prefill at 1,000 token/s, prefill alone takes about 100 seconds. Mitigations:
- Enable prefix caching so system prompts and completed history hit the cache;
- Bound the context and summarize or compress earlier content;
- Evict idle slots proactively, freeing KV cache for new sessions.
3.4 KV Quantization Can Expand Capacity, but Must Be Measured
Dropping the KV cache from 2 bytes to 1 byte per element theoretically halves KV usage. But low-bit KV quantization can introduce additional error, which warrants extra caution at long context. Before going live, run an evaluation on real tasks under both quantized and non-quantized configurations, confirm key metrics have not degraded materially, and only then enable it.
4. Performance Profiling: Prefill and Decode Differ by an Order of Magnitude
In the reference deployment, prefill ran close to 1,000 token/s and decode at about 50 token/s; the gap comes from different computational characteristics. To improve reproducibility, record the measured environment: GPU model, driver and CUDA version, inference backend version, weight quantization implementation, KV precision, batch size, input length, and warm-up strategy. The reference environment here can be summarized as: two used 32GB professional cards, roughly tens of TFLOPS of half-precision compute, about 1TB/s of VRAM bandwidth, an inference backend with support for older architectures, 8-bit weights, and a single-request batch size of 1.
4.1 Prefill: Compute-Bound
During prefill, input tokens are computed in parallel in one pass, so the primary bottleneck is compute. MoE’s sparse activation keeps the actual FLOPs below those of a dense model with the same total parameter count.
prefill FLOPs ≈ 2 × input tokens × activated parameters
For a single 15K-token prefill with 4B activated parameters, that is about 120 TFLOPs. With ~26 TFLOPS of half-precision compute per card, the theoretical time is about 4.5 seconds — measured, it was closer to 15 seconds. The gap comes mainly from additional memory traffic in MoE routing and expert dispatch, attention matrix overhead, and insufficient operator optimization on older architectures.
Optimization directions: pick an inference implementation with mature support for the target architecture; reduce the prefill chunk size to avoid VRAM spikes; raise the prefix cache hit rate; and make initialization asynchronous at the application layer so users are not left waiting.
4.2 Decode: Memory-Bandwidth-Bound
Decode generates one token per step, leaving much of the compute idle, so the bottleneck moves to VRAM bandwidth. For a MoE model, what matters is not total parameters but activated parameters. Each token generated requires the inference engine to read mostly the weights of the routed experts. At 4B activated parameters and 8-bit precision, that is about 4GB of weight reads.
With roughly 1TB/s of VRAM bandwidth per card, the theoretical ceiling is about 250 token/s; measured throughput was about 50 token/s, implying roughly 20% effective bandwidth utilization. The gap comes from non-contiguous access in MoE routing and expert lookup, kernel launch overhead, and the fact that some layers still involve large matrix operations.
4.3 Concurrent Batching Is the Real Advantage on Older Hardware
50 token/s for a single request is not impressive, but the value of MoE shows up under concurrency. When multiple requests form a batch, each decode step reads the weights once and produces one token for every request in the batch. With 3 concurrent slots, per-request speed may drop to 17–33 token/s, but aggregate throughput can rise to roughly 50–100 token/s. For batch-oriented workloads like coding agents, total throughput usually matters more than single-request speed.
5. Architecture Matters: Reading the Model Beats Blindly Buying Hardware
5.1 Total Versus Activated Parameters in MoE
MoE replaces the feed-forward layers with multiple expert sub-networks, and each token is computed by only a few experts selected by a router. Total parameters determine VRAM footprint; activated parameters determine compute and bandwidth pressure. With 26B total and 4B activated, VRAM must hold every expert, but only about 15% of the parameters are read at compute time. Expert routing and parallelism strategies affect actual bandwidth, so verify against your target inference backend.
5.2 Mixed Local Sliding-Window and Global Attention
Local layers keep their cache bounded, while global layers handle cross-passage retrieval and association. When evaluating this class of model, look at the number of global layers, the sliding-window size, and the GQA configuration, because they directly determine context cost.
5.3 Dense Models Suit Low-Latency-Sensitivity Background Work
A dense model uses all its parameters for every token, which gives stable latency and predictable behavior, but on older hardware its generation speed typically trails an MoE with the same activated parameter count. A reasonable split: run the dense model for background work such as heartbeats and periodic checks, and hand interactive long-context tasks to the MoE.
6. Coexisting Multiple Models: Moving Background Work Into the Time Dimension
Agent applications usually need a heartbeat mechanism — periodic checks, session keep-alive, task queue polling. These tasks fire infrequently with short inputs and outputs, but demand high availability.
The original setup loaded a roughly 20B-parameter dense model in the remaining VRAM alongside the main model to handle heartbeats. To be precise: what fits is a ~20B dense model with 8-bit quantization, limited context, and low concurrency. Deployed at 16-bit, weights alone need about 40GB, which a single card cannot hold — use time multiplexing or a separate GPU instead.
Points to watch with multiple coexisting models:
- Separate processes or separate ports, for fault isolation;
- Low concurrency and small context, so the main model’s KV space is not squeezed;
- Strict timeouts, with fallback to local rules on timeout, such as a fixed inspection script or a simple state machine;
- When resources are tight, load and unload models on demand, using memory-mapped weights and the page cache to shorten switchover time.
7. Tool-Calling Reliability: Don’t Rely on the Model Alone; Add Engineering Guardrails
Part of the reason this model was chosen was its relatively low tool-calling error rate in real environments. In observations on specific projects, however, some models produced comparatively many format errors. This is anecdotal and not a substitute for evaluation — validate with your own eval set.
Common tool-calling errors: malformed JSON structure, missing parameters or wrong types, non-existent tool names, hallucinated parameter values, and natural-language replies instead of structured calls.
Engineering needs several layers of fallback:
- Constrained decoding: where the backend supports it, use a JSON Schema or grammar constraint to force valid output structure;
- Schema validation: check parameter types and required fields;
- Tool name allowlist: reject unregistered tools;
- Feed errors back and retry: return the error message to the model to guide self-correction;
- Keep tool definitions near the recent context: avoid long conversations burying tool descriptions in history.
If the backend does not support constrained decoding, keep a degraded path: extract JSON from the text first, then run schema validation and feed-back retries. The eval set should cover high-frequency scenarios such as reading files, writing files, executing commands, and retrieving information, and should track tool-call success rate, parameter accuracy, and average retry count.
8. Rapid Model Iteration: Decouple to Withstand Model Turnover
When a new generation of models ships, the advantages of the previous one can disappear quickly. What determines long-term efficiency is not which model you picked, but whether the architecture lets you swap models cheaply.
Recommended three-layer decoupling:
- Model access layer abstraction — define a unified interface that hides backend differences;
- Configuration-driven management — keep model paths, quantization formats, context lengths, slot counts, and prompt templates all externalized;
- Replaceable inference layer — decouple the business logic from the inference framework, store weights centrally, containerize nodes, and wire in monitoring and logging.
Different models use different chat templates, tool-calling formats, and sensitivities to system prompts. When swapping models, manage prompt templates as separate configuration and validate them against the eval set, to avoid quality swings caused by “new model, old prompts.”
9. Pre-Launch Checklist
- VRAM budget: are weights, KV cache, activation buffers, and framework overhead each accounted for, with a margin of at least 10%?
- Quantization choices: have weight and KV precision been evaluated at the task level, not just against general benchmarks?
- Context planning: do slot count and per-slot limits match the business distribution, and are prefix caching and idle eviction enabled?
- Performance baseline: does load testing fix input length, concurrency, quantization format, backend version, and warm-up strategy, and does it record prefill, single-request generation, and aggregate throughput?
- Tool calling: are constrained decoding or degraded extraction, schema validation, allowlists, and feed-back retries all in place, with continuous regression against the eval set?
- Fault tolerance: are heartbeat tasks isolated from the main model and able to time out and degrade?
- Maintainability: are model, quantization, template, and slot configuration externalized, with canary and rollback support?
- Legacy hardware support: does the inference implementation support older architectures, and is the upgrade path explicit?
10. Conclusion: It Can Be Supported, but Only if the Budget Closes
Can two legacy 32GB GPUs support close to 780K tokens of context? Yes — but the prerequisite is not simply stacking more VRAM. You must simultaneously satisfy the sliding-to-global layer ratio, KV precision, activation buffer, and framework overhead budget, and confirm it with load testing. No two 32GB cards can carry 3 × 256K by default.
The method boils down to:
- Capacity: sparse activation plus 8-bit weights lets old hardware run a large-parameter model;
- Context: sliding windows, global attention, prefix caching, and idle eviction turn context into a manageable resource;
- Speed: prefill is compute-bound, decode is bandwidth-bound, and concurrency is a batching problem;
- Reliability: tool calling needs engineering guardrails, not a model with zero errors;
- Sustainability: models will keep changing; decoupling and an evaluation system are the real long-term advantage.
Hardware ages and models get updated. What endures is a reusable deployment methodology.
