Million-Token Context in Practice: Four Infrastructure Optimizations for LLM Systems

    Million-token context windows are not useful merely because they can accept long inputs. This article presents a system-level framework for making long context practical—covering attention computation, KV-cache organization, distributed execution, and serving scheduling—and explains how to evaluate capacity, effective utilization, and cost under real workloads.

    Million-Token Context in Practice: Four Infrastructure Optimizations for LLM Systems

    From processing a single conversation to analyzing an entire set of business documents, cross-file code, and continuously accumulated task records, large models are increasingly facing much longer inputs. Million-token context windows open up space for these applications, but “able to receive” does not mean “able to process efficiently,” and it certainly does not mean the model can accurately use every piece of information in the input.

    True long-context capability must answer four questions at the same time: Is attention computation affordable? Can historical state fit into GPU memory? Does communication across devices become a bottleneck? And can the serving system maintain stable latency at a reasonable cost?

    Therefore, discussing long-context technology should not focus only on model size or window length. It should turn to system-level coupled optimization. The following sections explain the key conditions for million-token context to become engineering-practical across four main lines: attention mechanisms, cache organization, distributed execution, and service scheduling. The “four optimizations” here are a general technical analysis framework and do not represent implementation approaches already adopted by any specific model.

    1. First Distinguish Three Concepts: Window Capacity, Effective Utilization, and Serving Performance

    Long context is first a capacity concept: it indicates how long a token sequence the model can hold in a single processing pass. A token here is the basic unit the model uses to process text, and there is no fixed conversion relationship between tokens and the number of Chinese characters, words, or file bytes.

    Beyond capacity, however, there are two equally important dimensions.

    The first is effective utilization. Can the model find dispersed evidence in a long document, correctly understand ordering relationships, and make judgments among multiple conflicting passages? If a key condition is located in the middle of the input, can the model still follow it reliably? These capabilities cannot be inferred only from the window limit.

    The second is serving performance. After a user uploads a very long document, how long must they wait before seeing the first output? Once generation begins, is the output speed stable? When multiple users submit long requests at the same time, will the system frequently queue requests or run out of GPU memory?

    A complete long-context evaluation should therefore include at least three conclusions: how much it can hold, how well it can use what it holds, and how expensive it is to use. Highlighting only one of these can easily lead to misjudgment.

    2. First Optimization: Re-examine Attention Mechanisms and Computation Paths

    2.1 Why Long Sequences Amplify Computational Pressure

    Standard dense self-attention needs to establish relationships among tokens. Let the input length be N. When other conditions are similar, the computation in the attention part usually grows roughly with the square of N.

    This means that expanding the context length to ten times the original does not merely increase attention-related computation by ten times. In a naive implementation, the intermediate attention matrix also creates significant memory pressure.

    Methods such as chunked computation and operator fusion can reduce the storage and movement of intermediate results, but this does not mean the computational complexity of global dense attention has become linear. Engineering optimization and algorithmic complexity must be discussed separately.

    2.2 What Multi-Query Attention and Multi-head Latent Attention Solve

    Multi-query attention lets multiple query heads share keys and values. Compared with storing key-value state separately for each attention head, it can reduce the key-value cache that must be stored and read during inference.

    The main value of this design is to lower cache capacity and memory-bandwidth requirements. However, as the degree of sharing increases, the model’s expressive behavior also changes. Its final effect must be validated through training and evaluation and cannot simply be understood as “the more sharing, the better.”

    Multi-head latent attention takes another approach: it compresses key-value-related information into a lower-dimensional latent representation, which participates in attention computation through corresponding mappings. It also aims to reduce cache burden, but its benefits are closely related to compression dimensions, positional encoding handling, computational fusion methods, and hardware execution efficiency.

    Neither approach has an absolute advantage independent of implementation conditions. Practical selection needs to examine:

    • How much historical state must be stored per token;
    • How much data must be read to generate each token;
    • How much additional computation the compression or mapping process introduces;
    • Whether existing hardware can execute the relevant operators efficiently;
    • Whether sufficient quality is maintained on the target task.

    A smaller cache does not necessarily mean lower end-to-end latency; less theoretical computation does not necessarily mean higher device utilization.

    2.3 Sparsification Must Be Evaluated Together with Information Fidelity

    In addition to changing how key-value state is represented, it is also possible to reduce the positions each token needs to attend to—for example, attending only to a local neighborhood, retaining a small number of global positions, or selecting relevant segments based on content.

    Such methods may reduce the computational cost of long sequences, but they introduce new questions: Do the skipped positions happen to contain key evidence? Can cross-chapter dependencies be preserved? Can multiple conditions that are far apart be correctly combined?

    Therefore, attention sparsification should not look only at speed improvements. It should also check the quality loss caused by incorrect information selection. For tasks such as contract review and complex code analysis, missing a single constraint may be harder to accept than answering slightly more slowly.

    3. Second Optimization: Turn the KV Cache into a Manageable System Resource

    3.1 Estimate the Cache First, Then Discuss Concurrency

    Autoregressive generation usually needs to store the keys and values corresponding to historical tokens to avoid recomputing all historical state at every step.

    For attention structures using a conventional KV-cache layout, the following approximate relationship can be used to estimate cache capacity:

    KV cache bytes ≈ 2 × layers × cached tokens × KV heads × head dimension × bytes per element

    Here, the coefficient 2 corresponds to the key and value parts. This formula is suitable for understanding capacity trends and should not be directly applied to all latent-compression attention structures; different implementations may also add position-related state, block tables, and alignment overhead.

    More importantly, the cache is not the only thing in GPU memory. Actual capacity planning also needs to deduct model weights, temporary workspaces, communication buffers, and runtime reserved space. The concurrency limit for long requests is often determined by these resources together.

    3.2 Block Management Reduces Fragmentation but Cannot Eliminate Real Occupancy

    Different requests vary greatly in input length and output length. If a large contiguous block of space is reserved for each request, external fragmentation easily occurs, and GPU memory is easily wasted when output length estimates are inaccurate.

    Dividing the cache into fixed-size blocks, allocating them on demand, and organizing them through mapping relationships can improve space utilization and make reclamation after a request ends easier.

    However, block management optimizes the allocation method; it does not make real historical state disappear. Block size also involves trade-offs: if blocks are too large, tail waste increases; if blocks are too small, management and addressing overhead may rise.

    3.3 Cache Quantization and Tiered Storage Each Have Boundaries

    Reducing the numerical precision of the cache can lower capacity and bandwidth requirements, but its impact on long-distance dependencies, numerical reasoning, and complex constraint tasks must be validated. Some errors may not be obvious with short inputs but may gradually emerge over long sequences and multi-step generation.

    Placing part of the cache in host memory or other larger-capacity storage tiers can also relieve GPU memory pressure. However, if the generation process frequently needs to read this state, data movement may become a new bottleneck.

    Therefore, tiered storage is better designed in combination with access frequency, scheduling policies, and bandwidth conditions, rather than simply moving overflowing cache to slower media.

    4. Third Optimization: Make Distributed Computing Benefits Cover Communication Costs

    When model weights and long-sequence state are difficult to fit into a single device, distributed execution becomes a necessary choice. But adding more devices does not guarantee proportional speed improvements.

    Model parameters can be partitioned across multiple devices, network layers can be deployed by stage, and long sequences can also be split along the sequence dimension. Different approaches change the distribution of computation, GPU memory, and communication in different ways.

    Long-context scenarios especially need to focus on cross-device data exchange. Although some partitioning methods reduce per-device GPU memory usage, they require continuous transfer of attention-related data between devices. When communication cannot be effectively hidden by computation, the benefit of additional devices drops significantly.

    Therefore, distributed approaches need to be designed in combination with the actual machine topology, rather than looking only at the total number of devices. Connection bandwidth between devices, communication latency, and differences between interconnect levels all affect the best partitioning method.

    It is also necessary to distinguish the two stages of inference:

    • Prefill stage: processes the input and establishes historical state; long inputs usually bring a large computational load;
    • Token-by-token generation stage: repeatedly reads historical state and produces new output, often affected by memory access, communication, and small-batch execution efficiency.

    Deploying the two stages separately creates an opportunity for each to use more suitable resources and scheduling policies, but it also increases cache transfer, routing, and failure recovery costs. Splitting is valuable only when these costs are smaller than the benefits from improved resource utilization.

    5. Fourth Optimization: Move from “the Model Can Run” to “the Service Can Be Delivered”

    5.1 Long and Short Requests Should Not Queue Indiscriminately

    A very long input request may occupy compute resources for a long time and affect the response speed of many short requests. Conversely, if short requests are always prioritized, long tasks may continue waiting.

    Feasible scheduling ideas include grouping by input length, setting separate queues for different tasks, and splitting prefill for very long inputs into smaller batches. The goal is not simply to pursue maximum throughput, but to establish a controllable balance among throughput, time to first token, and request fairness.

    5.2 Prefix Reuse Must Guarantee Correctness and Isolation

    Enterprise tasks often repeatedly use the same system instructions, document background, or project materials. For prefixes that are exactly identical and computationally compatible, reusing established state creates an opportunity to reduce repeated prefill cost.

    The emphasis here must be on “exactly identical.” Similar content semantics do not mean caches can be directly interchanged. Changes in model version, positional handling, and related computational configurations may also invalidate existing caches.

    In addition, cross-user reuse cannot bypass permission control. Cache hits should not become a channel for information leakage; their lifecycle, tenant isolation, and access boundaries all need explicit design.

    5.3 Cost Should Be Accounted per Successful Task

    The unit price per input token reflects only part of the cost. A complete task may also include document parsing, retrieval, repeated attempts, long outputs, and human review.

    A more meaningful metric is “total cost per successful task.” For example, if a low-price solution frequently misses key conditions and causes multiple retries, its final cost may be higher than that of a solution that completes the task with better quality in one pass.

    Similarly, discounts or resource savings from cache hits cannot simply be extrapolated as cost reductions for all tasks. Real benefits depend on the proportion of repeated prefixes, cache retention time, request distribution, and system utilization.

    6. Enterprise Practice: Not Every Task Should Fill the Context

    Million-token context is better suited to tasks that require extensive cross-reading, such as cross-chapter rule checking, multi-file dependency analysis, and complex reviews that need to retain a large amount of original evidence.

    However, for questions that only require a local fact, retrieving first and then inputting the relevant segment is usually easier for controlling cost and evidence scope.

    A practical system can adopt a layered strategy:

    The first layer uses permission filtering and retrieval to narrow the candidate range.

    The second layer retains original passages relevant to the question and adds necessary metadata such as section, time, and version.

    The third layer expands the input range or enables longer context only when the question truly depends on global relationships.

    The fourth layer requires outputs to include verifiable evidence and applies rule checks or human review to key conclusions.

    Note that summaries are not lossless compression. If later questions may depend on details, do not store only the summary and discard the original text. Retrieval results should also retain source locations so the model does not generate plausible explanations that cannot be traced.

    7. Build an Evaluation System That Exposes Problems

    Long-context evaluation should not test only “find one sentence in a long document.” Such tasks reflect some localization ability, but they are insufficient to prove complex reasoning ability.

    At minimum, the following dimensions should be covered:

    1. Position sensitivity: Place the same evidence at the beginning, middle, and end, and observe whether results remain stable.

    2. Multi-evidence combination: Make the answer depend on multiple distant segments and test whether the model truly completes integration.

    3. Conflict handling: Add materials from different times and versions, and check whether the model can choose according to specified rules.

    4. Distraction robustness: Add a large amount of topically similar but irrelevant content and observe changes in accuracy.

    5. Instruction safety: Embed text in external documents that attempts to change the task objective, and verify whether the system still follows trusted instructions and permission boundaries.

    6. Serving stability: Under different input lengths and concurrency levels, record time to first token, output speed, tail latency, GPU memory usage, and failure rate.

    7. Economics: Record both cache-hit and cache-miss scenarios, and calculate actual cost by task success rate.

    All performance results should include test conditions, including input length, output length, concurrency, hardware resources, and cache state. Without these conditions, a single speed or throughput number is difficult to use for engineering decisions.

    8. Conclusion: The Value of Long Context Depends on Whether the System Forms a Closed Loop

    Million-token context is not the victory of a single attention mechanism, nor is it a capability automatically obtained by expanding GPU memory or adding devices. It requires model structure, cache layout, communication paths, and service scheduling to adapt to one another.

    The key to judging whether a solution is mature is not how large the window limit is, but whether it can simultaneously deliver stable quality, acceptable response time, and predictable cost under real workloads.

    For developers, the most pragmatic path is to first clarify what information a task needs to retain, then estimate resources, establish benchmarks, and optimize step by step. Only by turning “containing information” into “reliably using information” can long context truly move from a capability on a specification sheet to a sustainable business system.