Modern LLM Architecture Explained: Decoder-Only Backbone, Attention Variants, MoE, and Parameter Scale

    This article breaks down the architecture of modern large language models and explains why most generative LLMs today use a decoder-only backbone. It examines key components, including the evolution of attention from MHA through MQA and GQA to MLA, sparse mixture-of-experts feed-forward layers, RoPE, Pre-Norm and RMSNorm, and SwiGLU. It also explains how parameter scale differs between dense and sparse models, how total and activated parameters differ, and the engineering trade-offs around training and inference cost, memory usage, quantization, and KV Cache optimization. It closes with practical guidance for choosing models.

    1. Overall Architecture: Why Modern LLMs Have Converged on Decoder-Only

    Understanding modern LLM architecture starts with its overall structure. Three common neural network architectures are used in the industry: encoder-only, decoder-only, and encoder-decoder.

    Encoder architectures excel at bidirectional understanding of the input and are typically used for tasks such as text classification and embedding or vector representation. Encoder-decoder architectures performed well in early translation and summarization tasks, mapping sequences to sequences through a two-stage “encode-decode” process. Mainstream generative LLMs today, however, almost all adopt the decoder-only architecture, mainly for three reasons:

    1. Unified task formulation: The autoregressive next-token prediction paradigm allows almost every task (understanding, generation, dialogue, code completion) to be expressed as “continue the text from the preceding context.” There is no need to design different input and output heads for each task.
    2. Training efficiency: With a causal mask, predictions at every position can be used to compute the loss in parallel. This yields a high density of training signals per forward pass and better data utilization.
    3. Inference friendliness: During inference, the KV Cache stores only the key and value pairs for past tokens. New tokens can be generated incrementally without recomputing previous ones. Combined with streaming output, this is well suited to interactive applications.

    As a result, discussions of modern LLM architecture focus on the decoder-only design. Each of its layers consists of two core sublayers:

    • The self-attention sublayer models dependencies among tokens within the sequence.
    • The feed-forward network (FFN) sublayer applies a nonlinear transformation to the representation at each position.

    Both are wrapped in residual connections and normalization. Stacked layer upon layer, they form deep networks with dozens or even hundreds of layers.

    2. Breaking Down the Core Components

    2.1 Attention: From MHA to GQA and MLA

    Attention is at the heart of the Transformer. It determines how a model assigns attention weights to aggregate contextual information.

    • MHA (multi-head attention): Projects the input into multiple independent groups of query, key, and value vectors and computes several attention heads in parallel. It offers strong expressive power, but inference requires caching the KV pairs of every head, which consumes a large amount of GPU memory.
    • MQA (multi-query attention): All heads share a single set of keys and values, substantially reducing the KV Cache, but potentially losing some expressive power.
    • GQA (grouped-query attention): Sits between the two. Multiple query heads share one KV group, balancing quality and efficiency. It has become a common choice in modern LLMs.
    • MLA (low-rank compression attention): Compresses the KV pairs with a low-rank projection and then reconstructs them, further reducing KV Cache usage. It is particularly advantageous for long-context scenarios.

    The main driver of this evolution is the memory overhead of the KV Cache. During inference, longer sequences, more layers, and more heads all mean more cached key-value pairs, which often become the memory bottleneck for long-context inference. Schemes such as GQA and MLA were designed to ease this tension.

    The following illustrative code shows scaled dot-product attention with a causal mask:

    1. import numpy as np
    2. def scaled_dot_product_attention(Q, K, V, mask=None):
    3. """
    4. Q, K, V: shape (batch, heads, seq_len, d_k)
    5. mask: causal mask, shape (seq_len, seq_len), upper triangle is -inf
    6. """
    7. d_k = Q.shape[-1]
    8. scores = np.matmul(Q, K.transpose(0, 1, 3, 2)) / np.sqrt(d_k)
    9. if mask is not None:
    10. scores = scores + mask # Mask out future positions to preserve causality
    11. attn = softmax(scores, axis=-1)
    12. return np.matmul(attn, V), attn
    13. def softmax(x, axis=-1):
    14. x = x - np.max(x, axis=axis, keepdims=True)
    15. e = np.exp(x)
    16. return e / np.sum(e, axis=axis, keepdims=True)

    2.2 Feed-Forward Networks: From Dense FFN to Sparse MoE

    The feed-forward network holds most of a model’s parameters, making it the main driver of parameter growth. There are two distinct approaches:

    • Dense FFN: Every token goes through the complete FFN, and all parameters participate in every forward pass. This architecture is simple and trains stably, but compute and memory overhead grow linearly as the parameter count increases.
    • Sparse MoE (mixture of experts): Splits the FFN into multiple “expert” sub-networks. A router selects a few experts to process each token. The key idea is that the total parameter count can be very large, yet each token activates only a small fraction of it. In other words, total and activated parameters are separate.

    Key design points of MoE include:

    1. Routing strategy: Top-K routing is commonly used, sending each token only to the K experts with the highest scores.
    2. Load balancing: An auxiliary loss keeps all tokens from flooding a few experts, which would cause training to degrade.
    3. Expert parallelism: Experts can be distributed across different devices and computed in parallel, improving scalability.

    It is important to note that total parameters do not equal activated parameters. An MoE model may have hundreds of billions of total parameters, but each token actually activates only a small part of them (for example, a few experts). This leads to an important intuition:

    • Total parameter count determines a model’s knowledge capacity and memory footprint.
    • Activated parameter count determines the compute (FLOPs) required per token.

    Both numbers need to be considered when evaluating a model.

    2.3 Positional Encoding and Normalization

    Positional encoding: Self-attention is inherently insensitive to order, so positional information must be injected separately. Modern models widely use rotary position embedding (RoPE) and its variants. RoPE applies rotational transformations to the queries and keys in the attention computation to encode relative positions. It naturally supports length extrapolation, which makes it an important foundation for long-context capability.

    Normalization: The mainstream approach has shifted from Post-Norm to Pre-Norm, which applies normalization before each sublayer and makes training of deep networks more stable. RMSNorm is commonly used as the normalization operator. Compared with LayerNorm, it drops the mean-centering step, making it more lightweight and efficient.

    2.4 Activation Functions

    Activation functions in feed-forward networks have evolved from early options such as ReLU and GeLU to gated linear unit variants such as SwiGLU. By introducing a gating branch, SwiGLU often achieves better performance at a similar parameter count and has become a common configuration in modern LLMs.

    3. Parameter Scale: Two Paths, Dense and Sparse

    Parameter scale is usually measured in billions (B) and trillions (T). The industry largely follows two clear paths:

    • Dense model path: Parameter counts are mainly in the billions, ranging from a few billion to tens of billions. All parameters take part in computation, so inference performance and memory requirements are predictable. This path suits scenarios with relatively fixed resources.
    • Sparse MoE model path: Total parameters can reach hundreds of billions or even trillions, while activated parameters remain low. This approach trades a controllable inference cost for greater knowledge capacity and is commonly used for ultra-large-scale models.

    Vocabulary size also directly affects the total parameter count. Modern LLMs often use vocabularies on the order of a hundred thousand tokens (for example, 100,000–150,000). The embedding and output layers then hold a considerable number of parameters, which is especially important for multilingual and code scenarios. Context length has expanded from a few thousand tokens in early models to hundreds of thousands or even millions of tokens. This puts greater demands on positional encoding, attention efficiency, and memory management.

    4. Engineering Trade-offs Behind Parameter Scale

    Growing parameter counts bring a series of practical constraints that must be weighed when putting models into production:

    1. Different costs for training and inference: Training is a one-time, heavy investment, whereas inference is an ongoing, long-term expense. Sparse models activate fewer parameters at inference, but their large total parameter count leads to high memory consumption. Deployment cost therefore cannot be judged by activated parameters alone.
    2. Memory estimation: A rough rule of thumb is that with FP16 storage, each parameter takes about 2 bytes of memory. Inference also requires extra overhead for the KV Cache, activations, and other components. A dense model with tens of billions of parameters can require tens of gigabytes of GPU memory for its weights alone. This is one reason large models are hard to run on a single consumer-grade GPU.
    3. Quantization: Low-bit quantization such as INT8 and INT4 can substantially reduce memory usage and increase inference throughput while keeping accuracy loss manageable. This makes it an important approach in resource-constrained settings.
    4. KV Cache optimization: Techniques such as GQA, MLA, and paged memory management (in the spirit of Paged Attention) are specifically designed to ease the memory pressure of long-context inference.

    5. Selection and Practical Recommendations

    With so many model architectures to choose from, here are a few practical guidelines:

    • Look at activated parameters, not just total parameters: When assessing inference cost, focus on the compute actually required per token, not just the total parameter count.
    • Weigh dense versus sparse by use case: Dense models are a good first choice when predictable deployment and fixed resources are priorities. Sparse MoE models suit scenarios that demand maximum capacity and scalability and are backed by strong engineering capabilities.
    • Pay attention to long-context capability: If your work involves long-document understanding or extended multi-turn conversations, take a close look at the positional encoding scheme and KV Cache optimizations.
    • Make good use of general-purpose cloud capabilities: In practice, model training and inference often require supporting infrastructure such as object storage, message queues, container platforms, logging, and monitoring and alerting. Platforms such as Baidu AI Cloud typically provide integrated general-purpose capabilities spanning compute, storage, and deployment and operations. This helps teams focus on the models and the business itself rather than on low-level resource management.

    In summary, the evolution of modern LLM architecture is essentially a constant search for a better balance among expressive power, training stability, inference efficiency, and deployment cost. Understanding the decoder-only backbone, key designs such as attention and MoE, and the distinction between total and activated parameters makes it easier to quickly grasp the architectural essence of new models. It also helps you make more rational engineering decisions that fit your business.