Deploying and Tuning 31B Dense LLMs: A Practical Guide for Memory, Quantization, and Long-Context Serving

    This article is a practical guide to deploying and tuning a 31B dense large language model on single-card or single-node hardware. It explains why dense models at this scale fit within mainstream data-center GPU memory, how to budget memory by computing KV cache before weights, and how low-bit KV and weight quantization trade accuracy for capacity. It also covers the effective use of long context windows, evaluating code and agent capabilities, building private evaluation sets, and choosing between single-card on-premise deployment and elastic cloud serving. Engineers will find memory-budgeting formulas, a KV-cache calculation script, an agent-loop pattern, an evaluation framework, and a checklist of common pitfalls.

    Deploying and Tuning 31B Dense LLMs: A Practical Guide

    1. First, a fact: the 31B scale brings dense models back into the practical range

    Open-source LLMs have clearly polarized over the past two years. At one end are flagship models with hundreds of billions of parameters that trade capability ceiling for sparse activation via mixture-of-experts (MoE). At the other end are small models ranging from a few hundred million to a few billion parameters, aimed at on-device and low-cost scenarios. Between the two, there has long been a gap—parameter counts too small to support complex reasoning and coding, yet deployment costs already out of reach for consumer-grade hardware.

    Dense models at 31B parameters sit right in this gap and have three properties that are critical from an engineering standpoint:

    • Dense structure, predictable compute. In MoE models, only part of the parameters are activated, so theoretical compute cost is low, but problems like uneven expert-routing load, cross-device all-to-all communication, and large numbers of “silent experts” in memory that are hard to share arise. In dense models, every parameter participates in the forward pass, the operator graph is regular, throughput under batching is stable, and capacity planning doesn’t need to reserve headroom for routing jitter.
    • Weight footprint aligns with mainstream single-card memory. Under bfloat16, 31B parameters need roughly the 60GB range just to hold the weights; together with KV cache and runtime overhead, this fits within the capacity boundary of a single 80GB-class data-center GPU. This means a complete inference service can be served by one machine with one card, without introducing the communication and sharding complexity of tensor parallelism.
    • The performance curve is still in its steep-rising phase. Compared with 2B/4B small models in the same series and 26B-class sparse models, the 31B dense version shows a noticeable jump in general knowledge, competition math, code generation, and tool calling. In public comprehensive academic-knowledge evaluations, models at this level generally score above 80%, and competition-level math and code evaluations hold steady in the 80-point range, placing them in the top tier among mid-sized models.

    The conclusion is direct: if what you need is not the “ultimate capability ceiling” but “near-frontier reasoning and coding ability at a controllable cost on a single card or single machine,” the 31B dense model is currently the option most worth validating first.

    2. How to budget memory: KV cache matters more than parameter count

    The first pitfall many teams hit when deploying is estimating memory by parameter count alone. Actual memory usage is the sum of four items:

    1. total memory ≈ weight memory + KV cache + activations and framework overhead + communication/temporary buffers

    The weight portion is easy to compute and depends on the precision format:

    Precision format Bytes per parameter 31B weight footprint
    bfloat16 / FP16 2 B ≈ 62 GB
    FP8 1 B ≈ 31 GB
    INT4 (W4A16) 0.5 B + quantization metadata ≈ 17–20 GB

    KV cache is the real variable. It grows linearly with “sequence length × concurrency”:

    1. KV_bytes = 2 × L × H_kv × d_head × bytes_per_elem × seq_len × batch
    2. # 2 for the K and V copies; L = number of layers; H_kv = number of KV heads (much smaller than attention heads after GQA)

    Plugging in a typical 31B dense configuration (40 layers, 8 KV heads, head_dim 128, bf16 storage):

    • Each token takes about 2 × 40 × 8 × 128 × 2 = 163,840 bytes, or about 160 KiB;
    • A single 32K-context request takes about 5 GB;
    • Serving 128 long-context requests at once, the KV cache alone needs about 640 GB.

    These numbers explain a common confusion: why the model “fits on one card” yet the service can’t run. When 256K context and high concurrency both hold, KV cache quickly surpasses the weights themselves as the dominant term. So the right way to budget memory is to compute KV first, then work backward to the concurrency and context length you can support, and only then decide whether quantization is needed.

    1. def kv_budget(n_layers, n_kv_heads, head_dim, bytes_per_elem=2):
    2. """Return per-token KV bytes and total usage under a given context/concurrency"""
    3. per_token = 2 * n_layers * n_kv_heads * head_dim * bytes_per_elem
    4. for seq_len in (8192, 32768, 131072, 262144):
    5. per_req = per_token * seq_len / (1024 ** 3)
    6. print(f"ctx={seq_len:>7} single_req={per_req:6.2f} GiB "
    7. f"32_concurrent={per_req * 32:8.2f} GiB")
    8. return per_token
    9. kv_budget(n_layers=40, n_kv_heads=8, head_dim=128)

    3. Quantization: the gains and costs of pushing KV cache down to 3–4 bits

    In response to the bottleneck above, the industry has seen a class of low-bit quantization schemes in recent years specifically designed to compress KV cache, reducing KV storage from 16 bits to the 3–4 bit range. Their engineering value can be understood as follows:

    • Memory dimension: KV usage drops to 1/4–1/5 of the original, equivalent to multiplying the supported concurrency or context length several-fold within the same memory. The 640GB scenario above compresses back to around the 160GB range, making multi-card single-machine or single-card low-concurrency setups viable again.
    • Bandwidth dimension: Decoding is a thoroughly memory-bound scenario—every generated token requires reading the entire history of KV. Reducing KV volume directly cuts HBM bandwidth pressure, and combined with highly optimized attention kernels, such schemes have reportedly achieved several-fold attention-compute speedups with near-lossless results on core accuracy metrics.
    • Cost dimension: Low-bit KV is sensitive to quantization granularity and outliers; choices like group size, per-head vs. per-token quantization, and whether to keep a few channels at high precision all affect recall at the tail of long sequences. You must run long-context regression on your own business corpus rather than only on short samples.

    The trade-off logic for weight quantization differs slightly from KV and can proceed in the following low-risk order:

    1. Quantize KV first, and verify that long-context task accuracy doesn’t drop;
    2. Then quantize weights with FP8 (bfloat16 weights can run at full speed directly when the hardware supports FP8), which usually causes minimal accuracy loss;
    3. Only then consider INT4 weight quantization, enabled only when memory is a hard constraint, combined with a small calibration set for low-rank fine-tuning compensation.

    An easily overlooked piece of experience: don’t quantize and fine-tune at the same time. Quantize-then-fine-tune and fine-tune-then-quantize yield noticeably different model behavior; the more reliable engineering approach is to fix the quantization scheme first, then do low-rank adaptation fine-tuning on top of it.

    4. 256K context: the pull between capability ceiling and cost floor

    An ultra-long context window is a selling point of this generation of models, but it’s also the capability most easily misused.

    • Computational complexity is unavoidable. Standard attention has quadratic complexity in sequence length. At 256K context, the prefill phase costs far more time and compute than decoding, and time-to-first-token (TTFT) becomes a bottleneck users can feel. Schemes like sparse attention, chunked local attention, and state-space hybrids each have trade-offs; when choosing, use “effective context” rather than “nominal context” as the metric.
    • Effective context is far smaller than nominal. Evaluations should include tasks like “multi-needle retrieval,” “cross-document aggregation,” “long-text summary consistency,” and “long-range code repository Q&A,” placing key information at the beginning, middle, and end to observe how flat the recall curve is. Many models show clear degradation beyond 64K.
    • Don’t force into context what retrieval can solve. The right architecture for long-document Q&A is usually a “hybrid approach”: structured retrieval locates candidate snippets, then the snippets are sent with the question into a 32K-class context, letting the model reason over high-quality input. The longer the context, the higher the risk of attention being diluted by noise, and cost also rises linearly.

    5. Code and agent capabilities: from “writing functions” to “completing tasks”

    The two most commercially valuable capability directions for a mid-sized model are code and agents, and their evaluation methods are entirely different.

    Code ability should be viewed in three layers: function-level completion, competition-style single-file problem solving, and repository-level defect fixing and multi-file refactoring. In public evaluations, models at this level can reach an Elo tier of 2000+ in algorithm competitions and a pass rate close to 80% on real-time code generation benchmarks, but these results mainly come from single-file, self-contained problems and cannot be directly inferred as repository-level engineering ability. Teams should build their own internal evaluation sets, using real private repositories with real build and test commands, with metrics based on “first-attempt pass rate” and “test pass rate” rather than subjective human scoring.

    The core of agent ability is loops and constraints. An illustrative implementation:

    1. def agent_loop(model, tools, task, max_steps=12):
    2. messages = [{"role": "user", "content": task}]
    3. for step in range(max_steps):
    4. # Key 1: constrain decoding with a schema so tool calls are parseable structured output
    5. reply = model.generate(
    6. messages,
    7. tools=[t.schema for t in tools],
    8. response_format="tool_call",
    9. temperature=0.0,
    10. )
    11. if reply.tool_call is None:
    12. return reply.text # task finished
    13. obs = tools[reply.tool_call.name]( # Key 2: run tools in a sandbox with least privilege
    14. **reply.tool_call.arguments
    15. )
    16. messages.append(reply.to_message())
    17. messages.append({"role": "tool", "content": truncate(obs, limit=8_000)})
    18. return "Step limit reached; returning intermediate findings and unfinished items"

    Three engineering constraints that must be enforced: first, structured output constraints—use schema or grammar-constrained decoding to push tool-call format error rates to near zero, which is far more reliable than post-hoc regex repair; second, sandbox and least privilege—code execution, file read/write, and network access must all be isolated, and tool credentials issued per call; third, context trimming and budget—tool return results must be truncated, or a single observation can consume the entire window, and the loop must have a hard step limit to prevent ineffective self-loops from burning compute.

    6. Multimodal input: the engineering pipeline for OCR and chart understanding

    Models at this level begin to natively support image and video input and have OCR and chart-analysis capabilities, which lets a batch of business scenarios that originally required a standalone OCR pipeline plus rule-based parsing be compressed into a single multimodal inference. Things to note when deploying:

    • Resolution and chunking strategy set the ceiling. For document images, do layout analysis first and then send in blocks—this works far better than scaling the whole page; for tables, provide both the image and structured text so the model can cross-validate.
    • Control video frame rate and keyframe selection, and align subtitle information by timestamp, or long videos will quickly exhaust the context budget.
    • Distinguish “recognition” from “understanding” in evaluation. Character recognition accuracy and “whether a conclusion can be derived from it and anomalies pointed out” are two different abilities; the latter is what corresponds to business value.

    7. Evaluation and model selection: turning public scores into your own decision basis

    Public leaderboards can only be used to narrow down the candidate pool; the final decision must be based on a private evaluation set. The recommended framework:

    Dimension Evaluation method Key metrics
    General understanding & reasoning Private business QA set (500–2000 items) Accuracy, hallucination rate
    Competition math / logic Difficulty-tiered problem set Tiered pass rate, chain-of-thought consistency
    Code generation Private repos + real unit tests First-attempt pass rate, test pass rate
    Agent / tool calling Multi-step task scripts Task completion rate, average steps, format error rate
    Long context Multi-needle retrieval + cross-document aggregation Recall by position, effective window length
    Engineering metrics Load testing TTFT, TPOT, throughput tokens/s, P95 latency, per-card concurrency

    Once an evaluation set is built, it must be versioned and brought into continuous integration; every model or inference-config change (including switching quantization schemes or changing sampling parameters) should run a regression pass. Only this way can problems like “switching to INT4 to save memory, only to find long-document recall dropped 10 points” be caught before going live rather than after.

    8. Deployment forms: single-card on-premise and elastic cloud serving

    Single-card on-premise deployment suits scenarios where data can’t leave the domain and concurrency is low (single digits to a dozen or so). The fact that bfloat16 weights fit on a full card and FP8 runs at full speed means an 8-card server can either run a single high-throughput instance or spin up multiple independent instances for isolation, with simple capacity planning.

    Elastic cloud serving suits scenarios with large traffic fluctuations and a need to route across multiple model specs. A typical approach is to containerize the inference service and hand it to a container platform, build node pools by memory spec, and use elastic scaling to handle traffic peaks; model weights and versions are stored in object storage and pulled with verification when instances start; connect logging and monitoring/alerting, and set thresholds and auto-scaling policies for TTFT, TPOT, memory watermarks, failure rates, and token consumption. On Baidu AI Cloud, such capabilities can be assembled from general products like the container platform, object storage, logging, and monitoring/alerting, while the inference-framework side is uniformly wrapped as standard HTTP/gRPC interfaces, so business teams don’t perceive whether the underlying hardware is a GPU or another accelerator.

    Cost control hinges on metering tokens as a resource: tally the average input/output length per request type, compute unit cost via “per-card throughput × card price ÷ effective output tokens,” and then decide which requests go to the 31B and which are pushed down to small models or routed to cache. Tiered routing usually reduces costs more significantly than simply switching to a smaller model, with controllable quality loss.

    9. Common pitfalls checklist

    1. Counting only weights, not KV, leading to OOM under high concurrency—build a KV budget table first.
    2. Chasing nominal context length, making 256K the default and losing control of prefill latency and cost; open windows on demand, and prioritize retrieval for long documents.
    3. Not running long-context regression after quantization—short samples all pass while long-document recall collapses.
    4. Not applying schema constraints to tool calls, constraining format with prompts instead, so agent stability can’t be guaranteed.
    5. Substituting algorithm-problem scores for engineering-ability evaluation of code ability, so repository-level task pass rates fall far below expectations after launch.
    6. Overlooking the cost of multimodal input—the token conversion for images/video and preprocessing overhead are often left out of the budget.
    7. No versioned evaluation set, so model upgrades lack comparable data and it’s impossible to tell whether there’s a regression.

    Overall, the value of a 31B-class dense model doesn’t lie in leading any single metric, but in compressing “good-enough complex reasoning and coding ability” into a cost structure that a single card can carry. What truly determines deployment success are the quantitative memory and KV budgeting, the effective use of long context, the engineering constraints of tool calling, and a continuously regression-tested private evaluation system—get these four right, and a mid-sized model can fully take on the role of an enterprise-side primary inference service.