Single-GPU Deployment for 31B Dense Models: Memory Sizing, Quantization, and Validation
This article provides a practical framework for deciding whether a 31B-parameter dense model can be deployed on a single 80 GB accelerator. It covers memory budgeting for weights, KV cache, activations, and runtime overhead; quantization tradeoffs and acceptance thresholds; long-context and multimodal input costs; internal evaluation and agent validation metrics; and go/no-go criteria for canary rollout. It includes sizing formulas, a Python screening script, and tables of suggested thresholds so readers can validate configurations before production deployment.
1. Scope and Conventions
This article focuses on single-GPU inference and assumes a nominal 80 GB accelerator. A dense model uses all parameters in every forward pass. Its structure is simple, and inference framework compatibility is generally good. Once a model cannot fit on one GPU, cross-GPU communication is required, which increases latency variance and operational complexity. Therefore, whether the model fits on a single GPU is the first selection gate.
The following conventions apply throughout this article:
- GB is decimal: 1 GB = 10^9 bytes.
- GiB is binary: 1 GiB = 2^30 bytes, approximately 1.074 GB.
- Actual available GPU memory depends on the driver, ECC settings, and framework. Use
nvidia-smior framework measurements as the source of truth.
2. Memory Budget: Weights Are Only One Part
Memory usage has four components: model weights, KV cache, activations and temporary buffers, and runtime overhead. Looking only at the weight file size will underestimate actual requirements.
Weight memory equals the number of parameters multiplied by the number of bytes per parameter. For 31e9 parameters:
| Precision | Calculation | Weights (GB) | Weights (GiB) |
|---|---|---|---|
| FP16 / BF16 | 31e9 × 2 bytes | 62.0 | 57.7 |
| INT8 | 31e9 × 1 byte | 31.0 | 28.9 |
| INT4 (group-wise quantization) | 31e9 × 0.5 bytes × 1.06 | 16.5 | 15.3 |
The 1.06 factor in the INT4 row is an estimate for quantization metadata. Assuming one FP16 scale and zero point per 128 weights, metadata is about 0.25 bits per parameter, or roughly 6%. Memory for calibration data and one-time overhead is not included in this table.
The KV cache stores the keys and values used in attention calculations and grows linearly with context length and concurrency. The formula is:
Bytes per token = 2 × number of layers × number of KV heads × head dimension × bytes per element
Assume a demonstration architecture: 64 layers, 8 KV heads, head dimension 128, and an FP16 KV cache. Each token uses 262,144 bytes, or about 0.262 MB. These values are for demonstration only; read actual values from the model configuration file.
- A single 32K-context request: about 8.6 GB (8.0 GiB).
- Four concurrent requests at 32K each: about 34.4 GB (32.0 GiB).
On an 80 GB GPU, FP16 weights consume 62.0 GB. After subtracting 2 GB of runtime overhead, about 16 GB remains, which can barely hold one 32K request with almost no concurrency headroom. With INT8 weights, about 47 GB remains, which can hold KV cache for four concurrent 32K requests and still leave about 12 GB of headroom.
The following script reads architecture parameters from the model directory and can be used for a quick pre-deployment configuration screen:
import jsonfrom pathlib import PathGB = 1e9 # Decimal: 1 GB = 10^9 bytesGIB = 2 ** 30 # Binary: 1 GiB = 2^30 bytesdef load_arch(model_dir: str) -> dict:"""Read architecture parameters from config.json in the model directory; do not fill them in manually."""cfg = json.loads((Path(model_dir) / "config.json").read_text(encoding="utf-8"))heads = cfg["num_attention_heads"]return {"layers": cfg["num_hidden_layers"],"kv_heads": cfg.get("num_key_value_heads", heads),"head_dim": cfg.get("head_dim") or cfg["hidden_size"] // heads,}def weight_bytes(params_b: float, bits: float, overhead: float = 0.0) -> float:"""Weight bytes. params_b is the parameter count in billions; overhead is the quantization metadata ratio."""return params_b * 1e9 * bits / 8 * (1 + overhead)def kv_cache_bytes(arch: dict, seq_len: int, batch: int, dtype_bytes: int = 2) -> float:"""KV cache bytes. Each token stores one set of K and one set of V at every layer."""per_token = 2 * arch["layers"] * arch["kv_heads"] * arch["head_dim"] * dtype_bytesreturn per_token * seq_len * batchdef free_after_weights(card_gb: float, weights_bytes: float, runtime_gb: float = 2.0) -> float:"""Memory available for KV cache and activations after weights and runtime overhead, in GB."""return card_gb - weights_bytes / GB - runtime_gbif __name__ == "__main__":arch = load_arch("/path/to/model") # Replace with the real model directorykv = kv_cache_bytes(arch, seq_len=32768, batch=4) / GBfor name, bits, ovh in [("FP16", 16, 0.0), ("INT8", 8, 0.0), ("INT4", 4, 0.0625)]:w = weight_bytes(31, bits, ovh)free = free_after_weights(80, w)print(f"{name}: weights {w / GB:.1f} GB ({w / GIB:.1f} GiB), "f"remaining {free:.1f} GB, KV cache for 4 concurrent x 32K about {kv:.1f} GB")
This script is a rough screening tool with two limitations. First, it does not include activations or fragmentation, so results must be verified with stress testing. Second, if the model uses a compressed attention structure such as MLA, the KV formula above no longer applies, and framework measurements should be used instead.
3. Quantization Tradeoffs: Use Thresholds to Decide Whether Accuracy Loss Is Acceptable
Quantization converts weights from higher precision to lower-bit representations. The memory benefit is deterministic; the accuracy cost depends on the task. Three common approaches are:
- Post-training quantization: no retraining is required; existing weights are converted directly. Implementation cost is low.
- Group-wise quantization: weights are split into small groups, and scaling factors are calculated per group. Smaller groups usually improve accuracy but add more metadata.
- Weight-only quantization: only weights are compressed while activations remain at higher precision, balancing speed and stability.
Calibration data should come from business scenarios, usually a few hundred to a few thousand samples. The calibration set must be separate from the evaluation set; otherwise, evaluation results will be inflated.
Average scores do not represent every case. Even when overall scores do not drop much, the error rate for a specific output format can still rise significantly. Set thresholds such as the following first, then adjust them according to business risk:
| Check | Pass criterion (suggested starting point) |
|---|---|
| Output format validity rate | JSON can be parsed by json.loads and passes schema validation at no less than 99%, with no more than a 1 percentage point drop relative to baseline |
| Key field accuracy | No more than a 2 percentage point drop relative to the FP16 baseline |
| Long-input stability | Accuracy at the target length drops no more than 5 percentage points relative to the short-input baseline, and format validity still meets the threshold |
Make quantization decisions in the following order:
- If FP16/BF16 can support the target concurrency and length while peak usage stays below 85% of nominal GPU memory, keep FP16.
- Otherwise, try INT8 weight quantization. Adopt it if all three checks pass.
- If it still does not meet requirements, try INT4 group-wise quantization. Adopt it if all three checks pass, and continue monitoring after launch.
- If INT4 still fails, reduce maximum sequence length or concurrency, or change hardware or model. Do not relax thresholds just to ship.
4. Long Context: Window Size Is Not the Same as Usable Capability
A model that supports a 256K context means its positional encoding and training length cover that range. It does not guarantee that the model can reliably retrieve and reason at that length.
Start with memory. Using the demonstration architecture from the previous section, the FP16 KV cache for a single 256K (262,144-token) request is:
262,144 × 262,144 bytes ≈ 68.7 GB (64.0 GiB)
Even with INT8 weights (31 GB) and 2 GB subtracted for runtime overhead, an 80 GB GPU leaves only about 47 GB for KV cache, which cannot hold this single request. KV cache quantization can halve this again, but it is a separate quantization change that must be validated independently.
Next, consider accuracy. The longer the input and the more distracting information it contains, the more retrieval and citation accuracy can degrade. Use needle-in-a-haystack style tests and evaluate across length and position buckets:
- Length buckets: 4K, 32K, 128K, 256K, and so on.
- Position buckets: information at the beginning, middle, and end.
- At least 20 samples per bucket, recording accuracy and peak memory.
When input exceeds the usable limit, three common handling strategies have different failure modes:
- Reject directly and ask the user to split the input. Failure is visible, but user experience suffers.
- Truncate and keep only the most recent or most relevant parts. Key information may be lost, and the truncation ratio must be logged.
- Chunk and retrieve. This depends on retrieval quality; missed retrieval directly causes incorrect answers.
At runtime, count how often finish_reason is length. This reflects how often output is truncated and is a direct signal that a limit may be set too tightly.
5. Multimodal Inputs: The Hidden Cost of Images and Audio
The cost of multimodal inputs is often overlooked. Images and audio are encoded into many tokens, consuming context and KV cache and increasing first-token latency.
The number of image tokens depends on resolution and visual encoder parameters. An approximate formula is:
Image tokens ≈ ⌈H / s⌉ × ⌈W / s⌉, where s = patch size × merge factor
Read the specific patch size and merge factor from the model documentation. For example, with a patch size of 14 and a merge factor of 2, s is 28. A 1024×1024 image is about 37 × 37 = 1369 tokens. A request with eight such images would consume about 11k tokens of context.
The visual encoder’s own weights and activations must also be included in the memory budget. Confirm its parameter count from the model configuration and documentation; it cannot be ignored. For audio, convert token counts using the sample rate and frame rate given in the model documentation, and set a maximum duration per request.
In engineering, implement the following controls:
- Limit maximum pixel count, downscale proportionally when exceeded, and state this in the response.
- Limit the number of images and audio duration per request.
- On out-of-memory or timeout, retry with lower resolution and tell the user that degradation occurred.
- Explicitly reject over-limit inputs with a reason; do not silently truncate.
- Measure first-token latency separately because the encoding stage delays the first output token.
6. Internal Evaluation and Agent Capability Validation
The evaluation set is the basis for model selection; its quality matters more than model leaderboards.
When building a business evaluation set, sample in layers by task type. Use at least 300 samples per task type and cover three sample categories: normal inputs, boundary inputs, and long inputs. Keep a gold answer and valid output format for every sample. The evaluation set and the quantization calibration set must be stored separately.
Core metrics include:
- JSON validity rate: the proportion that
json.loadssuccessfully parses and that pass schema validation. - Key field accuracy: the proportion of extraction or judgment results that match the gold answer.
- Tool call success rate: the proportion where the function name is correct, arguments pass schema validation, and tool execution returns success.
- Long-task completion rate: the proportion of tasks completed without human intervention within a given step limit.
- Performance metrics: first-token latency, output tokens per second, p95 latency, and peak memory.
Agent task outputs are stochastic. Run each sample at least three times, fix decoding parameters, and report both success rate and variation. Reporting only a single run can mistake an accidental success for stable capability.
Suggested starting points for rollout thresholds are below; teams should adjust them according to business risk:
| Metric | Threshold |
|---|---|
| JSON validity rate | No less than 99%, with no more than a 1 percentage point drop relative to baseline |
| Key field accuracy | No more than a 2 percentage point drop relative to baseline |
| Tool call success rate | No more than a 3 percentage point drop relative to baseline |
| Long-task completion rate | No more than a 5 percentage point drop relative to baseline |
| p95 latency | Meets business SLA |
| Peak memory | No more than 85% of nominal GPU memory |
Before launch, keep the FP16 checkpoint and the current deployment configuration for rollback. During canary rollout, switch a small share of traffic first, for example 5%. If any threshold is triggered continuously, roll back. Rollback operations should be scripted and rehearsed in advance rather than performed ad hoc during an incident.
7. Selection Conclusions and Unsuitable Scenarios
Based on evaluation results, decide the next step in one of three tiers:
- Scale up: all thresholds are met, canary has run for at least 7 days, and p95 latency and error rates are within SLA. Traffic can then be expanded gradually.
- Minor changes: one metric fails. Prioritize adjusting maximum sequence length, concurrency, or quantization method, then re-evaluate. Do not directly relax thresholds.
- Reselect: multiple metrics fail at the same time, or tool call success rate remains below baseline. Change the model or hardware, or split the task across multiple smaller models.
The single-GPU approach in this article is not suitable for the following scenarios:
- Business concurrency is far higher than single-GPU throughput, and latency jitter is unacceptable. In this case, consider multiple GPUs or service decomposition.
- The team has no business evaluation set and cannot validate quantization or tool-call behavior. In this case, do not ship a quantized version directly.
- The task requires input modalities beyond the model’s supported range, or must process documents longer than the usable limit.
- Output directly drives high-risk actions such as financial settlement or device control. In this case, add a rule-based validation layer; do not rely solely on model output.
