Evolution of LLM Architectures and Parameter Scale Analysis

    This article explores the evolution of Large Language Model (LLM) architectures and parameter scales. It distinguishes between model structure and parameter size, detailing the mainstream decoder-only Transformer framework, attention mechanism optimizations (such as GQA and MLA), and the differences between dense and Mixture of Experts (MoE) models. Furthermore, it provides methods for estimating parameter counts, analyzes the impact of parameters on memory and compute requirements, and discusses quantization alongside common misconceptions regarding model size.

    1. Clarifying the Concepts: What Structure and Parameter Scale Represent

    When discussing Large Language Models (LLMs), “structure” and “parameter scale” are often conflated. Structure describes how the model internally organizes computations, including the number of layers, the implementation of attention, the form of the feed-forward network, and whether expert partitioning is used. Parameter scale describes the total number of learnable weights in the model, typically measured in billions (B). The two are interdependent: for the same 7 billion parameters, a dense structure and a sparse structure can differ several times in inference compute and memory consumption. Therefore, understanding a model requires looking at its structure and scale together.

    2. The Mainstream Backbone: Decoder-Only Transformer

    Currently, the vast majority of generative LLMs adopt a stacked decoder-only Transformer architecture. Each layer typically contains two sub-modules: multi-head self-attention and a feed-forward network. Each sub-module is wrapped with residual connections and normalization layers.

    2.1 Normalization and Residual Connections

    The mainstream approach is Pre-Norm, where the input is normalized before entering the sub-module and then added to the output of the sub-module. This method makes gradients in deep networks more stable and training convergence more reliable. The normalization layer typically uses RMSNorm, which only calculates the root mean square for scaling, omitting mean centering. This reduces computational cost, and its practical performance is comparable to LayerNorm.

    2.2 Feed-Forward Networks and Gated Activations

    Early models used feed-forward networks composed of two linear transformations and an activation function. Currently, the SwiGLU gated structure is common. It uses two paths of linear transformations; one path passes through an activation function and is multiplied element-wise with the other path, followed by an output projection. If the hidden dimension is d and the intermediate dimension is d_ff, this structure contains three sets of weight matrices, with a parameter count of approximately 3 × d × d_ff. The intermediate dimension is typically 2.5 to 4 times the hidden dimension, depending on the designer’s trade-off between parameter efficiency and expressive power.

    2.3 Positional Encoding and Long Context

    Rotary Positional Encoding (RoPE) is the current mainstream choice. It encodes positional information as rotations applied to the query and key vectors, making attention scores depend only on relative positions. Long context capabilities are usually achieved through extrapolation by adjusting rotation frequencies, such as position interpolation or frequency-based scaling. These methods provide good generalization beyond the training length but still require adaptation training with long-text data; otherwise, performance drops significantly.

    3. Evolution of Attention Mechanisms

    The attention mechanism is the core component affecting inference costs. Its evolution primarily revolves around one question: how to reduce the size of the Key-Value (KV) Cache.

    3.1 Multi-Head Attention (MHA)

    Each attention head has independent query, key, and value projections. This offers strong expressive power, but during inference, each head needs to cache its keys and values, causing the KV Cache to grow linearly with the number of heads.

    3.2 Multi-Query Attention (MQA) and Grouped-Query Attention (GQA)

    MQA allows all query heads to share the same set of keys and values, reducing the cache size to 1/(number of heads) of the original. GQA divides the query heads into several groups, with each group sharing a set of keys and values, serving as a compromise between MQA and MHA. Most current large models use GQA to strike a balance between cache savings and quality loss.

    3.3 Multi-head Latent Attention (MLA)

    MLA’s approach is to first compress keys and values into a low-dimensional latent vector for storage, and then project them back when computing attention. Since the cache stores low-dimensional representations, it significantly reduces memory consumption while maintaining multi-head expressive power. However, this method is more complex to implement and demands higher operator optimization.

    4. Dense Models vs. Mixture of Experts (MoE)

    4.1 Dense Models

    In dense models, every token passes through all parameters in each layer. The larger the parameter count, the greater the computational load, meaning inference cost is approximately proportional to the parameter count. The structure is simple, and engineering for training and deployment is highly mature.

    4.2 Mixture of Experts (MoE)

    MoE replaces the feed-forward network with multiple expert networks, and a router selects a few experts for each token (commonly top-k, where k is 1 to 8). The model’s total parameter count is large, but each token only activates a fraction of them, meaning the activated parameter count is much smaller than the total.

    MoE needs to address two main issues:

    • Load Balancing: If the router consistently assigns tokens to a few experts, some experts will be overloaded while others are under-trained. A common solution is to add an auxiliary balancing term to the loss function or dynamically adjust routing tendencies through bias terms.
    • Communication Overhead: During multi-GPU training and inference, experts are distributed across different devices. Tokens need to be dispatched across GPUs, and network bandwidth can become a bottleneck.

    Some MoE designs also introduce shared experts, through which all tokens pass, to carry general knowledge, while the remaining experts focus on specific patterns.

    4.3 Example: Calculating MoE Parameters

    Assume a hidden dimension d of 4096, an expert intermediate dimension of 1408, 64 routing experts per layer, 2 routing experts selected per token, and 1 shared expert. The parameter count for a single expert is 3 × 4096 × 1408, approximately 17.3 million. Therefore:

    • Total parameters for routing experts per layer are approximately 64 × 17.3 million, i.e., 1.107 billion.
    • Activated parameters per layer are approximately (2 + 1) × 17.3 million, i.e., 51.9 million.

    It is evident that there is a significant gap between total parameters and activated parameters. When comparing two models, it is necessary to clarify whether the metric refers to total parameters or activated parameters.

    5. Long Context and Sparse Attention

    The computational cost of full attention grows quadratically with sequence length, which is the main bottleneck for long context. Common industry solutions include:

    • Sliding Window Attention: Each token only attends to a recent window. The computational cost is linearly related to the sequence length, but long-distance information relies on multi-layer propagation.
    • Sparse Attention Patterns: Combining local windows with a few global or selective attention mechanisms to balance long-range dependencies and computational cost.
    • Hybrid Architectures: Some layers use linear attention or state space modules, while others retain standard attention, balancing long-sequence efficiency with precise retrieval capabilities.

    These methods all require corresponding training recipes. Simply switching to sparse patterns only during inference usually results in noticeable quality degradation.

    6. Parameter Estimation Methods

    You can directly estimate parameter counts based on the structure, making it easier to judge model scale without consulting documentation. The following function targets a standard dense Transformer, ignoring minimal parameters like normalization layers:

    1. def dense_params(d, n_layers, d_ff, vocab, n_heads, n_kv_heads):
    2. head_dim = d // n_heads
    3. # Projections for query, key, value, and output
    4. attn = d * (n_heads * head_dim) + 2 * d * (n_kv_heads * head_dim) + (n_heads * head_dim) * d
    5. # Three sets of matrices for SwiGLU
    6. ffn = 3 * d * d_ff
    7. return n_layers * (attn + ffn) + vocab * d
    8. # Hidden dim 4096, 32 layers, intermediate dim 11008, vocab 32000, 32 heads (MHA)
    9. total = dense_params(4096, 32, 11008, 32000, 32, 32)
    10. print(f"{total / 1e9:.2f} B") # Outputs approximately 6.61 B

    This result is basically consistent with common 7B-level dense models. Note that if the model shares input and output embedding weights, the embedding part is only counted once; if not shared, it must be doubled.

    7. Relationship Between Memory, Compute, and Parameter Scale

    Parameter scale directly dictates the consumption of three types of resources.

    7.1 Weight Memory

    The weight footprint equals the parameter count multiplied by the number of bytes per parameter. Taking bf16 as an example, with 2 bytes per parameter, a 7B model requires about 14 GB just to store weights.

    7.2 KV Cache Memory

    The KV Cache grows with sequence length and the number of concurrent requests. Its size is calculated as:

    1. def kv_cache_bytes(seq_len, n_layers, n_kv_heads, head_dim, bytes_per_elem=2, batch=1):
    2. # Store key and value separately, hence multiply by 2
    3. return batch * seq_len * 2 * n_layers * n_kv_heads * head_dim * bytes_per_elem
    4. # 32 layers, 32 KV heads, head_dim 128, bf16, 4096 tokens
    5. print(kv_cache_bytes(4096, 32, 32, 128) / 2**30, "GiB") # 2.0 GiB
    6. # If changed to 8 KV heads (GQA), the same length drops to 0.5 GiB
    7. print(kv_cache_bytes(4096, 32, 8, 128) / 2**30, "GiB") # 0.5 GiB

    As you can see, simply adjusting the number of KV heads reduces the cache to a quarter of the original size. This is why GQA and MLA are highly valued.

    7.3 Compute Volume

    During inference, the forward compute for generating each token is approximately 2N floating-point operations, where N is the activated parameter count. During training, the compute per token is approximately 6N. Fewer activated parameters mean lower inference costs for the same quality level.

    8. Quantization and Deployment

    Quantization saves memory by reducing the bit-width of each weight. Common bit-widths and their approximate storage footprints are as follows:

    Precision Bytes per Parameter Approximate Weight Memory for 7B Model
    bf16 2 14 GB
    int8 1 7 GB
    int4 0.5 3.5 GB (additional overhead for scale factors, etc.)

    Quantization introduces a certain loss of precision, the degree of which depends on the quantization method, model structure, and task type. For inference-heavy, latency-sensitive scenarios, int8 is usually acceptable, while int4 requires empirical evaluation on the target task.

    9. Common Misconceptions About Parameter Scale

    • More parameters do not necessarily mean better performance. The quality and quantity of training data, the number of training tokens, and post-training alignment are equally critical. Industry experience suggests that with a sufficient compute budget, a ratio of training tokens to parameter count around 20 is common, though this is just an empirical reference.
    • Total parameters and active parameters cannot be directly compared. The total parameters of MoE models cannot be directly compared to the active parameters of dense models.