Architecture Design and Engineering Practices for Ultra-Large Open-Source Models

    Understanding architectural trade-offs is more valuable than relying solely on benchmark scores when deploying ultra-large open-source models. This article breaks down the engineering essentials across standard and linear attention, residual connections, Mixture of Experts (MoE), deployment resource estimation, long-context management, and evaluation strategies to help developers make informed decisions.

    1. Look at the Architecture Before the Leaderboard

    Benchmark scores can tell us how a model performs on certain test sets, but they rarely explain why it achieves those results or predict how it will behave in your specific business context. For developers, understanding architectural trade-offs is far more practical. Knowing what problem a design solves and what costs it incurs allows you to determine if it fits your hardware, latency requirements, and data characteristics.

    The following sections cover six areas: attention, residual connections, expert routing, deployment resources, context management, and model selection/evaluation. The numbers used here are illustrative examples to explain calculation methods and do not represent the actual specifications of any specific model. When referencing specific model parameters, always consult the official technical reports or model cards.

    2. The Bottleneck of Standard Attention

    The full attention mechanism in standard Transformers calculates the correlation between every pair of positions, resulting in an n × n score matrix. The computational complexity grows quadratically with the sequence length n. Implementations like FlashAttention reduce memory read/write overhead but do not eliminate the quadratic growth in computation.

    During inference, another issue arises: the KV Cache. It stores historical Keys and Values for every generated token. The VRAM consumption can be estimated using the following formula:

    KV Cache Bytes = 2 × Num Layers × Num KV Heads × Head Dim × Context Length × Bytes per Element × Concurrent Requests

    Consider a model with 60 layers, 8 KV heads, a head dimension of 128, using BF16. For a single request with 1 million tokens, the KV Cache alone requires approximately 2 × 60 × 8 × 128 × 1,000,000 × 2 bytes, which is about 245 GB. This does not even account for model weights and activations. As the context length grows, this overhead becomes impossible to ignore.

    3. Linear Attention and Hybrid Structures

    The idea behind linear attention is to change the order of computation. It first applies a feature mapping function φ to the Query and Key, then aggregates the Key and Value into a fixed-size state matrix, and finally multiplies the Query with this state. As a result, the computation scales linearly with the sequence length.

    1. # Standard attention: computes n×n score matrix, computation scales with n²
    2. attn = softmax(Q @ K.T) @ V
    3. # Linear attention (non-causal illustration): aggregates K and V first, computation scales linearly with n
    4. attn = phi(Q) @ (phi(K).T @ V)

    The formulas here are simplified to illustrate the change in order. The causal version used in language models requires maintaining a state that updates recursively with each token and handling masks.

    Pure linear attention usually falls short of standard attention in precise retrieval tasks. For example, in “needle in a haystack” scenarios where the model must retrieve a specific detail from a long text, compressing all history into a fixed state loses information. Therefore, many new designs adopt hybrid structures: a few layers retain standard attention to ensure precise retrieval, while most layers use linear or gated linear attention to control costs. In gated linear attention, methods like the DeltaNet series perform selective forgetting and correction when updating the state, thereby improving the utilization of historical information.

    The trade-off in this structure is clear. More full-attention layers mean more stable retrieval capabilities but higher costs. More linear layers mean lower costs but a higher risk of missing long-range precise recalls. When selecting a model, you should conduct specific tests targeting the retrieval needs of your task rather than just looking at average scores.

    4. Residual Connections and Deep Information Passing

    As networks get deeper, information from early layers is gradually diluted during layer-by-layer transmission. Residual connections are the basic means to mitigate this issue. Some designs further allow later layers to directly access the attention output of early layers, essentially enhancing feature reuse. This concept is similar to the dense connections found in DenseNet.

    Such designs typically bring three impacts:

    1. Smoother Gradient Propagation: Signals return to shallow layers through shorter paths, making the training of deep models more stable.
    2. Better Retention of Distant Information: Key information from early positions maintains a clearer pathway even after multiple layers of processing.
    3. More Efficient Parameter Utilization: The same number of parameters can be used more effectively, though the actual benefit depends on the specific implementation.

    Whether it is truly effective needs to be verified through ablation studies. In your own training or fine-tuning pipeline, compare versions with and without the extra connections to observe differences in loss curves and downstream task metrics.

    5. Sparse Experts (MoE): More Parameters, Less Computation

    Mixture of Experts (MoE) models split the feed-forward network into multiple experts, with each token passing through only a small subset. A router scores the experts based on the input, selects the top k highest-scoring experts, and performs a weighted sum based on normalized weights.

    1. # Simplified MoE routing, omitting training details like load balancing loss
    2. def moe_forward(x, experts, router, top_k):
    3. scores = softmax(router(x)) # Routing scores for each expert
    4. indices = topk(scores, k=top_k) # Select Top-K experts
    5. weights = scores[indices] / scores[indices].sum()
    6. return sum(w * experts[i](x) for i, w in zip(indices, weights))

    There is a common point of confusion here. Suppose a model has a total of 1 trillion parameters but only activates about 30 billion per token. The computation for a single token is then close to that of a 30-billion-parameter dense model. However, the model’s knowledge capacity is determined by the total parameters.

    MoE also comes with clear costs. First, all expert weights must reside in VRAM or RAM, so it does not reduce the memory footprint of the weights. Second, expert loads can easily become unbalanced—some experts overloaded, others idle—usually requiring auxiliary loss functions to constrain the routing distribution. Third, during distributed deployment, tokens need to be routed across devices, generating All-to-All communication overhead; expert parallelism and pipeline scheduling must be coordinated properly. Fourth, as the number of experts increases, early-stage training routing may oscillate, requiring progressive training strategies.

    6. Deployment Resource Estimation

    Hardware requirements should be estimated before deployment. The table below calculates only the model weights and does not include the KV Cache, activations, communication buffers, or framework overhead. The actual VRAM required will be higher.

    Total Params Precision Weights Only Min GPUs (80 GB VRAM)
    1T (1 Trillion) BF16 ~2 TB At least 25
    1T (1 Trillion) FP8 / INT8 ~1 TB At least 13
    1T (1 Trillion) INT4 ~0.5 TB At least 7
    200B (200 Billion) INT4 ~100 GB At least 2

    The calculation method is: total parameters multiplied by the number of bytes per parameter (BF16 is 2, FP8 or INT8 is 1, INT4 is 0.5). The number of GPUs is the total weight size divided by the VRAM of a single GPU, rounded up. Actual deployment also needs to reserve headroom for KV Cache and communication, generally planned at 1.2 to 1.5 times the theoretical value.

    Teams with limited resources can prioritize evaluating distilled versions or smaller-scale variants of the same architecture released by the community. Elastic compute on cloud platforms is suitable for on-demand deployment and stress testing, reducing long-term idle hardware costs. For large model weights, storing them sharded in object storage combined with version management helps accelerate deployment and rollback. Inference services should also monitor time-to-first-token latency, tokens generated per second, and VRAM usage, with alerting thresholds set accordingly.

    7. Correct Usage of Long Context

    A window that can accommodate 1 million tokens does not mean you should cram everything in every time. Longer inputs often lead to weaker utilization of information in the middle of the text, while computation costs and latency rise. In practice, you can follow these guidelines:

    • Place key instructions at the beginning or end of the input to avoid burying important constraints in the middle.
    • Perform hierarchical summarization on ultra-long materials first, then inject original paragraphs as needed based on the question.
    • Combine Retrieval-Augmented Generation (RAG) with long context, choosing between direct input or retrieval-then-input based on the task type.
    • For multimodal inputs, pay attention to the conversion ratio between image resolution and tokens. High-resolution images may consume a large number of tokens, requiring a trade-off between quality and cost rather than assuming input is limitless.

    8. Context Management in Agent Scenarios

    In software engineering tasks, agents continuously accumulate dialogue, file contents, tool call results, and intermediate artifacts. Without management, the context will quickly be filled with logs and old outputs. The following strategies can be adopted:

    1. Sliding Window for Recent Dialogue: Fully retain the most recent interactions to ensure the model grasps current details.
    2. Rolling Summarization for History: At certain intervals, compress earlier content into a few summary paragraphs.
    3. Key Entity Table: Separately record file paths, API signatures, decisions made, and known errors, and include this table in every request.
    4. Tool Output Truncation and External Storage: For long outputs, retain only the summary and key lines, store the full results in external storage, and provide them to the model in the form of reference IDs.

    Here is a simplified example of a context structure:

    1. [System Prompt] Role, constraints, output format
    2. [Key Entity Table] File: src/api/user.py (modified)
    3. Decision: Use Pydantic v2 to validate request body
    4. Error: KeyError on line 42, identified as missing default value
    5. [History Summary] Rounds 1 to 15: Completed user module refactoring, tests passed 38/40
    6. [Recent Dialogue] Full content of rounds 16 to 20
    7. [Tool Output Ref] test_log_0817 (full log stored externally, call read if needed)

    This structure ensures the model always sees the core facts while preventing the context from being crowded out by irrelevant details. Reserving a portion of the context as a “thinking space” for the model also contributes to the stable completion of complex reasoning tasks.

    9. Model Selection and Evaluation

    Do not make decisions based solely on benchmark scores. A more reliable approach is to build an evaluation set based on your own business, typically starting with 50 to 200 real-world tasks. Focus on checking the following:

    • Code generation quality for target programming languages and frameworks, including compilation pass rates and unit test pass rates.
    • Factual consistency in long documents, especially whether cross-paragraph references are accurate.
    • Stability of instruction following in multi-turn interactions, and whether the model forgets early constraints in subsequent turns.
    • Whether end-to-end latency and unit costs meet product requirements.

    Evaluation results should record the test conditions, including the test set version, context length, decoding parameters, and hardware environment, to facilitate future reproduction and comparison.

    10. Conclusion

    The core design of ultra-large open-source models lies in trade-offs. Hybrid attention uses a few precise layers in exchange for lower computational costs; sparse experts trade larger total parameters for controllable single-pass computation; long context brings new memory and management challenges. Every design has its benefits and its boundaries.

    For developers, practical work typically involves three main tasks: estimating resources in advance using formulas and tables, validating the model’s performance on critical tasks using proprietary data, and managing context in a structured manner. Once these tasks are solidified, the balance between model capability and deployment cost becomes much easier to judge.