Multi-GPU Long-Context LLM Inference in Practice: How to Budget VRAM and Concurrency

    A hands-on guide to serving a long-context Mixture-of-Experts model on two used 32GB datacenter GPUs. It covers reading total vs. activated parameters, calculating KV cache size, choosing weight and KV quantization, splitting across cards, scheduling concurrent slots, and co-locating an auxiliary model. It also walks through the prefill-vs-decode performance profile, tool-call reliability for agents, and a deployment checklist—with formulas and code to help you budget VRAM and concurrency before you launch.

    A developer took two used datacenter accelerator cards with 32GB of VRAM each and loaded a sparse-architecture model with 26 billion total parameters that activates only about 4 billion per token, quantized the weights to 8-bit, and got three concurrent slots running with roughly 786,000 tokens of combined context. At this scale, filling a system prompt plus chat history hit nearly 1,000 tokens/s, while token-by-token output ran at about 50 tokens/s. With VRAM still to spare, they co-located a ~20-billion-parameter auxiliary model to handle lightweight tasks such as “heartbeat” checks. From an engineering standpoint, this setup touches nearly every key decision point in long-context inference serving: how to quantize weights, how to compress the KV cache, how to split across two cards, how to schedule long-context slots, and how to let two models coexist. Let’s break each one down.

    1. Starting point: total parameters vs. activated parameters

    Sparse-architecture models (commonly called Mixture-of-Experts, or MoE) split parameters across many experts, and each token passes through only a few of them. In the case model, only about one-sixth of the total parameters take part in computation per token. This has two direct consequences:

    • VRAM is sized by total parameters. Every expert’s weights must stay resident, ready to be selected by any token. Even at 8-bit, 26 billion parameters need about 24.3GB of weights (26×10⁹×1B÷1024³), which won’t fit on a single card.
    • Compute is sized by activated parameters. Per-token compute is roughly equivalent to a 4-billion-parameter dense model, so even older-architecture accelerator cards can run it smoothly.

    Sparse models therefore suit hardware that is “large on VRAM, weak on compute.” Conversely, if you size your cards based only on activated parameters, you’ll likely fail at load time due to insufficient VRAM.

    2. The cost core of long context: calculating the KV cache

    During inference, each token produces a set of Key/Value vectors at every layer, which are cached so later tokens don’t have to recompute them. The KV cache size for a single sequence is:

    1. KV_bytes = 2 × L × H_kv × d_head × bytes × N_tokens
    • 2: one copy each for Key and Value.
    • L: number of layers.
    • H_kv: number of KV heads. With grouped-query attention (GQA), multiple query heads share one KV group, so H_kv is far smaller than the total attention heads.
    • d_head: dimension of each attention head.
    • bytes: bytes per element; 2 for FP16, roughly 1 for 8-bit quantization.
    • N_tokens: number of cached tokens.

    This formula explains three things:

    1. VRAM grows linearly with context. Ten times the context means ten times the KV cache.
    2. Each concurrent session holds its own copy. Three slots means three copies.
    3. GQA shrinks the KV cache by a multiple. If 32 query heads share 8 KV groups, the cache drops to a quarter.
    1. def kv_bytes_per_token(layers, kv_heads, head_dim, bytes_per_elem=2):
    2. return 2 * layers * kv_heads * head_dim * bytes_per_elem
    3. def budget_check(total_gib, weight_gib, per_tok_kib, max_ctx, slots, reserve=0.12):
    4. usable = total_gib * (1 - reserve) - weight_gib
    5. per_slot_gib = per_tok_kib * max_ctx / 1024 / 1024
    6. return {"usable_gib": round(usable, 2),
    7. "full_slot_gib": round(per_slot_gib, 2),
    8. "max_slots": int(usable // per_slot_gib)}
    9. # Sample numbers: ~24GB of weights on 32GB per card
    10. print(budget_check(32, 24.3, per_tok_kib=64, max_ctx=8192, slots=3))

    The method matters more than the result. Plug a real model’s layer count, KV head count, and head dimension into the formula, and you can decide before deployment how long a context and how many slots the VRAM can support, avoiding frequent cache eviction or even process crashes after launch.

    Two more things to note:

    • Mainstream open-source inference frameworks pre-allocate a KV cache pool, so the actually available context length is determined jointly by “weights + pool size.”
    • Fixed overhead such as the process itself, temporary buffers for the compute graph, and the CUDA context, plus VRAM fragmentation, also count. Reserving 10%–15% is usually the safe choice.

    3. KV cache quantization: buying long context at minimal cost

    8-bit weight quantization is relatively mature, with generally controllable error. The KV cache is more sensitive: its value distribution shifts across layers and token positions, individual Key channels may show extreme outliers, and naive symmetric quantization can amplify errors that accumulate over long sequences.

    Practical guidance:

    • Prioritize weight precision, then decide whether to quantize the KV cache.
    • If you do quantize KV, choose a method that computes scale factors per token or per group and handles outliers well.
    • After quantizing, always validate on long context—for example, needle-in-a-haystack retrieval, cross-chapter summarization, and multi-turn coreference resolution.

    The budget itself is layered: the longer the context, the more the sequence dimension dominates the KV cache and the greater the payoff from compressing it; with more slots and shorter per-slot context, layer count and head count matter more.

    4. Multi-GPU deployment: pooling VRAM is not pooling compute

    The 26 billion total parameters won’t fit on one card. Two common splitting approaches:

    Approach Inter-card communication Suitable scenario
    Tensor parallelism: split each layer’s weights across cards At least one collective communication per layer High-bandwidth interconnect, larger batches
    Pipeline layer split: first N layers on card A, the rest on card B Activations passed only at the split boundary Low concurrency, low-bandwidth interconnect
    • On old cards with only PCIe links, tensor parallelism’s communication overhead is especially pronounced.
    • Long-context serving usually has low concurrency, so layer splitting is often the better deal.

    Either way, remember that VRAM is “in series.” If any one card hits OOM, the whole service goes down. Better to leave ample headroom on each card than to push VRAM to the limit.

    5. Multi-slot scheduling: the core strategy for long-context serving

    Inference frameworks generally manage concurrency with “slots”: each slot holds one sequence’s KV cache, the number of slots is fixed at startup, and it determines how many requests the service can handle at once. Key points:

    • Pool by context length. Long-context requests (codebase analysis, long-document Q&A) and short requests differ in VRAM demand by tens of times. Mixing them in one pool means a single ultra-long session can take down all short requests.
    • Size slots by peak budget. Using the section 2 formula, estimate the KV pool ceiling as “slot count × max context per slot.”
    • Keep preemption controllable. Under VRAM pressure, the framework may swap out or drop some slots’ caches, which then need re-prefilling—extremely costly in long-context scenarios. Set reasonable swap-out thresholds and monitor preemption counts.
    • Align timeouts with SLOs. When input already reaches hundreds of thousands of tokens, a single conversation turn involves multiple prefills (system prompt, history, tool returns). Use end-to-end latency rather than single-pass throughput as the service metric.

    The case’s “3 slots, 786432 tokens combined” can be read this way: on average ~262,000 tokens per slot, corresponding to about 4 long sessions at a 64K cap, or dozens of shorter ones. Exact numbers vary with model structure and quantization, but the accounting approach is the same.

    6. Performance profile: fast prefill, slow generation—what it means

    Look at the difference between the two phases:

    • Prefill: compute-bound. Processing thousands of tokens at once means large matrix operations, high hardware utilization, and speeds up to nearly a thousand tokens/s.
    • Decode: memory-bound. Each step generates one token yet has to read all the weights for the activated parameters. By the case’s numbers, each token needs to read about 1.6GB of parameters from VRAM, plus KV cache reads. At VRAM bandwidths of hundreds of GB/s, tens of tokens/s is a reasonable result.

    Implications for agent-style applications:

    1. Long context doesn’t slow the first token. Tens of thousands of tokens of system prompt and tool definitions take only a few seconds to prefill.
    2. Generation takes patience. At ~50 tokens/s, a 1000-token reply takes about 20 seconds. Use streaming output to improve the experience and set reasonable timeouts for long tasks.
    3. Batching amortizes memory access. Multiple sequences in one batch share a single weight read, so raising the concurrency batch size usually improves total throughput noticeably. But KV cache reads grow with batch size, so the gains taper off.

    7. A hidden metric in agent scenarios: tool-call stability

    In agent applications, structured output matters more than textual fluency. A single malformed parameter can cause a tool call to fail and break the whole task chain. The case mentions that one sparse model showed no tool-call errors in the author’s environment, while a comparison model with a similar parameter count errored frequently. Such differences usually relate to the model’s instruction-following ability, how much structured-output training it has had, and its decoding configuration, and they must be measured in your own business scenario. A reference approach:

    1. {
    2. "name": "search_docs",
    3. "description": "Search the knowledge base for relevant snippets and return a list of results",
    4. "parameters": {
    5. "type": "object",
    6. "properties": {
    7. "query": {"type": "string", "description": "Search keywords, no more than 64 characters"},
    8. "top_k": {"type": "integer", "minimum": 1, "maximum": 10, "default": 5}
    9. },
    10. "required": ["query"],
    11. "additionalProperties": false
    12. }
    13. }
    • Tighten parameter constraints. Fewer parameters with clearer value ranges lower the chance of model error.
    • Choose a framework with grammar-constrained decoding. Constrain the JSON structure during generation rather than validating and patching afterward.
    • Build a regression test set. Collect real tool-call samples from conversations, replay them uniformly after each model change or quantization adjustment, and track call success rates.

    8. Resource governance: what VRAM headroom can and cannot do

    Fitting another ~20-billion-parameter model into the remaining VRAM to handle lightweight tasks like “heartbeat” checks (periodically probing whether the main model is alive and responsive) is a typical way to raise utilization on old hardware. Prerequisites:

    • Static accounting. Itemize “weights + KV cache + runtime overhead + safety margin” and confirm the auxiliary won’t be squeezed out at the main service’s peak.
    • The total is still constrained. Roughly, the main model’s weights are about 24.3GB and the auxiliary’s about 18.6GB (if also 8-bit), totaling about 42.9GB against the 64GB combined across both cards—leaving almost no room for KV cache and runtime overhead. Coexistence then relies on layer splitting, distributing different models’ layers across different cards. It’s feasible but leaves virtually no redundancy, so the auxiliary model’s context length must be strictly limited.
    • Fault isolation. Run the auxiliary service as a separate process on a separate port, with short timeouts and circuit breaking. On heartbeat failure, only log an alert—never let it affect the main path.
    • Match responsibilities. Tasks like heartbeat probing, session summarization, and title generation produce short output and tolerate errors, making them suitable for a small model; calls involving business decisions should still go to the main model.

    9. Launch checklist

    1. VRAM budget: Use the formula to account for weights, KV cache, and fixed overhead, reserving 10%–15%.
    2. Splitting scheme: Prefer layer splitting on low-bandwidth interconnects; consider tensor parallelism only with high-bandwidth interconnects.
    3. Slot planning: Pool by context length, and estimate by peak rather than average.
    4. Quantization validation: Evaluate weights and KV separately, focusing on long-context tasks.
    5. Tool-call regression: Use a fixed test set to verify structured-output success rates.
    6. Observability: Monitor throughput, latency, slot occupancy, VRAM level, and preemption counts.
    7. Resource isolation: Deploy the auxiliary model separately, with timeout, circuit-breaking, and degradation policies in place.

    10. Conclusion: beware the “new version, new model” selection anxiety

    The original author noted in a follow-up that after a new round of model releases, their setup quickly “changed identity.” This underscores the point: the parameters of any single deployment aren’t the end—what’s truly reusable is the method. Rather than chasing a specific model, turn VRAM accounting, splitting, scheduling, quantization validation, and tool-call regression into a reusable workflow. Then, no matter how models iterate, you can quickly judge how long a given hardware setup can hold out and whether the next model version is worth migrating to. Many major cloud platforms also offer elastic container and GPU resource management, making it easy to move this workflow to the cloud and scale elastically with business peaks.