Inference Optimization and Multimodal Practices for Mid-Sized Dense Large Language Models

    This article explores engineering practices for deploying mid-sized dense large language models (LLMs), specifically focusing on models around the 31-billion parameter scale. It covers single-GPU resource planning, low-bit KV cache compression, 256K long-context implementation strategies, multimodal processing, and the service-oriented design of code and AI agent capabilities, providing practical guidelines for balancing performance, accuracy, and cost in production environments.

    Inference Optimization and Multimodal Practices for Mid-Sized Dense Large Language Models

    1. Background: Why Mid-Sized Dense Models Still Matter

    In large language model (LLM) engineering, parameter scale is not the only metric to consider. Sparse Mixture of Experts (MoE) models can reduce per-token computation through conditional activation, but they introduce additional complexity in routing, load balancing, expert parallelism, and memory fragmentation management. In contrast, dense models activate all parameters per token, offering stable inference paths, predictable batching behavior, and shorter debugging cycles. They are particularly well-suited for complex reasoning, code generation, tool calling, and multi-step agent tasks.

    Taking a dense model with approximately 31 billion parameters as an example, it forms a representative sweet spot between capability and resources. Capability-wise, it is sufficient for long-document understanding, structured extraction, code assistance, and scientific reasoning. Resource-wise, it can be hosted on a single high-VRAM GPU, lowering the barrier to entry for small teams and edge data centers. Estimating at bfloat16 precision, 31B parameter weights consume about 62GB of VRAM; when placed on an 80GB GPU, there is still headroom for KV cache, intermediate activations, and batching. However, the real engineering challenge lies not in the weights themselves, but in cache management under long contexts, multimodal inputs, and high concurrency.

    Therefore, the discussion around such models should shift from “how many parameters” and “benchmark scores” to three actionable questions: how to partition single-GPU resources, how to prevent memory explosions with long contexts, and how to build stable services for multimodal and agent capabilities.

    2. Single-GPU Deployment: Resource Boundaries and Capacity Planning

    The first step in single-GPU deployment is establishing a memory budget model. For dense models, VRAM primarily consists of four parts: model weights, KV cache, intermediate activations, and runtime reserves. Weights can be estimated by “parameter count × bytes per parameter.” KV cache strongly correlates with the number of layers, KV heads, head dimension, sequence length, concurrency, and precision. The simplified formula is as follows:

    1. KV Memory ≈ 2 × Number of Layers × Number of KV Heads × Head Dimension × Sequence Length × Concurrency × Bytes per Element

    The coefficient 2 accounts for both Key and Value caches. At a 256K context length, the KV cache for a single request is already substantial; layering high concurrency on top of this will rapidly turn VRAM into a bottleneck. Engineering practices typically employ the following combined strategies:

    1. Paged KV Cache: Allocates and reclaims cache by page, avoiding the need to reserve large contiguous memory blocks for each request, thereby reducing fragmentation.
    2. Prefix Cache Reuse: Caches system prompts, fixed knowledge base fragments, and long document prefixes to reduce redundant pre-filling.
    3. Continuous Batching: Dynamically batches requests of varying lengths to improve utilization during the decode phase, though care must be taken to prevent long requests from blocking short ones.
    4. Low-bit KV Compression: Compresses the cache to 3-bit levels, combined with group scaling and outlier compensation, aiming to maintain acceptable accuracy on core metrics.
    5. Multi-GPU or Tiered Fallback: When single-GPU concurrency is insufficient, use tensor parallelism or horizontal scaling of multiple replicas instead of infinitely extending a single request’s context.

    During cloud deployment, inference services can be deployed on container platforms, using object storage to manage model files and multimodal samples, and logging/monitoring services to collect Time To First Token (TTFT), throughput, peak VRAM, and error rates. Cloud providers like Baidu AI Cloud offer general containers, object storage, and logging/monitoring capabilities, but specific capacity requirements still need to be determined through load testing based on business concurrency and context distribution.

    3. Engineering Essentials for Low-bit KV Compression and Attention Acceleration

    One of the primary costs of long-context inference is not matrix multiplication, but the read/write bandwidth of the KV cache. Compressing the KV cache to low-bit significantly reduces bandwidth usage, freeing up space for longer sequences or higher concurrency. However, low-bit quantization is not simple truncation; it requires addressing the following issues:

    • Outlier Handling: A small number of large-magnitude elements can amplify quantization errors. This can be mitigated using group scaling, per-channel scaling, or by preserving high precision for critical channels.
    • Error Compensation: Apply different quantization strategies for Keys and Values, or perform dequantization compensation before attention score calculation.
    • Precision Acceptance: Post-compression evaluation should not only check perplexity but also ensure there is no degradation in tasks like long-document QA, retrieval positioning, code completion, and multi-hop reasoning.
    • Kernel Fusion: Fuse dequantization, attention score calculation, and weighted summation into a blocked kernel to reduce extra memory round-trips.

    Metrics such as “8x attention compute acceleration” should be understood as end-to-end gains under specific hardware, sequence lengths, and batching conditions, and cannot be directly extrapolated to all use cases. Actual acceptance testing should simultaneously record TTFT, Time Per Output Token (TPOT), throughput, peak VRAM, and task accuracy before and after compression. If compression causes a noticeable decline in long-context retrieval capability, you should revert to higher-bit caches or preserve high precision for critical layers.

    4. Implementation Strategies for 256K Context

    The value of 256K context lies in reducing cross-document splicing and multiple retrievals, but it is not a free capability. As context length increases, so do pre-fill costs, KV cache usage, and attention computation complexity; the model may also suffer from “lost in the middle” information loss. Engineering practices recommend a tiered context strategy:

    1. Short Context Priority: Use Retrieval-Augmented Generation (RAG) to solve problems without forcing full documents into the prompt.
    2. Segmented Summary & Structured Indexing: Split long documents by sections, summarize, and index entities first, then recall relevant fragments based on the query.
    3. Prefix Caching & Incremental Pre-filling: Fix system prompts and common knowledge prefixes to reduce redundant computation.
    4. Context Pruning & Reordering: Place highly relevant fragments closer to the query to reduce long-distance dependency pressure.
    5. Long Context Specific Evaluation: Construct business test sets for needle-in-a-haystack retrieval, multi-hop QA, cross-page table reasoning, and timeline understanding to observe decay curves at different lengths.

    A pseudo-code example is as follows:

    1. def build_context(query, docs, max_tokens):
    2. chunks = split_by_section(docs)
    3. ranked = rank_by_relevance(query, chunks)
    4. selected = []
    5. used = 0
    6. for chunk in ranked:
    7. if used + chunk.tokens <= max_tokens * 0.7:
    8. selected.append(chunk)
    9. used += chunk.tokens
    10. summary = summarize_unselected(docs)
    11. return assemble(summary, selected, query)

    The core of this strategy is “retrieval first, summary fallback, cache reuse, segmented validation,” rather than dumping all content into the model at once.

    5. Multimodal Input, OCR, and Chart Analysis

    Natively supporting image and video inputs means the model service pipeline must expand from text-only to visual encoding, image splitting, frame sampling, and cross-modal alignment. In OCR scenarios, directly scaling high-resolution documents loses small text; splitting, coordinate mapping, and layout analysis are usually required. Chart analysis needs to identify axes, legends, data series, and numerical relationships, rather than relying solely on image descriptions.

    Video input also requires handling frame sampling strategies: fixed-interval sampling is simple but may miss key segments, while sampling based on scene changes or motion magnitude is finer but more expensive. Engineering practices can store video frames, image splits, and OCR results in object storage, process them asynchronously via message queues, and then feed structured results into the model. For agent scenarios, multimodal results should be converted into trackable intermediate structures, such as tables, entity lists, timestamps, and confidence scores, facilitating subsequent tool calls and human review.

    6. Servitization of Code and Agent Capabilities

    Code and agent capabilities cannot be evaluated solely by single-shot generation. Code tasks require repository-level context, compile-test feedback, and static checking loops; agent tasks require tool descriptions, permission control, sandbox execution, timeout retries, and full-chain observability. A stable agent service typically includes:

    • Tool registration and parameter schema validation;
    • Plan, execute, observe, and correct loop control;
    • Sandboxed code execution and file system isolation;
    • Call logs, trace tracking, and cost statistics;
    • Manual confirmation nodes and failure rollback mechanisms.

    For a ~31B parameter dense model, a single GPU can host the weights, but high-concurrency agent loops will amplify KV cache and tool wait times. It is recommended to decouple the inference service from the tool execution service, use asynchronous queues for load shedding, and set maximum steps and budget thresholds for long loops.

    7. Evaluation, Acceptance, and Model Selection

    Public benchmarks only serve as an initial filter and cannot replace business acceptance testing. It is recommended to establish four categories of metrics: task accuracy, long-context degradation, inference performance, and multimodal quality. The performance side focuses on TTFT, TPOT, throughput, peak VRAM, and batching efficiency; the quality side focuses on the legality rate of structured output, OCR character accuracy, chart data extraction accuracy, and code test pass rate.

    Final model selection should follow the principle of “scenario first, verifiable accuracy, calculable cost, feasible fallback”: validate compression and long-context strategies on a small-scale business set first, then gradually expand concurrency; retain high-precision caches or dual-model fallbacks for critical tasks; and in general cloud environments like Baidu AI Cloud, build an observable inference foundation through container platforms, object storage, and logging/monitoring services to achieve a continuous balance of cost, throughput, and quality.