Analyzing and Optimizing Million-Token LLM Inference: A Technical Breakdown

    This article examines the engineering architecture behind efficient million-token large language model inference. It covers dual-path hybrid attention, manifold-constrained hyper-connections, FP4/FP8 mixed precision, staged training scheduling, post-training distillation, and deployment infrastructure, offering developers a systematic framework to reduce long-context costs.

    1. Background: Why Million-Token Contexts Drive Up Inference Costs

    When the context window expands from tens of thousands of tokens to the million-token range, inference overhead does not grow linearly—it approaches quadratic growth. Standard attention requires every new token to compute relevance against all historical tokens, so doubling the sequence length often multiplies the computation several times over. At the same time, the key-value cache (KV cache) expands linearly with the sequence, memory quickly becomes the bottleneck, throughput drops, time-to-first-token rises, and the cost per request is rapidly amplified.

    The industry generally relies on three approaches: sparsification, where each token attends only to the most relevant fraction of history; compression, where the historical sequence is shortened by a ratio before computation; and hybridization, which combines different mechanisms to complement one another. A preview release of an open-source large model series in April 2026 follows the third route and provides a worthwhile engineering case study.

    2. Dual-Path Hybrid Attention: Dividing Precise Retrieval and Global Coverage

    The most core architectural change in this version splits attention into two parallel paths that share the same compression mechanism but use different compression ratios.

    • Precise retrieval path: A moderate compression ratio (around 4x) retains relatively complete sequence information after compression. Sparse selection then picks the most relevant segments for fine-grained computation, making it good at locating specific details.
    • Global coverage path: An aggressive compression ratio (around 128x) reduces a million-token input to a few thousand tokens. At this scale, dense attention can be applied directly without relying on a selector, avoiding the risk of missing key information that was not selected.

    The two paths are interleaved and stacked within Transformer layers. In the flagship model, there are 61 layers: the first two use the global coverage path to establish a global view, and the remaining layers alternate between both paths. The lightweight model has 43 layers: the first two use sliding-window attention, and the remaining layers also alternate. The logic is clear: aggressive compression shrinks the sequence to a scale that dense computation can handle, while moderate compression combined with sparse selection preserves retrieval precision. The two complement rather than replace each other.

    It is worth noting that the previous version already introduced sparse attention with two-stage indexing plus top-k selection, reducing complexity from quadratic to linear multiplied by k. However, at the million-token scale, two shortcomings remain: the selector’s own overhead grows with length, and selection is probabilistic, potentially missing key segments. The dual-path structure is a patch targeting these two shortcomings.

    3. Manifold-Constrained Hyper-Connections: Stabilizing Deep Networks

    When stacking many layers, the numerical scale of inter-layer connections can easily get out of control, and drift in gradients and activation distributions slows convergence. Manifold-constrained hyper-connections expand the form of inter-layer connections while imposing manifold constraints on connection weights, restricting parameter updates to a reasonable geometric range. This improves training stability and representational capacity in ultra-deep networks. The practical engineering benefit is that, under the same compute budget, you can achieve a more stable convergence curve with fewer adjustment rounds.

    4. FP4 and FP8 Mixed Precision: Relieving Memory and Bandwidth Pressure

    Low precision is a must for long-context inference. A common strategy is to tier by tensor sensitivity: keep FP8 for parts with sensitive numerical distributions and large dynamic ranges, use FP4 for parts with concentrated weight distributions and controllable quantization error, and apply per-block scaling factors to control error accumulation. The benefits appear in two places: reduced memory footprint for weights and reduced memory access volume. Throughput improvements are especially pronounced for memory-bound workloads during the decoding stage.

    The following is an illustrative quantization configuration logic (pseudocode, expressing only the tiering idea):

    1. # Select precision by layer sensitivity; keep higher precision for sensitive layers
    2. def pick_dtype(layer):
    3. if layer.attn_indexer or layer.norm:
    4. return "fp8" # Large dynamic range, keep FP8
    5. return "fp4" # Concentrated weights, FP4 is fine
    6. # Block scaling to suppress error accumulation
    7. block_scale = per_block_amax(tensor, block_size=128)
    8. q = quantize(tensor, dtype=pick_dtype(layer), scale=block_scale)

    5. Training Scheduling and Long-Context Expansion

    Long-context capability is not obtained by simply enlarging the window. It requires staged, curriculum-style expansion: first complete the main training on shorter sequences, then gradually lengthen the window, adjusting parallel partitioning strategies (combinations of tensor parallelism, pipeline parallelism, and expert parallelism) and recomputation granularity to control peak activation memory. On the data side, long-range dependency samples must be constructed to prevent the model from only learning to “look at the beginning and the end.”

    6. Post-Training: Online Policy Distillation and Verifiable Rewards

    The post-training stage introduces online policy distillation: the teacher model provides distribution-level supervision on the student’s current sampling distribution in real time, which fits the student’s actual state better than offline fixed labels and converges faster. For rewards, a generative reward model combined with scoring rubrics constrains the scoring dimensions, turning “how good” into verifiable multi-dimensional items and reducing reward drift and score gaming.

    7. Deployment and Infrastructure Essentials

    Deployment requires a full supporting stack: a security sandbox to isolate code execution, write-ahead logging for fault recovery, domain-specific intermediate representations to bridge heterogeneous compute, expert-parallel communication optimization, a compilation stack for low-precision operators, and tiered KV cache (cold data offloaded to object storage or higher-tier storage, hot data resident in memory). On Baidu AI Cloud, this type of architecture is typically supported by container platforms for elastic scaling, object storage for cache offloading, and monitoring, alerting, and logging services to observe tail latency, forming a complete engineering loop.

    8. Conclusion and Recommendations

    The efficiency profile of this version is highly informative: in million-token context scenarios, per-token inference compute is about 27% of the previous generation, and KV cache is about 10%. The takeaway for developers is that reducing long-context costs is not a single-point trick but a systems engineering effort combining “attention structure + low precision + training scheduling + post-training + infrastructure.” It is recommended to first validate capabilities with the lightweight model, then decide whether to upgrade to the flagship model based on load-testing results, and to use cache hit rate, time-to-first-token, and cost per token as core observation metrics.