Long-Context LLM Inference Optimization: Segmented Computation and Cache Sharing Explained

    This article explains why inference cost for long-context language models depends on computation, cache capacity, and the data read for each generated token, not just output length. It covers how segmented computation, cross-layer cache sharing, low-precision storage, and candidate reuse affect speed and memory use, and what developers should measure to judge real gains.

    1. The Real Bottleneck May Be Reading, Not Generation

    In agentic coding, document analysis, and multi-turn tool calling, the workload of a model is usually asymmetric. The input may contain large amounts of source code, test logs, retrieved passages, and tool outputs, while the output is often only a short revision suggestion or a next action.

    As a task runs in steps, new information keeps entering the context. The system must process the new input while retaining earlier information so that later generation can build on existing conclusions. Inference cost therefore cannot be understood only by how many words are generated. Three questions also matter:

    • How many layers of computation does the new input pass through?
    • How much cache does the historical context occupy?
    • How much historical data must be read for each new token generated?

    These three questions relate to input computation, cache capacity, and data access cost during generation. They affect one another, but they are not the same metric.

    The key to understanding long-context optimization is to analyze the computation path and the storage path separately. Seeing that less input is computed should not lead to the conclusion that the cache shrinks by the same proportion.

    2. Why the Cache Grows With Context

    1. Attention reads conditionally from history

    A language model first converts text into tokens. A token can be a character, a fragment of a word, punctuation, or a code symbol.

    In a common attention structure, the current position produces a query vector Q, while historical positions provide key vectors K and value vectors V. How well the query matches each key determines which historical positions the model reads from. The value vectors carry the content that is read.

    For a simplified attention head, this can be written as:

    o = softmax(qKᵀ / √dₖ)V

    Here, q is the current query, K and V are the keys and values of the visible historical positions, and dₖ is the key dimension. Real networks usually include multiple attention heads, position processing, normalization, and other components. Still, this expression is enough to show what the cache is for.

    2. The cache avoids recomputing history

    In causal autoregressive generation, historical positions never see future tokens. The keys and values they have already computed can usually be reused. The system stores these intermediate results as a key-value cache, or KV cache.

    Without a cache, each new token may require recomputing a large number of historical representations. With a cache, the model mainly computes the state of the current position and reads the existing historical data.

    The cache reduces repeated computation but adds storage that keeps growing. For a conventional structure that stores keys and values separately for each layer, the capacity can be roughly expressed as:

    M ≈ B × L × T × Hₖᵥ × (dₖ + dᵥ) × s

    where:

    • B is the number of sequences maintained at the same time;
    • L is the number of layers that need their own cache;
    • T is the cached length of each sequence;
    • Hₖᵥ is the number of key-value heads;
    • dₖ and dᵥ are the key and value dimensions;
    • s is the number of bytes per element.

    This formula shows how the cache size grows. It does not apply to every cache structure. Compression, cross-layer sharing, local windows, and quantization metadata all change the actual footprint.

    Still, the formula shows a basic point: cache optimization is not limited to reducing sequence length. It can also reduce the number of independent cache copies, lower the representation dimension, or lower storage precision.

    3. Segmented Computation: Reducing Input Cost Without Simply Skipping Layers

    1. Treat context processing and token-by-token generation differently

    Ordinary inference usually has two stages.

    The first is prefill, which processes the input context and builds the state needed for later generation. The second is decoding, which generates new tokens one at a time and keeps updating the cache.

    For tasks with long inputs and short outputs, prefill may take up a large share of the time. Some architectures therefore divide the network into parts with different roles. The front part builds context representations, and the back part uses those representations to complete generation.

    Encoding here does not have to mean bidirectional reading. A context-processing part that uses causal constraints can still access only the current position and earlier positions. This supports appending input and continuous generation.

    If an architecture is designed so that some generation layers can directly use the context representations built by the front part, a long input may not need the same amount of processing in every layer.

    2. This is an architectural design, not a general runtime switch

    A normal model cannot be made equivalent by simply cutting off some layers.

    The representations, reading methods, and training objectives of different layers are usually linked. Whether later layers can use earlier states must be established through structural design and training. Otherwise, skipping layers may reduce context understanding, miss code constraints, or even harm generation stability.

    When evaluating such a solution, focus on:

    • which layers produce the context representations;
    • how later layers read those representations;
    • which states must be updated when new input is appended;
    • which computations run when a new token is generated;
    • whether the training process covers the corresponding data flow.

    3. Halving input computation does not double end-to-end speed

    Even if a design mainly routes the input through a shorter computation path, the final gain is still limited by other parts of the system. These include attention operations, data movement, cache maintenance, task scheduling, and generation computation.

    The time for one request can be understood as:

    Total time = input processing time + generation time + other system overhead

    Segmented computation mainly affects one of these terms. When the output is long, or when the main bottleneck is cache reading, the overall benefit of a shorter input path is limited.

    4. Cross-Layer Sharing: Why a Lighter Sequence Compression Can Still Yield a Smaller Cache

    1. Cache size depends on several multiplicative factors

    Sequence compression determines how many historical records are kept along the time axis. Cross-layer sharing determines how many copies of the same historical information must be stored.

    In traditional structures, each layer usually forms its own key-value representations, so each one needs its own cache. If a model is designed so that several layers read the same set of historical keys and values, the number of independent cache copies can be reduced.

    This does not require the queries of those layers to be the same. Different layers can still produce different queries and extract different content from the same historical representations.

    To judge whether a cache is smaller, do not compare only how many historical positions remain after compression. Also compare:

    • the number of independent cache groups;
    • the number of records in each group;
    • the dimension of each record;
    • the bytes used per element;
    • extra indexes, local caches, and management metadata.

    2. A one-quarter result can come from combining different dimensions

    The following is a purely theoretical example and does not represent any actual product configuration.

    Suppose a design reduces the number of independent cache copies to one half of the original, and also reduces the storage bytes per element to one half. If the number of records and the representation dimension stay the same, and extra metadata is ignored for now:

    New cache capacity / original cache capacity ≈ 1/2 × 1/2 = 1/4

    This explains why a design that compresses less along the sequence direction may still produce a smaller cache. It saves more space by reducing copies across layers and