Deploying a 9B-Parameter Dense LLM: From Model Selection to Production

    This article provides a practical guide to deploying a dense large language model in the 9-billion-parameter range, covering model selection, version choices, KV cache estimation, tool-calling workflows, and a phased deployment plan for production environments.

    Why Choose a Dense Model in the 9B-Parameter Range?

    Choosing a model typically involves trade-offs among quality, latency, and cost. Dense models with parameter counts between a few billion and ten billion sit in a pragmatic sweet spot. They can be deployed on a single GPU or a small number of GPUs, while their general capabilities are sufficient for common scenarios such as enterprise internal assistants, code assistance, and document Q&A.

    Unlike Mixture-of-Experts (MoE) architectures, a dense model activates all of its parameters during the inference of every token. This brings two direct benefits. First, GPU memory usage can be estimated directly from the parameter count. Second, latency is more stable for the same input, and load-test results are easier to reproduce.

    For a 9-billion-parameter model, the weight footprint can be estimated as follows:

    • BF16 (2 bytes per parameter): ~9×10⁹ × 2 B ≈ 16.8 GiB
    • INT8 (1 byte per parameter): ~8.4 GiB
    • INT4 (~0.5 bytes per parameter): ~4.2 GiB

    Vendor documentation often uses GB (10⁹ bytes), but this article uses GiB (2³⁰ bytes) for consistency. The difference is roughly 7%, so it is important to normalize units before comparing numbers.

    In addition to weights, there are three other sources of overhead: KV cache, activation memory, and inference framework runtime. Runtime overhead varies significantly across inference engines. As a starting point, reserve approximately 2 GiB during planning, then adjust based on measured results.

    On a 24 GiB GPU, for example, BF16 weights plus ~2 GiB of runtime overhead leave roughly 5 GiB, primarily for the KV cache. This means both concurrency and long-context support will be noticeably constrained. Quantizing to INT8 frees up more space. Whether to quantize should be decided based on quality evaluation results, not just memory numbers.

    Model Family and Version Selection

    Models within the same generation are typically released in multiple variants:

    • Base model: Pretrained only. Suitable for further fine-tuning or domain adaptation. Usually has a shorter default context window.
    • Chat model: Fine-tuned with instruction following and preference alignment. Can be used directly for multi-turn Q&A.
    • Long-context model: Extends positional encoding and training length. Suitable for whole-document or long-log analysis.
    • Multimodal model: Adds a vision encoder on top of language capabilities. Supports mixed image-text input.

    Before selecting a version, answer three questions: How long are the inputs typically? Is image understanding required? Do you need to fine-tune the model yourself? The table below provides a starting point; specific thresholds should be validated with your own evaluation results.

    Business characteristic Recommended version Notes
    Text-only Q&A, input under 8K tokens Chat model with retrieval-augmented generation (RAG) Only relevant segments are sent to the model, minimizing memory and compute overhead
    Whole-document understanding, input between 8K and 32K tokens Long-context model Must estimate KV cache using Section 5 and run concurrency load tests
    Long documents, but questions only concern local information Chat model with RAG Lower cost, but answer quality depends on retrieval recall
    Needs to understand screenshots, charts, or mixed image-text input Multimodal model Vision encoding adds GPU memory overhead
    Needs domain-specific terminology or style adaptation Base model with fine-tuning Data quality matters more than data quantity for fine-tuning

    RAG requires maintaining a vector database and an index, and each retrieval adds an extra round of latency. Long-context models, on the other hand, cause KV cache to grow linearly with sequence length for each request, while attention computation during the prefill phase grows quadratically with sequence length. When a question requires cross-paragraph reasoning and retrieval is unlikely to surface all the necessary evidence, the cost of long-context support is usually worth bearing.

    Architecture Essentials: Dense Transformer and Attention Optimizations

    The self-attention computation in a standard Transformer scales quadratically with sequence length, and the memory footprint of the attention score matrix grows accordingly. Three techniques are commonly used for long-sequence scenarios:

    1. Grouped-Query Attention (GQA): Multiple query heads share a smaller number of key-value heads, reducing the KV cache. With H_q query heads and H_kv key-value heads, KV cache size is proportional to H_kv. The compression ratio relative to standard multi-head attention (where H_kv = H_q) is H_q / H_kv. For example, with 32 query heads and 8 key-value heads, the KV cache is one quarter the size of standard multi-head attention. A larger compression ratio increases the risk of quality degradation, and evaluation results should be the deciding factor.
    2. Sliding-window attention: Each position only attends to a local window of tokens, making per-layer attention cost roughly linear in sequence length.
    3. Positional encoding extrapolation: Adjusting the base frequency of rotary position embeddings (RoPE) or applying position interpolation allows the model to maintain usability on inputs longer than its training length. Quality after extrapolation must be verified with long-text evaluations; it is not enough to confirm that the model runs without errors.

    The core of sliding-window attention is constructing a banded mask. The following code generates this mask:

    1. import numpy as np
    2. def sliding_window_mask(seq_len: int, window: int) -> np.ndarray:
    3. """Return a boolean mask of shape (seq_len, seq_len); True means attention is allowed.
    4. The allowed range is the current position and the window-1 positions to its left,
    5. for a total of window positions (including itself).
    6. """
    7. idx = np.arange(seq_len)
    8. rel = idx[:, None] - idx[None, :] # Query position minus key position
    9. return (rel >= 0) & (rel < window) # rel >= 0 already excludes positions to the right
    10. mask = sliding_window_mask(seq_len=6, window=3)
    11. print(mask.astype(int))

    For seq_len=6 and window=3, the output is:

    1. [[1 0 0 0 0 0]
    2. [1 1 0 0 0 0]
    3. [1 1 1 0 0 0]
    4. [0 1 1 1 0 0]
    5. [0 0 1 1 1 0]
    6. [0 0 0 1 1 1]]

    The i-th query can only see keys in positions i-window+1 through i. The rel >= 0 condition in the code already excludes positions to the right, so the mask inherently contains the causality constraint and does not need to be multiplied by a lower-triangular causal mask. When window is not less than seq_len, this degenerates into an ordinary causal mask.

    Window attention loses long-range dependencies. When layers are stacked, information can propagate backward layer by layer, and the effective receptive field grows roughly with the number of layers, approximately equal to layers × (window − 1) + 1. With window=3 and 4 layers, the receptive field is about 9 positions. The window size should therefore be determined by the dependency distance required by the task, not just by GPU memory considerations. Additionally, a theoretical reduction in compute does not always translate into actual speedup; confirm that the inference engine provides a corresponding kernel implementation.

    Training Engineering and Model Selection Checks

    Data cleaning, deduplication, data mixing ratios, and low-precision training are handled by the training team. The application team’s focus is on how training precision affects deployment.

    FP8 reduces GPU memory usage and increases matrix operation throughput compared to BF16, but it has a narrower numerical range. Training typically requires dynamic scaling, and some critical layers may need to keep higher precision. These are training-side concerns. Application developers only need to confirm three things during model selection:

    • What is the training precision at release, and what inference precision is recommended?
    • Are the released weights in full precision, or already quantized? If quantized, what quantization method was used?
    • Does the target inference engine support that precision and quantization format?

    Estimating KV Cache for Long Contexts

    As context length grows, the primary bottleneck in inference often shifts from computation to the KV cache. The KV cache size for a single request can be estimated with the following formula:

    KV cache bytes = 2 × layers × kv_heads × head_dim × seq_len × bytes_per_element

    The factor of 2 accounts for the key (K) and value (V) components. Bytes per element is determined by precision: 2 for BF16 and FP16, 1 for FP8 and INT8.

    The following code uses hypothetical parameters. These do not represent any specific model’s actual configuration; they are for demonstrating the calculation method only.

    1. def kv_cache_bytes(layers: int, kv_heads: int, head_dim: int,
    2. seq_len: int, dtype_bytes: int) -> int:
    3. """Estimate the KV cache size in bytes for a single request. The factor of 2 accounts for keys and values."""
    4. return 2 * layers * kv_heads * head_dim * seq_len * dtype_bytes
    5. if __name__ == "__main__":
    6. # Hypothetical parameters, not representative of any specific model's actual configuration
    7. size = kv_cache_bytes(layers=32, kv_heads=8, head_dim=128,
    8. seq_len=32768, dtype_bytes=2)
    9. print(f"{size} B")
    10. print(f"{size / 1024**3:.2f} GiB")

    The output is:

    1. 4294967296 B
    2. 4.00 GiB

    With these parameters, a single 32K-token request requires 4 GiB of KV cache. With standard multi-head attention using 32 KV heads, the same conditions would require 16 GiB. GQA has a significant impact on GPU memory for long contexts.

    Batch size scales KV cache proportionally. Handling 4 such requests simultaneously would require approximately 16 GiB of KV cache. In the earlier 24 GiB single-GPU example with about 5 GiB remaining, only one 32K-token request could fit. If the KV cache is quantized to INT8, a single request drops to 2 GiB, allowing two concurrent requests.

    Inference engines typically allocate KV cache in blocks, so actual usage may be slightly higher than the formula suggests. It is advisable to reserve 10-20% headroom during planning.

    Tool-Calling Workflow

    Tool calling enables the model to convert a question into a structured request to an external system, such as querying an order, searching a knowledge base, or performing a calculation. A complete call typically involves the following steps:

    1. Define tools: Provide each tool with a name, a description of its function, and a JSON Schema for its parameters. The description should clearly state when this tool should be called, as the model relies on it for selection.
    2. Receive the call request: The model returns a tool name and JSON-formatted arguments. The application side must not trust this output directly.
    3. Validate arguments: Check types, required fields, and value ranges against the schema, and confirm the tool is on the whitelist. If validation fails, return the error message to the model and ask it to regenerate.
    4. Execute the tool: Set a timeout and a retry limit. Read-only tools can be retried. Write operations should not be auto-retried, as this could cause duplicate execution.
    5. Return results: Append the tool return value to the conversation as a tool message, then hand it back to the model for final answer generation.
    6. Control rounds: Set a maximum number of tool-call rounds to prevent the model from falling into a loop by repeatedly calling the same tool.

    Below is an illustrative implementation of this flow. Helper functions such as validate and tool_result need to be implemented per the actual framework:

    1. MAX_STEPS = 5
    2. def run_agent(model, tools, messages):
    3. for _ in range(MAX_STEPS):
    4. reply = model.generate(messages, tools=tools)
    5. if reply.tool_call is None:
    6. return reply.text
    7. name, args = reply.tool_call.name, reply.tool_call.args
    8. if name not in tools:
    9. messages.append(tool_error(f"Unknown tool: {name}"))
    10. continue
    11. ok, err = validate(args, tools[name].schema)
    12. if not ok:
    13. messages.append(tool_error(err))
    14. continue
    15. result = tools[name].run(args, timeout=5)
    16. messages.append(tool_result(name, result))
    17. raise RuntimeError("Exceeded maximum number of tool-call rounds")

    Important considerations:

    • Treat tool-returned content as data, not as instructions. Text in web pages or documents that asks the model to call other tools should be ignored and logged.
    • Grant tools minimal privileges. Read-only tools and write tools should be authorized separately.
    • Write or delete operations require human confirmation before execution.
    • Log tool names, argument summaries, and duration. Do not log keys, secrets, or personally identifiable information (PII).

    Deployment Plan

    Deployment can proceed in five phases:

    1. Resource planning: Use the formulas from Sections 1 and 5 to calculate the concurrency and maximum context length a single GPU can support. The memory budget is the sum of weights, KV cache, runtime overhead, and headroom.
    2. Choose an inference engine and precision: Compare quality and throughput between BF16 and INT8. Base conclusions on your own evaluation data.
    3. Load testing: Focus on time to first token (TTFT), per-output-token latency (TPOT), overall throughput, and P95/P99 latencies. The input length distribution in load tests must match real production traffic; do not rely on short text alone.
    4. Canary rollout: Start with 5% of traffic, monitor error rates, latency, and answer quality, then gradually expand once no anomalies are observed.
    5. Rollback: Keep the previous version’s weights and configuration. Switching only requires changing the routing config.

    Pre-launch checklist:

    • Measured peak memory is below 85% of GPU capacity
    • Requests at maximum context length have passed load testing
    • Tool-call timeout, retry, and round limits are configured
    • Logs do not contain keys or personal sensitive information
    • Rollback steps have been rehearsed

    After launch, monitor memory utilization, request queue depth, error rates, and timeout rates.

    Building Your Own Evaluation Set

    Public benchmark scores do not represent your business-specific performance, so an internal evaluation set is necessary:

    • Collect 200-500 samples from real business traffic, covering short inputs, long inputs, tool calls, and scenarios that require refusal.
    • Define scoring criteria for each task type. Use rules or check scripts for tasks that can be auto-graded. For subjective questions, have two people score independently and take the average.
    • Keep the sample set fixed as a regression baseline. Re-run it every time you change models, adjust quantization, or modify prompts.
    • Compare quality and cost together, such as memory usage and cost per thousand requests, rather than making decisions based on a single metric.