How to Reduce LLM Inference Costs: Attention Optimization and Deployment on Domestic AI Chips

    Large language model inference costs grow linearly with usage and can quickly become the deciding factor in whether a product is sustainable. This article explains why inference cost matters, how attention computation and KV cache memory create bottlenecks in long-context scenarios, and how hybrid attention structures, cache compression, and deployment-level engineering optimizations—especially on memory- and bandwidth-constrained accelerators—can reduce cost per token. It also provides a practical framework for measuring unit cost and actionable recommendations for production deployment.

    1. Background: Why Inference Cost Is a Core Metric

    Once a large model moves from experimentation to large-scale service, inference cost directly determines whether the product can operate sustainably. Training cost is a one-time investment, while inference cost grows linearly with request volume. The cost of serving the same model can vary dramatically across scenarios, mainly depending on three factors: the number of tokens processed per request, the computational cost per token, and the effective utilization of the hardware.

    Long-context scenarios amplify these problems. Document analysis, code repository understanding, and long multi-turn conversations all require the model to process hundreds of thousands or even millions of tokens. The longer the context, the faster attention computation and memory usage grow, pushing up the cost of each request. Inference optimization therefore typically proceeds along two directions simultaneously: improving the model architecture to reduce the computation and storage overhead of attention, and improving the inference engine and deployment strategy to raise hardware utilization.

    2. The Compute and Memory Bottlenecks of Attention

    Standard self-attention over a sequence of length n requires computing an n × n relevance matrix, with a computational complexity of roughly O(n²·d), where d is the hidden dimension. Doubling the sequence length increases the compute by about four times.

    During autoregressive generation, the model caches the Key and Value of every historical token at each layer—the KV Cache. Its memory footprint can be estimated with the following formula:

    1. def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, batch=1, dtype_bytes=2):
    2. # The factor of 2 accounts for both Key and Value caches
    3. return 2 * layers * kv_heads * head_dim * seq_len * batch * dtype_bytes
    4. # Illustrative calculation with hypothetical parameters, not measured data from any specific model
    5. size = kv_cache_bytes(layers=60, kv_heads=8, head_dim=128, seq_len=1_000_000)
    6. print(f"KV cache for a single 1M-token request is roughly {size / 1e9:.1f} GB (FP16)")

    As the formula shows, the KV cache scales with the number of layers, KV heads, sequence length, and data precision. With long contexts combined with high concurrency, memory quickly becomes the bottleneck limiting throughput. Reducing KV heads, lowering precision, or compressing cache length all directly relieve memory pressure.

    3. Designing Hybrid Attention Architectures

    To address these problems, a common industry approach is to combine different types of attention mechanisms within a single model.

    1. Linear Attention

    Linear attention uses kernel functions to rewrite the Softmax computation into a cumulative form, reducing complexity to O(n·d²). The model only needs to maintain a fixed-size state matrix instead of storing all historical Keys and Values. Its advantage is that compute and memory grow slowly with sequence length; its drawback is weaker capability for precise long-range retrieval.

    2. Sparse Attention

    Sparse attention computes relevance only between selected positions—for example, a local sliding window plus a few global key positions. It retains the form of exact attention while significantly reducing both computation and cache size. The following example generates a causal, window-limited mask:

    1. import numpy as np
    2. def local_causal_mask(seq_len: int, window: int) -> np.ndarray:
    3. """Returns a boolean mask where True means the position participates in attention."""
    4. idx = np.arange(seq_len)
    5. causal = idx[None, :] <= idx[:, None] # Cannot see future tokens
    6. local = (idx[:, None] - idx[None, :]) < window # Only look at the last `window` tokens
    7. return causal & local
    8. mask = local_causal_mask(seq_len=8, window=3)
    9. print(mask.astype(int))

    3. Hybrid Composition

    In practice, the two mechanisms are often alternated across layers or divided by function: some layers handle low-cost propagation of global information, while others handle precise local modeling. The key to combining them lies in the ratio and placement. Too high a proportion of cheap attention hurts retrieval accuracy; too low a proportion fails to reduce cost meaningfully. Typically, different configurations must be compared on long-text evaluation sets to find the balance point between quality and cost.

    4. KV Cache Compression and Reuse

    Beyond changing the attention structure, you can directly reduce the amount of cached data. Common approaches include the following.

    Precision quantization. Quantizing the KV cache from FP16 or BF16 to INT8 or FP8 roughly halves memory usage. Quantization introduces some numerical error, so output quality must be validated on the target task.

    Cache merging and sharing. When multiple index structures or auxiliary pathways in a model need to cache similar intermediate data, they can be merged into shared storage. This reduces both memory footprint and read/write bandwidth pressure. After merging, you must verify that each pathway can still correctly retrieve the data it needs.

    Windowing and eviction policies. For historical tokens beyond the window, you can keep caches only at key positions, or score tokens by importance and evict low-value entries. Such policies require evaluating the impact of information loss on the task and are not suitable for every scenario.

    5. Inference Engineering Optimizations for Accelerator Hardware

    Different hardware platforms vary widely in memory capacity, memory bandwidth, interconnect bandwidth, and operator support. Directly porting an inference solution designed for one type of hardware to another often fails to deliver the expected results. Below are common optimization ideas for platforms with constrained memory capacity and bandwidth.

    1. Quantization and Operator Adaptation

    On bandwidth-constrained platforms, quantizing weights and caches usually yields greater gains than on high-bandwidth platforms, because data movement is often more time-consuming than computation. At the same time, you need to verify the target chip’s support for low-precision operators, and write custom implementations for hot operators when necessary.

    2. Layered Deployment and Pipeline Partitioning

    When a single card cannot hold the full model, you can partition it across multiple cards by layer (pipeline parallelism) or by tensor dimension (tensor parallelism). The partitioning strategy determines the frequency and volume of inter-card communication. The granularity should be chosen based on interconnect bandwidth—when bandwidth is low, reduce the number of cross-card communication rounds.

    3. Trading Compute for Communication

    In some scenarios, recomputing certain intermediate results is cheaper than transferring them from one card to another. This “compute-for-communication” strategy must be measured operator by operator. The benefit only appears when computation time is lower than communication time.

    4. Inference Engine Selection and Scheduling

    The inference engine handles batching, request scheduling, memory management, and operator fusion. Key capabilities to look for:

    • Continuous batching: New requests are inserted as soon as previous ones finish, reducing device idle time.
    • Paged memory management: The KV cache is allocated in blocks, reducing waste from fragmentation.
    • Prefix caching: Caches computed for shared system prompts or document prefixes are reused.
    • Operator fusion: Reduces kernel launch counts and memory reads/writes of intermediate results.

    5. Performance Evaluation Metrics

    When evaluating inference optimizations, compare the following metrics under identical hardware and identical request workloads:

    Metric Meaning What It Reflects
    Time to first token Time from request to the first output token Interactive experience
    Output throughput Tokens generated per unit of time Service capacity
    Memory usage Total footprint of weights and caches Supported concurrency and context length
    Cost per token Hardware time cost divided by effective output tokens Business sustainability

    Reporting a single metric in isolation can be misleading. For example, if throughput improves while time to first token degrades significantly, the user experience may not actually improve.

    6. A Framework for Evaluating Unit Cost

    When selecting or retrofitting a system, teams can estimate per-task cost with the following formula:

    1. def cost_per_task(hourly_cost, tokens_per_sec, input_tokens, output_tokens, concurrency=1):
    2. # Device time occupied by a single task (seconds)
    3. total_tokens = input_tokens + output_tokens
    4. effective_tps = tokens_per_sec * concurrency
    5. seconds = total_tokens / effective_tps
    6. return hourly_cost / 3600 * seconds

    This formula assumes device cost can be amortized evenly over time. A real evaluation must also account for idle time, warm-up overhead, failure rates, and operational staffing. If the service is priced per request, the impact of cache hit rates on effective input token counts also needs to be considered.

    7. Practical Recommendations

    1. First clarify your business’s context-length distribution and concurrency peaks, then decide on the optimization direction.
    2. Validate accuracy loss with your own evaluation sets—do not rely solely on public benchmarks.
    3. Measure the benefit of each optimization independently, so that stacking multiple changes does not make attribution impossible.
    4. Run end-to-end load tests on the target hardware; do not base hardware selection on theoretical compute specifications alone.
    5. Set up continuous monitoring of unit cost, and make cost a review item in version releases.

    Inference cost reduction comes from the combined effect of architecture, caching, quantization, and engineering implementation. Every change must be validated under real workloads before it can translate into stable, reliable gains.