Deploying Large Dense Models on a Single GPU: Memory Budgeting and Long-Context Testing

    A practical guide to deploying dense large language models on a single GPU. Learn how to budget VRAM for weights and KV cache, evaluate GQA vs MHA memory costs at 8K/32K/128K contexts, weigh quantization trade-offs, and run load tests to validate real-world limits.

    Key Takeaways First

    Whether single-GPU deployment is viable comes down to three things: whether the weights fit, how much VRAM remains for the KV cache after loading them, and whether peak usage exceeds the limit under long-context requests. Weights fitting in memory does not mean the service will run stably. Without measured data, every VRAM number is just an estimate and must be replaced with real runtime figures.

    Pre-Deployment Checklist

    Check How to calculate Pass condition
    Weight footprint Parameter count × bytes per parameter Weights plus headroom fit within available VRAM
    KV bytes per token 2 × layers × KV heads × head_dim × bytes per element Total KV for the target context length fits in remaining VRAM
    Runtime headroom Activation values, temporary buffers, and framework overhead measured under load Reserve based on measured peaks, not an arbitrary percentage
    Concurrency Available KV VRAM ÷ KV footprint per request Target concurrency stays within budget
    Quantization accuracy Compare against the baseline on your own task set Key metrics stay within business-acceptable degradation
    Load test results See Section 6 Peak memory, OOM count, and latency all meet targets

    1. Dense vs. MoE: Which to Choose

    A dense model uses all of its parameters in every forward pass. The inference path is fixed, implementation and debugging are straightforward, and per-step compute is roughly proportional to parameter count.

    A Mixture-of-Experts (MoE) model splits parameters into multiple experts, activating only a subset per token. Its compute cost is lower, but all expert weights still need to reside in VRAM or fast-access memory. So “fewer active parameters” does not mean “less VRAM usage.”

    Dimension Dense model MoE model
    Per-step compute Proportional to parameter count Proportional to active parameter count
    VRAM usage All parameters resident All experts resident, usually larger
    Implementation complexity Low Requires routing, load balancing, and expert parallelism
    Single-GPU deployment Easy to estimate Hard to run on one GPU when total parameters exceed VRAM

    For single-GPU deployment, a dense model has a clearer memory accounting and should be evaluated first.

    2. Memory Budget: Start with Weights

    Weight VRAM ≈ parameter count × bytes per parameter. For a 30-billion-parameter model, using decimal GB:

    Precision Bytes per parameter Weight footprint (approx.)
    FP32 4 120 GB
    BF16/FP16 2 60 GB
    FP8/INT8 1 30 GB
    INT4 0.5 15 GB

    The code below computes weight footprint and estimates how much VRAM remains for the KV cache after subtracting weights and reserve:

    1. GB = 1e9 # Decimal GB, 1 GB = 10^9 bytes
    2. BYTES_PER_ELEMENT = {
    3. "fp32": 4,
    4. "bf16": 2,
    5. "fp16": 2,
    6. "fp8": 1,
    7. "int8": 1,
    8. "int4": 0.5,
    9. }
    10. def weight_memory_gb(num_params_billion: float, dtype: str) -> float:
    11. """Weight VRAM (GB) = parameters (billions) × 10^9 × bytes per param ÷ 10^9"""
    12. bytes_per_param = BYTES_PER_ELEMENT[dtype]
    13. return num_params_billion * 1e9 * bytes_per_param / GB
    14. def kv_budget_gb(gpu_gb: float, weight_gb: float,
    15. utilization: float = 0.9, reserve_gb: float = 0.0) -> float:
    16. """VRAM available for the KV cache (GB).
    17. utilization: fraction of VRAM the framework is allowed to use.
    18. reserve_gb: activations, temporary buffers, and runtime overhead — should be measured via load testing.
    19. """
    20. usable = gpu_gb * utilization
    21. return usable - weight_gb - reserve_gb
    22. if __name__ == "__main__":
    23. w_bf16 = weight_memory_gb(30, "bf16")
    24. w_fp8 = weight_memory_gb(30, "fp8")
    25. print(f"BF16 weights: {w_bf16:.1f} GB")
    26. print(f"FP8 weights: {w_fp8:.1f} GB")
    27. print(f"KV budget at BF16 (4GB trial reserve): {kv_budget_gb(80, w_bf16, 0.9, 4):.1f} GB")

    Runtime requirements: Python 3.9 or later, no third-party dependencies.

    Two caveats. First, the “80 GB” a GPU vendor advertises usually means GiB, roughly 85.9 decimal GB. nvidia-smi typically reports in MiB. Keep units consistent in your calculations, or you will be off by several GB. Second, the CUDA context, framework memory pools, and fragmentation all consume VRAM, and none of that is captured by the weight formula.

    3. KV Cache: The Dominant Cost of Long Contexts

    KV cache grows linearly with context length and concurrency, and in long-context scenarios it often becomes harder to control than the weights themselves.

    Per-request KV cache size:

    KV bytes = 2 × layers × KV heads × head_dim × sequence length × batch × bytes per element

    The leading 2 accounts for the K and V tensors. KV head count is one of the biggest drivers of memory usage. With GQA (Grouped-Query Attention), KV heads are far fewer than attention heads, dramatically reducing memory. MQA is the extreme case, with only a single KV head group.

    1. def kv_cache_gb(layers: int, kv_heads: int, head_dim: int,
    2. seq_len: int, batch: int = 1, dtype: str = "bf16") -> float:
    3. """KV cache footprint for one batch (GB)."""
    4. per_token_bytes = 2 * layers * kv_heads * head_dim * batch * BYTES_PER_ELEMENT[dtype]
    5. return seq_len * per_token_bytes / GB
    6. def max_tokens_in_budget(budget_gb: float, layers: int, kv_heads: int,
    7. head_dim: int, dtype: str = "bf16") -> int:
    8. """Given a KV budget, total tokens that fit (summed across all concurrent requests)."""
    9. per_token_bytes = 2 * layers * kv_heads * head_dim * BYTES_PER_ELEMENT[dtype]
    10. return int(budget_gb * GB // per_token_bytes)

    4. Worked Examples: 8K, 32K, 128K

    The following examples use a hypothetical configuration: 60 layers, head_dim of 128, 8 KV heads (GQA), and BF16 KV cache. These numbers only illustrate the calculation. For real deployments, read the actual parameters from the model’s config.json.

    KV footprint per request:

    Context length GQA (8 KV heads) MHA (64 KV heads, comparison)
    8K (8192) ~2.01 GB ~16.1 GB
    32K (32768) ~8.05 GB ~64.4 GB
    128K (131072) ~32.2 GB ~257.7 GB

    The same model can differ by a factor of 8 in memory purely due to KV head count. This is why you should confirm whether a model uses GQA before committing to it.

    Now the budget. Assume the framework’s gpu_memory_utilization is set to 0.9, so an 80 GB card has about 72 GB usable.

    Option A: BF16 weights. Weights take 60 GB, leaving 12 GB. With 4 GB reserved for activations and runtime overhead, 8 GB remains for KV — roughly 32,552 tokens. A single 32K request barely exceeds the cap, making it effectively unusable.

    Option B: FP8 weights. Weights take 30 GB, leaving 42 GB. After a 4 GB reserve, 38 GB remains for KV — roughly 154,622 tokens. A 128K request needs 32.2 GB, which theoretically fits, with about 5.8 GB to spare.

    Option B looks feasible, but with one critical caveat: during a 128K prefill, activations may far exceed 4 GB. The reserve must be determined by load testing. If measured activation peaks are higher, a single 128K request will trigger OOM. In that case, lower the context limit, switch to INT8 KV cache (if the framework supports it), or move to a larger-VRAM GPU.

    5. Quantization: Benefits and Risks

    Quantization can substantially shrink the VRAM footprint of both weights and KV cache. Moving from BF16 to FP8 halves the weights. That is an important selection factor, but not the only one.

    The risks of quantization include:

    1. Accuracy degradation. FP8 and INT4 are more sensitive to numerical error, especially in math reasoning, code generation, and structured output. Compare against a BF16 baseline on your own task set — public leaderboards alone are not enough.
    2. Long-context degradation. Quantization error can accumulate over long sequences. Tasks like 128K retrieval and cross-segment referencing need dedicated regression tests.
    3. Not necessarily faster. Low-bit compute requires matching kernel support, and dequantization overhead can offset bandwidth savings. Judge by actual latency and throughput, not bit width alone.
    4. Unstable output formats. Structured output such as JSON and tables may suffer missing fields or formatting errors after quantization; track pass rates.

    6. Load Testing Procedure and Acceptance Criteria

    Run load tests in five steps.

    Step 1: Record the baseline. After loading the model, record idle VRAM. Warm up, then record again — the difference reflects the framework’s memory pools and caches.

    Step 2: Probe peaks by length. Test single requests at 8K, 32K, and 128K in turn, recording the peak. The function below works as a probing tool. generate_fn is provided by your inference service and takes prompt length and generation length as arguments.

    ```python
    import torch

    def probe_peak_memory(generate_fn, prompt_len: int, max_new_tokens: int = 256) -> dict:
    “””Probe peak VRAM for a single generation request.
    Note: torch reports PyTorch allocator statistics only, excluding non-PyTorch
    memory such as the CUDA context. In production, also monitor whole-GPU
    usage with nvidia-smi.
    “””
    torch.cuda.synchronize()
    torch.cuda.reset_peak_memory_stats()
    generate_f