Architecture Innovations and Engineering Practices for Trillion-Parameter LLMs

    As large models reach the trillion-parameter scale, raw parameter stacking can no longer guarantee capability gains. This article traces the industry's shift from a parameter-and-score contest toward architecture and efficiency. It explains the quadratic cost of standard self-attention, the principles and trade-offs of linear attention and attention residuals, and the engineering challenges introduced by long context, sparse MoE, and native multimodality. It also presents a layered evaluation framework and cloud deployment practices covering elastic compute, storage, inference serving, and observability, giving developers a practical path to balance quality, latency, and cost.

    1. Introduction: From Stacking Parameters to Competing on Architecture

    Large models at the trillion-parameter scale are being released in rapid succession. Whenever a new model arrives, discussion quickly turns to “how capable is it really” and “does it belong to the top tier.” Some of this hype is overstated or timed to coincide with a launch for marketing effect, and it deserves a rational look.

    In practice, simply stacking parameters can no longer reliably deliver capability gains. On one hand, high-quality training data is approaching exhaustion; on the other, scaling compute is constrained by power availability, cluster interconnect, and scheduling efficiency. The industry has converged on a view that reaching the top tier requires three keys:

    • Scale: sufficient compute and parameter capacity, which sets the upper bound of a model’s capability;
    • Efficiency: high-performance architecture and systems engineering, which determines how far the same compute can go;
    • Validation: public, reproducible evaluation and real-world feedback, which determines whether capabilities can be trusted.

    Over the past two years, the technical center of gravity has clearly shifted from a “parameter and score contest” to architecture and efficiency. The most typical trend is that more and more models adopt a hybrid attention structure: standard attention is kept only in a few critical layers, while the remaining layers use linear-complexity sequence-modeling modules. At the same time, training stability, inference cost, and evaluation methodology have risen rapidly in engineering importance.

    This article follows that main thread:

    1. Start with the complexity bottleneck of standard attention;
    2. Analyze the technical principles of linear attention and attention residuals;
    3. Review the engineering challenges brought by long context, sparsification, and multimodality;
    4. Provide a scientific evaluation methodology and cloud deployment practices.

    Note: The architecture descriptions here are based on publicly available technical consensus. For specific implementations, refer to the technical documentation released by each team.

    2. The Complexity Bottleneck: The Quadratic Cost of Standard Attention

    Self-attention is the core operator of large models. Because it computes a relevance score for every pair of positions, both its compute and memory footprint grow quadratically with sequence length, which is an inherent bottleneck for long-context scenarios.

    Let the sequence length be T and the hidden dimension be d. Then:

    • Compute complexity: O(T² · d);
    • KV cache memory: approximately 2 · L · H · T · d_kv · bytes (L is the number of layers, H the number of attention heads, d_kv the key/value dimension per head);
    • Cache bandwidth: during decoding, reading the full history of keys and values is required for every generated token.

    Take a 128K context as an example. Without optimizations such as compressed caches, shared keys/values, or paged management, the KV cache for a single request alone can reach several GB. As concurrency rises, memory and bandwidth become the bottleneck first. In addition, softmax is a global normalization operation, and the attention matrix is hard to split cleanly along the sequence dimension, adding extra complexity to parallel implementations.

    More fundamentally, attention weights are concentrated on a single normalization denominator, making it difficult to express the whole computation as a simple recurrence along the sequence. This leads to:

    • During training and long-sequence inference, a long sequence cannot be treated as “a single accumulable state”;
    • The keys and values of every token must be fully retained, so cost grows linearly with context.

    The idea behind linear attention is precisely to relax the constraint introduced by this denominator.

    3. Key Technique 1: Linear Attention

    3.1 Principle: Replacing softmax with a Kernel Function

    The output of standard attention can be written as:

    1. o_i = Σ_j exp(q_i·k_j) · v_j / Σ_j exp(q_i·k_j)

    Linear attention uses a feature map φ(·) to approximate the softmax kernel and rewrites the output as:

    1. o_i = φ(q_i)ᵀ ( Σ_j φ(k_j) · v_jᵀ ) / ( φ(q_i)ᵀ Σ_j φ(k_j) )

    Note the position of the parentheses: first compute φ(k_j)·v_jᵀ, then multiply by the query. This step lowers the complexity order:

    • Standard attention: O(T² · d);
    • Linear attention: O(T · d²).

    When T is far larger than d, the latter grows almost linearly with sequence length. More importantly, Σ_j φ(k_j)·v_jᵀ is a [d, d] matrix independent of sequence length, which can be viewed as a “state” that compresses the entire history.

    Therefore, during autoregressive decoding there is no need to keep historical keys and values; only this fixed-size state must be maintained, greatly reducing memory and bandwidth pressure. Introducing a per-step decay factor into the state lets the model “gradually forget” stale information. This is conceptually close to the selective mechanism in state space models.

    1. import numpy as np
    2. def linear_attention_forward(Q, K, V, phi, eps=1e-6):
    3. """Mathematically equivalent implementation of linear attention.
    4. Q, K, V all have shape [B, H, T, D]; phi is the kernel feature map,
    5. e.g. elu(x) + 1.
    6. Returns an output with shape [B, H, T, D].
    7. """
    8. q, k = phi(Q), phi(K)
    9. # Aggregate keys/values first to obtain the state matrix S: [B, H, D, D]
    10. S = np.einsum('bhtd,bhts->bhds', k, V)
    11. # Normalization term z: [B, H, D]
    12. z = k.sum(axis=2)
    13. out = np.einsum('bhtd,bhds->bhts', q, S)
    14. denom = np.einsum('bhtd,bhtd->bht', q, z)[..., None] + eps
    15. return out / denom
    16. def linear_attention_decode_step(q, k, v, S, z, decay=1.0):
    17. """Autoregressive decoding: state size is fixed and independent of length.
    18. q, k, v are single-step [D] vectors; S is [D, D], z is [D].
    19. """
    20. S = decay * S + np.outer(k, v)
    21. z = decay * z + k
    22. return (q @ S) / (q @ z + 1e-6), S, z

    3.2 The Limits of Expressive Power

    Linear attention is not free of cost:

    • The kernel map “compresses” historical information, and the capacity of a single state is limited. On tasks such as long-range exact recall and needle-in-a-haystack retrieval, pure linear attention often underperforms standard attention;
    • Without decay, it is essentially a linear recurrence with fixed decay weights, good at modeling continuous dependencies but poor at content-based dynamic forgetting;
    • A common approach is to introduce gated decay, letting the model adaptively decide, based on the input, what information to keep or discard. The trade-off between recall accuracy and state capacity is one of the current research hotspots.

    3.3 Hybrid Structure: Balancing Capability and Efficiency

    The mainstream industry approach is a “hybrid”: most layers use linear-complexity modules to compress global information, while a few layers retain standard attention (or sliding-window local attention) for precise retrieval and local modeling. Interleaving the two at a fixed ratio is a common practice:

    1. class HybridStack:
    2. """Interleaved stack of linear attention layers and standard attention layers.
    3. n_layers : total number of layers
    4. linear_ratio: fraction of linear attention layers, e.g. 0.75 means 3 of every 4 layers are linear
    5. window_size : local window size for standard attention layers; None means global attention
    6. """
    7. def __init__(self, n_layers, linear_ratio=0.75, window_size=None):
    8. # Place one standard attention layer every `interval` layers
    9. interval = round(1 / (1 - linear_ratio))
    10. self.layers = []
    11. for i in range(n_layers):
    12. if i % interval == 0:
    13. self.layers.append(
    14. ("standard_attn", window_size)
    15. )
    16. else:
    17. self.layers.append(("linear_attn", None))
    18. def plan(self):
    19. """Output the type of each layer, for estimating memory and compute budgets."""
    20. return self.layers
    21. # 12 layers, 75% linear attention: layer 1 of every 4 is global standard attention
    22. for idx, (kind, window) in enumerate(HybridStack(12, 0.75).plan()):
    23. print(f"layer {idx:>2}: {kind} (window={window})")

    It is worth emphasizing that the hybrid ratio is not merely a hyperparameter but a cost lever that runs through both training and inference:

    Evaluation dimension Linear attention layer Standard attention layer
    Long-sequence training compute Near-linear growth Quadratic growth
    Long-context decoding memory Fixed-size state KV cache that grows with length
    Global exact retrieval Limited by state capacity Stronger
    Maturity of implementation and kernel ecosystem Relatively new, requires dedicated optimization Mature
    Sequence parallelism State merging is relatively complex Matrix hard to split without conflict, needs extra techniques

    A practical approach is to weigh the retrieval-accuracy gain from “keeping one more standard attention layer” against the change in long-context inference cost, deciding the ratio with data rather than intuition.

    3.4 Consistency Between Training and Inference

    Linear attention has two equivalent execution forms:

    • Parallel form: similar to a blockwise scan, where blocks compute independently and pass the state forward, fully parallelized during training;
    • Recurrent form: updates the state token by token, suited to autoregressive decoding.

    High-performance implementations usually require custom compute kernels that unify these two forms under the same interface and guarantee numerical consistency between training and inference. Otherwise, online behavior may deviate from offline evaluation. On the engineering side, special attention is needed for accumulation error in low precision and for feature-map overflow under large-magnitude inputs.

    4. Key Technique 2: Attention Residuals

    If linear attention answers “is it fast enough to compute,” residual connections answer “does it train stably, and does information flow smoothly.” Attention residuals are one direction of improvement over residual connections.

    4.1 Residual Connections: The “Highway” for Deep Networks

    Every Transformer sublayer is paired with a residual connection. Taking an attention layer as an example:

    1. x ← x + Attention(Norm(x))

    The residual branch lets gradients flow back directly along the identity path, which is the foundation that makes deep networks trainable.

    However, “indiscriminate addition” has two shortcomings:

    • Rigid allocation: no matter what a sublayer learns, its output is added to the main path with equal weight; the model cannot adjust each sublayer’s contribution by depth;
    • Noise interference: before early sublayers have converged, their outputs may disturb the main representation, while deep layers tend to repeatedly stack similar transformations.

    4.2 The Improvement Idea Behind Attention Residuals

    The core of “attention residual” style improvements is to introduce learnable or depth-varying weights into the residual. More broadly, it can be understood as allowing information from different layers or positions to be selectively aggregated in an attention-like manner. Common directions include:

    1. Learnable scaling: introduce a per-layer scalar or per-channel vector for the residual branch output, letting the model adaptively control each sublayer’s contribution;
    2. Depth-dependent scheduling: adjust the residual weight according to a sublayer’s depth, changing smoothly over the course of training;
    3. Cross-layer residual aggregation: allow deep layers to read information directly from several shallow layers, mitigating the decay that occurs as information is passed layer by layer through the network.
    1. def attention_residual_forward(x, attn_output, alpha, beta):
    2. """Generic skeleton for attention residuals (framework-agnostic).
    3. Standard residual: out = x + attn_output
    4. Weighted residual: out = (1 - alpha) * x + beta * attn_output
    5. alpha: main-path retention ratio, beta: attention-branch scale factor,
    6. both learnable.
    7. """
    8. return (1 - alpha) * x + beta * attn_output
    1. Normalization strategy: whether the normalization layer is placed before or after the sublayer significantly affects deep-training stability and final quality, and requires ablation experiments tuned to the specific model scale.

    4.3 Engineering Value: Stability Is Cost

    Training a very large model on a ten-thousand-GPU cluster can take weeks or even months, and a single divergence anomaly can bring enormous losses. A subtle change to the residual structure may lead to entirely different training-curve behavior.

    Therefore, any residual improvement should follow the same engineering discipline:

    • Controlled comparison under fixed conditions: run a control group on a similar scale with the same data and the same hyperparameters;
    • Multi-metric observation: track the loss curve, gradient norms, activation distributions, and performance on several intermediate-scale proxy tasks;
    • Follow scaling laws: confirm that gains at small scale persist at larger scale, rather than “effective at small scale, ineffective at large scale.”

    5. New Challenges at Scale: Long Context, Sparsification, and Multimodality

    5.1 Long Context: More Than Just Window Length

    As the context window expands from a few thousand tokens to hundreds of thousands or more, the difficulty is not only “fitting it in” but also:

    • Position-encoding extrapolation: inference beyond the trained length causes noticeable quality degradation. Mainstream approaches include adjusting the frequency base of rotary position encodings and staged “short-then-long” training;
    • Attention-distribution drift: under long context, attention weights tend to over-concentrate on local regions, hurting global information integration;
    • Evaluation losing focus: merely testing “can it find a given sentence” is not enough. Multi-hop reasoning, cross-section summarization, and ultra-long-document QA are the real tests of production workloads.

    5.2 Sparsification: Decoupling Total from Activated Parameters

    Mixture-of-Experts (MoE) is a common choice for very large models. It decouples a model’s total parameters from the parameters actually activated per token: total parameters determine knowledge capacity, while activated parameters determine compute cost. This lets a model expand capacity substantially while keeping inference cost controllable.

    Sparsification places higher demands on systems engineering:

    • Load balancing: auxiliary losses and similar techniques are needed to suppress “routing collapse” (a few experts being over-selected), otherwise some devices sit idle and overall throughput drops;
    • Expert-parallel communication: tokens must be dispatched and gathered across devices, and communication overhead is significant, requiring full overlap of computation and communication;
    • Asymmetry between memory and bandwidth: at inference time all expert weights must reside in memory, but each token reads only a small fraction of them. During decoding, bandwidth is often the main bottleneck, and batch size and quantization strategy have a large impact on throughput.

    5.3 Native Multimodality: Unified Representation and Unified Positions

    Native visual understanding differs fundamentally from “attaching a vision encoder and then concatenating”:

    • Visual information is encoded as tokens isomorphic to text, entering the same position-encoding and attention system;
    • Position representation is unified, making long-document understanding of interleaved text and images more natural;
    • The number of visual tokens directly affects context cost. A common approach is dynamic-resolution tiling, then pooling, compressing tokens, and similar methods to balance detail against overhead.

    At the training level, the ratio of interleaved text-image data, resolution sampling strategy, and the training order of visual versus textual data all influence cross-modal reasoning capability.

    6. Systematic Evaluation: Building Trustworthy Capability Metrics

    When a new model is released, promotional material often emphasizes “leading across the board.” But a single leaderboard score hardly reflects real usability, and evaluation needs a layered system.

    6.1 Layered Evaluation Framework

    Evaluation layer Question of focus Typical metrics
    Base capability Are knowledge and reasoning solid Subject knowledge, math, code, logical reasoning
    Instruction following Can it reliably meet format and constraints Format compliance rate, constraint satisfaction rate
    Long context Can it use very long inputs accurately Multi-hop retrieval, long-document summarization, global QA
    Domain adaptation Does it meet business needs Business test-set pass rate, human ratings
    Inference performance Is the engineering cost acceptable Time to first token, throughput, cost per token
    Safety and compliance Can risky content be effectively controlled Violation blocking rate, false-block rate

    6.2 Common Evaluation Pitfalls

    • Data contamination: public benchmarks may already be in the training data. Keep private test sets and detect overlap through sample deduplication;
    • Prompt sensitivity: changing the prompt template can shift results by several percentage points for the same model. Use multiple templates with repeated sampling and report variance;
    • Unfair comparison: directly comparing quantized versus non-quantized models, different context lengths, or different decoding parameters often yields misleading conclusions;
    • Ignoring inference cost: looking only at quality and not speed fails to reflect the real online experience.

    6.3 Performance Load Testing: Speak with a Common Yardstick

    Only by load-testing under the same hardware, the same parallelism strategy, and the same quantization configuration can comparisons be made horizontally. The following example is framework-agnostic and only illustrates the logic of metric collection:

    1. import time
    2. from concurrent.futures import ThreadPoolExecutor
    3. def benchmark(endpoint, prompts, max_new_tokens=256):
    4. """Load-test an inference service (pseudocode; interfaces depend on the actual service).
    5. endpoint: the inference service address under test
    6. prompts : a list of requests in a unified format
    7. max_new_tokens: max generation length per request
    8. Returns statistics of time to first token, throughput, and generation speed.
    9. """
    10. samples = []
    11. def one_request(prompt):
    12. start = time.perf_counter()
    13. first_token_at, n_tokens = None, 0
    14. for chunk in stream_completion(endpoint, prompt, max_new_tokens):
    15. if first_token_at is None:
    16. first_token_at = time.perf_counter() # moment the first token is received
    17. n_tokens = chunk.total_tokens # cumulative token count returned by the server
    18. end = time.perf_counter()
    19. ttft = first_token_at - start # time to first token
    20. decode_time = end - first_token_at # pure decoding time
    21. tps = (n_tokens - 1) / decode_time if decode_time > 0 else 0.0
    22. return {"ttft": ttft, "tps": tps, "tokens": n_tokens, "e2e": end - start}
    23. with ThreadPoolExecutor(max_workers=16) as pool:
    24. samples = list(pool.map(one_request, prompts))
    25. total_tokens = sum(s["tokens"] for s in samples)
    26. wall = max(s["e2e"] for s in samples)
    27. return {
    28. "P50_TTFT": sorted(s["ttft"] for s in samples)[len(samples) // 2],
    29. "P99_TTFT": sorted(s["ttft"] for s in samples)[int(len(samples) * 0.99)],
    30. "avg_TPS": sum(s["tps"] for s in samples) / len(samples),
    31. "throughput": total_tokens / wall, # total system throughput (tokens/sec)
    32. }

    On top of this, a weighted scorecard can be built so that quality, speed, and cost enter the same decision table:

    1. def scorecard(report, weights):
    2. """Normalize quality, latency, and cost to 0~1, then take a weighted sum.
    3. report : {"quality": quality score (0~100), "ttft_ms": time to first token (ms),
    4. "cost": cost per 1K tokens}
    5. weights: {"quality": 0.5, "latency": 0.3, "cost": 0.2}
    6. """
    7. q = report["quality"] / 100.0
    8. # Normalization example: 500ms latency and 1.0 cost correspond to baseline points
    9. latency = 500.0 / max(report["ttft_ms"], 1e-6)
    10. cost = 1.0 / max(report["cost"], 1e-6)
    11. latency = min(latency, 1.0)
    12. cost = min(cost, 1.0)
    13. return (weights["quality"] * q
    14. + weights["latency"] * latency
    15. + weights["cost"] * cost)

    The point of the scorecard is to turn “which model is better” into “which option is better under our business constraints.” The model itself becomes more like an infrastructure component that needs ongoing operation, rather than a one-time purchase.

    7. Cloud Deployment Practices: From Selection to Scale

    Bringing large-model capabilities into a business touches many areas: compute, scheduling, storage, serving, and observability. General capabilities from cloud providers such as Baidu AI Cloud can be combined in layers to form a complete technical foundation.

    7.1 Elastic Compute and Job Scheduling

    • Heterogeneous compute instances: provide compute instances of various specifications, matched to task needs. For example, long-context inference leans toward memory capacity, while high-concurrency short-text services lean toward throughput;
    • Elastic scaling: automatically scale up and down with traffic to handle business peaks;
    • Container platform: deploy training and inference jobs using the orchestration capabilities of a container platform, with queues and quotas enabling resource sharing across multiple teams;
    • Topology-aware scheduling: multi-machine, multi-GPU training is sensitive to network interconnect, so a single training job should be placed within a group of nodes with high-bandwidth interconnect whenever possible;
    • Fault tolerance: checkpointing and automatic-restart mechanisms can greatly reduce interruption losses in large-scale training.

    7.2 Storage and Data

    Training data and model artifacts are best stored in object storage:

    • Use versioning to trace the evolution of data and checkpoints;
    • Use lifecycle policies to archive cold data and control costs;
    • Read sharded data in a streaming manner to avoid piling up massive numbers of small files on local disk.

    On the data side, batch processing and stream-computing services can handle cleaning, deduplication, and sensitive-information masking, building a reusable data-processing pipeline.

    7.3 Inference Serving and Traffic Governance

    • Model serving: inference services should support continuous batching, paged KV-cache management, and prefix caching. For requests with long common prefixes, this can significantly reduce time to first token;
    • Traffic governance: connect to an API gateway for authentication, rate limiting, canary releases, and multi-model routing;
    • Cost tiering: route simple requests to lightweight models and complex requests to more capable models.
    1. # Multi-model routing and fallback policy (illustrative config; fields adjustable per gateway capabilities)
    2. routes:
    3. - name: simple-qa
    4. match:
    5. estimated_tokens: { lte: 512 }
    6. upstream: light-model
    7. rate_limit: { qps: 200 }
    8. - name: complex-reasoning
    9. match:
    10. estimated_tokens: { gt: 512 }
    11. upstream: strong-model
    12. rate_limit: { qps: 50 }
    13. fallback: light-model # auto-degrade when upstream fails, ensuring availability
    14. observability:
    15. metrics: [ttft, tps, error_rate, token_usage]
    16. logging: structured-json # unified structured logs for easy search and analysis

    7.4 Observability and Cost Governance

    • Use a logging service to centrally collect request logs, and monitoring and alerting to set thresholds for time to first token, throughput, and error rate;
    • Use distributed tracing to locate cross-service performance bottlenecks;
    • Track token usage by business line and by model, establish cost attribution, and periodically review high-consumption scenarios.

    7.5 Data Feedback Loops and Continuous Iteration

    Real business traffic is the most valuable optimization signal. After masking, online logs can be accumulated into a high-quality evaluation set for periodic regression testing. When systematic weaknesses appear, targeted optimization can be applied through supervised fine-tuning, preference alignment, and similar techniques, forming an “evaluate–optimize–re-evaluate” loop.

    8. Conclusion

    In the era of trillion parameters, what truly determines the value of a large model is no longer parameter scale alone, but the synergy of architecture innovation, systems engineering, and evaluation methodology:

    • Architecture layer: efficient mechanisms such as linear attention alleviate quadratic complexity, improvements such as attention residuals enhance deep-training stability, and hybrid structures plus sparsification balance capability against cost;
    • Engineering layer: from parallel training and fault-tolerant recovery to inference acceleration and traffic governance, each item directly affects the cost per token and the user experience;
    • Evaluation layer: a layered, reproducible evaluation system that includes private data is the foundation for technical selection and business decisions.

    For developers and enterprises, the pragmatic path is to first clarify the business scenario and constraints, then build a scorecard around the three dimensions of quality, latency, and cost, and finally complete deployment using elastic compute, container platforms, model serving, and observability capabilities. Only by letting the technology be continually validated and refined in real traffic can “technical prestige” be turned into sustainable business value.