31B Dense LLM Selection and Deployment Guide: Memory Estimation, Quantization, and Serving Best Practices

    This guide explains how 31B-class dense large language models differ from sparse Mixture-of-Experts (MoE) models, how to estimate their GPU memory footprint, and how to move them from a pilot to stable production. It covers VRAM estimation for FP16/BF16, INT8, and 4-bit weights, the KV Cache formula and how GQA, MQA, or KV Cache quantization reduce it, a side-by-side comparison of dense and sparse architectures, a step-by-step quantization workflow with calibration, acceptance criteria, and rollback thresholds, a 4-bit inference example, inference service encapsulation, observability metrics, common deployment mistakes, and quantified target metrics for typical scenarios such as RAG question answering, long-document summarization, code completion, and structured extraction. Use it to size hardware, choose a precision level, and set realistic latency and memory targets for a 31B dense model.

    1. What Is a 31B Dense LLM?

    Large language models are often divided by how their parameters are organized and how compute flows through them: dense models and sparse models (Mixture-of-Experts, or MoE). The defining trait of a dense model is that every input token passes through all of the model’s parameters — the full set of weight matrices participates in the forward pass. A sparse MoE model instead spreads parameters across multiple expert subnetworks and routes each token to only a few experts, so the number of activated parameters per token is typically smaller than the total parameter count.

    That difference has direct consequences for deployment. A dense model has a fixed compute path, which makes FLOPs, memory usage, and latency easier to model in advance — but it does not mean you can simplify the analysis and ignore runtime conditions. Latency and throughput are still affected by input and output sequence length, batch size, KV Cache, inference framework overhead, GPU memory bandwidth, PCIe/NVLink bandwidth, and concurrency scheduling strategy. When evaluating a 31B-class dense model, then, do not stop at the “31B” total parameter count. Measure it against your actual request lengths, concurrency peaks, context window, and precision plan.

    2. How to Estimate VRAM for a 31B Model

    A 30-billion-parameter-class dense model is often treated as a middle ground between capability and cost. It handles complex reasoning, long-document understanding, and multi-turn conversation better than models with hundreds of millions of parameters, and it is easier to deploy on-premises on limited hardware than models in the hundreds of billions.

    The figures below are theoretical estimates; actual numbers vary with model architecture, attention implementation, context length, and inference framework:

    Precision / scheme Weight memory estimate Common deployment guidance
    FP16/BF16 ~62GB Typically an 80GB single GPU, dual GPUs, or higher total VRAM
    INT8 ~31GB Consider a single 40GB, 48GB, or larger GPU
    INT4 / 4-bit ~15.5GB–18GB Consider a single 24GB or 48GB GPU, but reserve headroom for long context and batching

    Weights are only part of the picture. A realistic deployment should account for at least four categories of memory consumption:

    1. Model weights — directly tied to parameter count and precision.
    2. KV Cache — tied to sequence length, batch size, number of layers, number of KV heads, attention implementation, and precision.
    3. Activations and temporary buffers — tied to the inference framework, operator implementations, and parallelism strategy.
    4. Runtime overhead — framework scheduling, memory fragmentation, communication buffers, and similar.

    A simplified estimation formula:

    Total memory ≈ weights + KV Cache + activations and temporary buffers + runtime overhead

    KV Cache can be estimated further:

    KV Cache ≈ 2 × num_layers × num_kv_heads × head_dim × sequence_length × batch_size × bytes_per_value

    If a model uses standard multi-head attention, the number of KV heads is close to the hidden dimension. If it uses GQA, MQA, or KV Cache quantization, KV Cache shrinks substantially. As an example, for a 31B model with a hidden size of roughly 6656 and about 60 layers, a single request with around 1K of context in FP16 may need close to 1.5GB of KV Cache; at 8K of context, a single request can reach the 10GB range. KV Cache grows as concurrent requests increase. For long-context, high-concurrency, and low-latency scenarios, run a dedicated VRAM stress test rather than relying on the weight estimate alone.

    3. Dense or Sparse: How to Choose

    In selection work, do not assume a dense model is inherently better than an MoE model, and do not assume MoE is inherently cheaper. Their strengths apply under different conditions.

    Dimension Dense Sparse (MoE)
    Activated parameters All parameters activated per token Only a subset of experts per token
    Compute path Fixed and predictable Affected by routing policy
    VRAM characteristics All weights resident Total weights usually still resident or loaded in tiers
    Latency stability Generally more stable Routing long tails and expert hotspots possible
    Deployment complexity Lower Higher — needs routing, scheduling, and load balancing
    On-premises barrier Relatively friendly Higher engineering requirements

    Work through the following questions:

    1. Are there strict P95/P99 latency requirements?
      If so — particularly for online Q&A, code completion, or real-time customer support — evaluate dense models first.

    2. Do you want to reduce deployment and operations complexity?
      If the team is small and needs to ship quickly, a dense model is easier to turn into a stable service.

    3. Are you chasing maximum cost efficiency and do you have strong engineering capability?
      If the platform can handle expert routing and scheduling, dynamic batching, fault isolation, and capacity stress testing, it is worth evaluating MoE as well.

    4. Do you need single-machine or few-machine on-premises deployment?
      After quantization and memory optimization, a 31B dense model is easier to bring into a closed loop on limited GPU resources.

    One misconception deserves special attention: a dense model does not automatically have “higher knowledge density per parameter.” At the same number of activated parameters, an MoE model usually has a larger total parameter count, and its knowledge capacity, storage cost, VRAM usage, and inference cost need to be evaluated separately. The dense model’s advantages lie mainly in a deterministic compute path, engineering controllability, and stable latency; the MoE model’s advantages lie in controllable activated parameters and potentially more room to optimize throughput cost — at the price of higher routing and operations complexity.

    4. Deploying a 31B Model: Quantization, Serving, and Observability

    4.1 How to approach quantization

    Quantization is a common way to reduce VRAM usage and improve throughput. Follow a “baseline first, then quantize; evaluate first, then go live” sequence.

    Recommended steps:

    1. Establish a precision baseline
      Load the model in FP16 or BF16 first and record typical task metrics: answer accuracy, summary quality, code completion pass rate, structured-output validity rate, and so on.

    2. Choose a quantization level
      Try INT8 first, then evaluate INT4/4-bit against your VRAM budget. INT8 is usually easier to balance precision and performance; INT4 suits scenarios where VRAM is tight and some quality fluctuation is acceptable.

    3. Prepare a calibration set
      The calibration set should reflect the real distribution of business inputs, not only generic public corpora. For a small pilot, 256 to 512 samples is enough; for production, expand to 512 to 1024 samples and cover Q&A, long text, code, extraction, summarization, and multi-turn conversation.

    4. Define acceptance criteria
      Evaluate both quality and performance. Quality metrics include task accuracy, manual spot-check pass rate, JSON validity rate, and factual consistency; performance metrics include time to first token, average generation speed, P95/P99 latency, throughput, peak VRAM, and error rate.

    5. Set rollback thresholds
      Example thresholds: a drop of no more than 2% to 5% on core task metrics relative to the FP16 baseline; P95 latency within 120% of the business budget; peak VRAM within 90% of the single-GPU safe threshold; OOM or severe error rate close to zero. Once a threshold is breached, roll back to a higher precision or adjust batch size, context length, and concurrency policy.

    6. Handle failures
      Common issues include quantization dependency mismatches, unsupported operators, insufficient VRAM, repetitive output, broken formatting, and abnormal truncation at long context. Before deployment, keep a fallback FP16/BF16 version and prepare plans for configuration rollback, model rollback, and traffic degradation.

    4.2 A 4-bit inference example and runtime dependencies

    The example below only illustrates the basic idea of running 4-bit quantized inference for a 31B-class dense model; it is not an optimal production configuration.

    Before running it, prepare the following:

    1. A Python environment — Python 3.9 or newer is recommended.
    2. Dependencies such as transformers, accelerate, and bitsandbytes, with attention to version compatibility.
    3. Confirmation that the CUDA driver, PyTorch, and GPU support in bitsandbytes are all working.
    4. A VRAM budget estimate: 4-bit weights themselves may be around 16GB, but long context, batching, KV Cache, and framework overhead still need additional headroom.
    5. Replace your-dense-31b-model-path with the actual model path.
    1. # Conceptual example: load a 31B-class dense model with 4-bit quantized inference
    2. from transformers import AutoModelForCausalLM, AutoTokenizer
    3. model_id = "your-dense-31b-model-path"
    4. tokenizer = AutoTokenizer.from_pretrained(model_id)
    5. model = AutoModelForCausalLM.from_pretrained(
    6. model_id,
    7. device_map="auto",
    8. load_in_4bit=True, # 4-bit quantization to reduce VRAM usage
    9. bnb_4bit_compute_dtype="bfloat16", # compute precision
    10. )
    11. prompt = "Briefly explain what a dense large language model is."
    12. inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
    13. outputs = model.generate(**inputs, max_new_tokens=256)
    14. print(tokenizer.decode(outputs[0], skip_special_tokens=True))

    4.3 Wrapping inference into a service

    Being able to load a model is only the first step; a stable service needs engineering work around it. Wrap the model as a service compatible with mainstream API styles, with support for streaming output, timeouts, retries, and dynamic batching. Under high concurrency, continuous batching improves GPU utilization, but queueing latency and long-tail requests need attention at the same time.

    At the serving stage, focus on:

    1. Request validation — cap input length, output length, concurrency, and timeout.
    2. Dynamic batching — set maximum batch size and wait window based on latency targets.
    3. Rate limiting and degradation — protect critical paths during traffic peaks and avoid exhausting VRAM.
    4. Version management — version model weights, quantization configurations, prompt templates, and service images.
    5. Resource scheduling — use a container orchestration platform for elastic scaling, manage weights in object storage, and distribute requests through a load balancer.

    4.4 Observability

    After launch, build a monitoring system that covers at least:

    1. Latency metrics — time to first token, time per generated token, P95/P99 latency.
    2. Throughput metrics — QPS, concurrency, batch size, tokens generated per second.
    3. Resource metrics — GPU utilization, VRAM usage, KV Cache usage, CPU memory, disk I/O.
    4. Quality metrics — error rate, truncation rate, empty-response rate, formatting error rate, abnormal user-feedback rate.
    5. Request-path metrics — queue time, model load time, number of service restarts.

    Combine logs, metrics, and tracing so that when latency spikes, VRAM approaches its ceiling, or output quality drops, you can quickly determine whether the cause is the model, the quantization configuration, batching, the network, or a shift in the business input distribution.

    5. Common Mistakes

    The following mistakes show up often when deploying 31B dense models:

    1. Quantizing without calibration
      Quantizing directly can degrade accuracy on specialized tasks, weaken long-text understanding, or produce abnormal output formats.

    2. Measuring only time to first token
      Total time for a generative task also includes per-token decoding time; measuring only the first token misjudges the real user experience.

    3. Ignoring long-context VRAM
      As context grows from 2K to 8K, 16K, or 32K, KV Cache increases sharply and can trigger OOM directly.

    4. Ignoring batching and queueing latency
      Single-request load tests cannot reflect real P95/P99 under high concurrency.

    5. Dependency version mismatch
      Incompatible versions among transformers, accelerate, bitsandbytes, and the CUDA driver can cause quantization loading failures or abnormal performance.

    6. No rollback plan
      After changing the quantized version, the model version, or service configuration, keep a baseline that can be rolled back quickly.

    7. Looking only at total parameter count
      Dense versus MoE, quantization, context length, and concurrency scale all affect real cost; parameter count alone cannot tell you how hard a deployment will be.

    6. Typical Scenarios and Example Target Metrics

    A 31B-class dense model fits scenarios with higher demands on stability, on-premises control, and predictability — for example enterprise knowledge base Q&A, retrieval-augmented generation over documents, long-document summarization, structured information extraction, coding assistance, and multi-turn conversation.

    Example metrics to reference:

    1. Enterprise knowledge base RAG Q&A
      Knowledge base size: 500K to 5M document chunks; peak concurrency: 10 to 50; time-to-first-token target: no more than 1 second; P95 end-to-end response: no more than 3 seconds. Citation accuracy or answer traceability should be a core acceptance metric.

    2. Long-document understanding and summarization
      Input length: 8K to 32K; output length: 500 to 2000 tokens. Focus on summary coverage, factual consistency, and recall of key information.

    3. Coding assistance and completion
      This scenario is sensitive to time to first token; a 300–800ms target is reasonable. Also evaluate syntactic correctness, compile pass rate, and unit test pass rate.

    4. Structured information extraction
      Focus on JSON validity rate, field completeness rate, entity accuracy, and retry rate after failures.

    7. Developer FAQ

    Can a 31B model run on a single GPU?

    Yes, but it depends on precision, context length, and concurrency targets. After INT4 or INT8 quantization, running a 31B model on a single GPU is more feasible; with very long context or high concurrency, you will still need more VRAM or a multi-GPU setup.

    Will INT4 noticeably hurt quality?

    Not necessarily. If the workload has high precision requirements, validate INT8 first and evaluate INT4 against a calibration set. For long-text understanding, code generation, and structured output, pay particular attention to format validity rate and factual consistency.

    Is a dense model always more stable than MoE?

    Dense models generally have a more fixed compute path and more predictable latency, but an MoE model can also serve stably through routing optimization, load balancing, and capacity design. The key difference is engineering complexity.

    How do I estimate throughput?

    A simplified formula: throughput ≈ batch size × average output tokens ÷ average decode time. Actual throughput is also affected by input length, KV Cache, GPU bandwidth, and framework scheduling, so calibrate it with load tests.

    What hardware matters for on-premises deployment?

    Beyond GPU VRAM, also consider CPU memory, local storage bandwidth, model loading speed, network bandwidth, container scheduling capability, and monitoring. Weight loading, cache management, and scaling of multiple replicas for a 31B model should all be part of capacity planning.

    8. Recommendations for Developers

    For teams moving from a pilot to production, a 31B-class dense large language model is usually a solid starting point. If the team values simpler deployment, predictable latency, data control, and fast on-premises rollout, evaluate the dense option first. If the platform has strong engineering capability and the goal is maximum cost efficiency through large-scale online serving, evaluate sparse architectures as a next step.

    Whether you choose the dense or sparse path, quantization, service encapsulation, observability, and rollback mechanisms are what move a model from “it runs” to “it runs reliably in production.” The value of a 31B dense model lies not only in its moderate parameter size, but in providing fairly predictable inference within resources an enterprise controls — with a steadily lower deployment barrier as engineering work accumulates.