Reducing LLM Inference Costs: A Practical Guide from Attention to Domestic Compute

    This article explains how to evaluate and reduce the inference cost of large language models (LLMs). It introduces a task-level cost metric that accounts for retries and success rates, then examines the computational and memory bottlenecks of standard self-attention, particularly the KV cache in long-context scenarios. A formula and code example are provided for estimating KV cache memory, offering a foundation for cost-optimized inference design.

    Bottlenecks and How to Measure Cost

    Inference cost is driven by three main factors: computation volume, GPU memory usage, and data movement. Longer input sequences, higher concurrency, and larger models amplify all three.

    Comparing the price per token across different solutions is not enough. A low per-token price may still lead to higher total cost if it requires repeated attempts or produces overly verbose outputs. Instead, use the unit task cost—the total cost of completing one valid task:

    Unit task cost = (average cost per call × average number of calls per task) ÷ task success rate

    Where:

    • Average cost per call = (input tokens × input price) + (output tokens × output price) + fixed call fee
    • Average number of calls per task includes the first call and all retries
    • Task success rate is the proportion of task flows that yield a usable result

    The following hypothetical numbers illustrate the principle (not real pricing):

    Plan A: 3,000 input tokens and 600 output tokens per call. Input price ¥2 per million tokens, output price ¥8 per million tokens. Average 1.2 calls per task, success rate 85%.
    Single-call cost = 3,000 × 2 ÷ 10⁶ + 600 × 8 ÷ 10⁶ = ¥0.0108
    Unit task cost = 0.0108 × 1.2 ÷ 0.85 ≈ ¥0.0152

    Plan B: Input price ¥1 per million tokens, output price ¥4 per million tokens—obviously lower unit prices. But it averages 2.0 calls per task with only 60% success.
    Single-call cost = ¥0.0054
    Unit task cost = 0.0054 × 2.0 ÷ 0.60 = ¥0.0180

    Plan B has lower per-token prices but a higher unit task cost. When evaluating any solution, record these four indicators together: unit price, token consumption, task success rate, and retry rate.

    Attention and KV Cache Compression

    This section focuses on standard Transformer self-attention, not implementation-level optimizations like FlashAttention. In standard self-attention, computation grows quadratically with sequence length. For example, increasing sequence length from 4K to 128K (32× longer) causes the attention computation to grow by roughly 1,024×.

    Inference proceeds in two phases:

    • Prefill phase: processes the entire input in one pass, compute-intensive.
    • Decode phase: generates tokens one by one; each step reads the full history of KV cache, memory-bandwidth-intensive.

    These phases have different bottlenecks and require separate optimization strategies.

    In long-context scenarios, the KV cache becomes the dominant GPU memory consumer. Its size can be estimated with:

    KV cache bytes = 2 × layers × KV heads × head dimension × sequence length × bytes per element

    The factor 2 accounts for separate K and V caches. As an example (not tied to any specific model), consider 60 layers, 8 KV heads, head dimension 128, sequence length 1,000,000 tokens, and 2 bytes per element (FP16/BF16). With decimal units (1 GB = 10⁹ bytes), one request’s KV cache is about 246 GB. In binary units (GiB), it is about 229 GiB. Do not mix the two.

    1. def kv_cache_bytes(layers, kv_heads, head_dim, seq_len, dtype_bytes=2):
    2. assert min(layers, kv_heads, head_dim, seq_len, dtype_bytes) > 0
    3. # Factor 2 accounts for K and V caches
    4. return 2 * layers * kv_heads * head_dim * seq_len * dtype_bytes
    5. size = kv_cache_bytes(layers=60, kv_heads=8, head_dim=128, seq_len=1_000_000)
    6. print(f"{size / 1e9:.1f} GB") # Outputs 245.8 GB

    This estimate is a lower bound. It does not include model weights, activations, framework reserved space, or memory fragmentation. End-to-end latency is also affected by the feed-forward network