Ultra-Long Context Open-Source LLMs: Architecture and Engineering Practices

    This article examines the architectural and engineering considerations behind open-source LLMs designed for million-token context. It explains why agent workloads create long-context demand, how mixture-of-experts balances parameter scale and compute cost, how attention mechanisms are redesigned for KV cache and positional stability, what makes long-context training difficult, how inference kernels and serving systems are optimized, how to evaluate long-context capability beyond generic QA scores, and how enterprises can adopt these models through a phased deployment approach.

    In recent years, competition among large language models has gradually shifted from single-turn question answering toward the sustained execution of complex tasks. In ordinary conversation, a context window of a few thousand to tens of thousands of tokens is often sufficient. However, when a model is used for code analysis, document retrieval, task planning, tool calls, and long-term memory management, context length can expand rapidly. A new generation of open-source models is beginning to treat million-token context as a baseline capability and is using mixture-of-experts architectures and system-level optimizations to reduce inference cost while maintaining quality.

    1. Why Agents Need Million-Token Contexts

    Traditional chat scenarios often follow a short path of “user asks a question, model answers.” The number of historical messages is limited, and the model only needs to focus on the most recent turns. When an agent executes a task, however, it usually needs to retain the following information over time:

    1. The user’s original goals and constraints;
    2. Multi-turn planning results and intermediate decisions;
    3. Code files, configuration files, and technical documents that have been read;
    4. Tool-call records and their returned results;
    5. Logs, error messages, and standard output produced by executed commands;
    6. The model’s previous reasoning conclusions, assumptions, and to-do items;
    7. Historical information retrieved from a long-term memory system.

    Consider a code agent that runs continuously for dozens of turns. In each turn, it may read multiple source files, run test commands, analyze compilation errors, and generate new modification plans. Even if each turn adds only a few thousand to tens of thousands of tokens, the accumulated total can quickly reach hundreds of thousands of tokens. If the system also retains complete tool logs, patch content, and historical decisions, million-token context is not an extreme case but a natural outcome of complex tasks.

    The value of long context is not merely the ability to “fit more text.” More importantly, it can reduce the information loss caused by frequent summarization, avoid repeated reads of external materials, and keep task state continuous over a longer period. For tasks that require cross-file reasoning, cross-chapter verification, or cross-stage execution, complete context is often more reliable than fragmented retrieval.

    2. Mixture of Experts: Balancing Parameter Scale and Compute Cost

    As model scale continues to grow, activating all parameters for every inference would create very high compute and memory pressure. The core idea of mixture-of-experts is that a model contains many expert networks, but each token is routed to only a small number of experts for computation.

    This can be abstracted as follows:

    1. Input token
    2. ↓
    3. Router computes expert scores
    4. ↓
    5. Select a small number of candidate experts
    6. ↓
    7. Expert networks process separately
    8. ↓
    9. Merge results by routing weights

    This approach provides two direct benefits.

    First, the model can have a larger total parameter count. Different experts can develop relatively different knowledge specializations during training, such as patterns related to code, mathematics, natural language, or tool calling. This does not mean that experts necessarily correspond one-to-one with specific domains; in practice, specialization is usually formed automatically by the training process.

    Second, each inference uses only some of the parameters, so computation does not grow linearly with total parameter count. For serving systems, this helps balance model capability, response speed, and hardware cost.

    However, mixture-of-experts is not simply “reducing computation.” The router itself requires additional computation, and communication may occur between experts. When different tokens are dispatched to different devices, communication latency, load imbalance, and memory usage can all become bottlenecks. A strong system design must therefore optimize routing strategy, expert placement, communication mechanisms, and batching methods together.

    3. The Key to Long Context: Re-architecting Attention

    The computational complexity of standard self-attention usually grows quadratically with sequence length. When context expands from hundreds of thousands of tokens to the million-token level, using a conventional implementation directly creates enormous compute and memory pressure. Long-context models therefore often need to modify attention mechanisms at multiple levels.

    3.1 Reducing KV Cache Size

    During autoregressive generation, the keys and values of historical tokens are usually cached to avoid recomputation. The longer the context, the more memory the KV cache consumes, and it can eventually become the main constraint on inference serving.

    Common optimization directions include:

    • Letting multiple query heads share some key-value heads;
    • Compressing historical caches or storing them in tiers;
    • Using lower-precision representations for distant content;
    • Keeping frequently accessed content in high-speed memory while moving less frequently accessed content to other storage tiers;
    • Evicting content that is determined never to be accessed again.

    The common goal of these methods is to reduce the storage requirement per token for historical state while minimizing impact on model quality.

    3.2 Improving Long-Range Stability of Positional Encoding

    A model needs to know the positional relationships among tokens in a sequence, but positional information learned from short contexts may not generalize naturally to million-token lengths. Direct extrapolation can lead to distorted long-distance relationships, abnormal attention concentration, or reduced utilization of the latter part of a text.

    Long-context training therefore usually needs to combine positional encoding extension, staged training, and long-sequence data mixing. The model must not only “see longer text” but also learn to locate key information in long text, establish cross-paragraph relationships, and distinguish local details from global structure.

    3.3 Chunked or Sparse Attention

    Not every token needs to attend to all historical content. For many tasks, local windows, chunk summaries, and a small number of global anchors can already cover the main information. A system can let the model use dense attention within local regions and use sparser paths for cross-region access.

    This design can reduce无效 computation, but it also introduces new challenges: if the sparsity strategy is too aggressive, the model may miss key evidence. Practical systems therefore need to trade off local precision against global connectivity.

    4. Engineering Challenges of Training with Million-Token Contexts

    Long-context training places higher demands on data, parallelism, and stability.

    First, training samples must be sufficiently long and structurally sound. Simply concatenating large amounts of short text may teach the model only the form of long sequences, not effective cross-segment understanding. High-quality training data should include long-document question answering, cross-chapter information integration, long-codebase analysis, complex log troubleshooting, and multi-step task execution.

    Second, training memory and communication pressure increase significantly. Long sequences amplify the scale of activations, gradients, and caches, so training usually needs to combine data parallelism, tensor parallelism, pipeline parallelism, and sequence parallelism. More parallelism is not always better; excessive partitioning can cause communication costs to exceed the computational benefits.

    Third, training stability becomes more important. Abnormal samples, repeated content, and extreme lengths in long sequences can amplify gradient fluctuations. Engineering practice usually requires length bucketing, dynamic batching, gradient clipping, mixed-precision validation, and abnormal-sample filtering, along with continuous monitoring of loss curves and long-text-specific metrics.

    5. Kernel Optimization During Inference

    After model architecture design is complete, the inference system often determines the actual user experience. In long-context scenarios, simply adding more compute cannot solve all problems; low-level computation kernels also need optimization.

    5.1 Efficient Matrix Computation

    Attention projections, expert networks, and output layers all contain many matrix operations. Efficient kernels need to reduce intermediate tensor reads and writes, improve the continuity of memory access, and fuse multiple operations into a single computation where possible. Operator fusion can reduce both memory access overhead and kernel launch count.

    5.2 Dynamic Batching

    Different requests vary widely in context length and generation speed. Fixed batching can cause short requests to wait for long requests. Dynamic batching can flexibly combine tasks after requests arrive and adjust computation order according to sequence state, thereby improving device utilization.

    5.3 Prefix Caching and Reuse

    Many applications repeatedly use the same system prompt, document prefix, or task rules. Recomputing this content on every request creates substantial redundant overhead. Prefix caching can store intermediate states that have already been computed and reuse them in later requests. However, the cache needs a validity period, capacity limit, and consistency strategy; otherwise, it may cause memory pressure or data isolation problems.

    5.4 Tiered Storage

    Million-token context does not necessarily need to reside entirely in the fastest storage. A tiered structure can be built based on access frequency: recent tokens are kept in high-speed memory, earlier content is placed in main memory, and long-term content is managed through compression or external storage. This can achieve a more practical balance between capacity and speed.

    6. How to Properly Evaluate Long-Context Models

    Generic question-answering scores alone cannot determine whether a model truly has long-context capability. A complete evaluation should cover at least the following aspects:

    • Locating key information in long documents;
    • Synthesizing information scattered across different chapters;
    • Analyzing dependencies in a long codebase;
    • Maintaining state across multi-turn tasks;
    • Recovering from errors after tool calls;
    • Output stability under ultra-long input;
    • Information utilization in both the first and second halves of the context;
    • Latency, throughput, and memory usage at different lengths.

    It is also important to distinguish “can contain” from “can understand.” A model that accepts million-token input does not necessarily use all content evenly. Some models may have weaker information extraction in the middle of the context, or may focus mainly on the beginning and end. Tests should therefore place key information at different positions and include questions that require joint reasoning across regions.

    7. Implementation Recommendations for Enterprises

    For teams planning to deploy long-context models, a phased approach is recommended.

    First, map the sources of context in real business workloads and distinguish user input, tool output, historical messages, and long-term memory to avoid indiscriminate accumulation.

    Second, establish context governance mechanisms. Trim logs, deduplicate repeated content, summarize low-value history, desensitize sensitive data, and retain traceable task state.

    Third, separate “factual materials” from “reasoning processes.” Not all intermediate reasoning needs to be retained permanently. A system can store only conclusions, evidence locations, and unfinished items, reducing the speed at which context expands.

    Fourth, continuously monitor cost and quality. Focus on time to first token, generation speed, peak memory usage, cache hit rate, long-text accuracy, and task completion rate, rather than only observing single-request latency.

    Fifth, where appropriate, combine compute, storage, logging, and monitoring infrastructure from Baidu AI Cloud to build a scalable model serving pipeline. Actual deployment should still be evaluated based on model size, concurrency, data compliance requirements, and business fault tolerance.

    Conclusion

    Million-token context is not a competition over a single parameter. It is the result of co-evolution across model architecture, training data, attention mechanisms, inference kernels, and serving systems. Mixture-of-experts addresses the tension between parameter scale and compute cost, long-context mechanisms expand the range of information a model can process, and caching, chunking, sparse computation, and tiered storage determine whether these capabilities can be deployed in practice.

    For developers, the most important question is not the promotional metric of context length, but whether a model can reliably use long text, maintain state in complex tasks, and run continuously at controllable cost. Only by combining model capability with context governance, agent orchestration, and engineering infrastructure can ultra-long context move from a laboratory metric to reliable production capability.