LLM Architectures and Parameter Scales: Dense vs. MoE, Attention, KV Cache, and Inference Cost

    This article explains why model structure should be examined before parameter count, then walks through Transformer decoder components, parameter estimation, dense and mixture-of-experts architectures, attention variants and KV-cache sizing, long-context implementation considerations, rough inference-cost bounds, and practical model-selection advice. It includes runnable estimation snippets based on illustrative configurations rather than metrics for any specific model.

    1. Why Look at Structure Before Parameters

    When people discuss large language models, parameter count is often the first metric that comes to mind. It is certainly the most intuitive indicator, but it only describes the model’s size. It does not explain how the model uses those parameters. Two models with the same parameter count can differ substantially in inference speed, memory usage, and long-text behavior if they use different layer counts, hidden dimensions, attention schemes, or expert organization. Understanding mainstream architectures is therefore a prerequisite for judging whether a parameter scale is reasonable.

    This article follows this order: basic structure, parameter calculation, dense and sparse architectures, attention optimization, long context, inference cost, and model-selection advice. It also provides estimation code that can be run directly. The numerical values in this article are assumed configurations for illustrating the method and do not correspond to actual metrics of any specific model.

    2. Basic Structure of Mainstream Models

    Most current large language models use a Transformer decoder structure, which mainly consists of the following parts.

    1. Token embedding layer: Maps discrete tokens to continuous vectors. The vector dimension is usually called the hidden size.
    2. Stacked decoder blocks: Each layer contains an attention sublayer and a feedforward sublayer. Both sublayers have residual connections and normalization.
    3. Position encoding: Provides token-order information. Rotary position embedding (RoPE) is one of the most widely used approaches. It rotates query and key vectors so that attention scores naturally carry relative position information.
    4. Output layer: Projects the hidden states from the final layer to logits of vocabulary size, then applies softmax to obtain the probability distribution for the next token.

    In implementation details, RMSNorm has become a common normalization choice because it is computationally cheap and trains stably. Feedforward sublayers commonly use gated structures such as SwiGLU. Compared with a traditional two-layer MLP, this structure often achieves better results at a similar parameter count.

    3. How to Estimate Parameter Count

    For a dense model, parameters mainly come from three parts: attention projection matrices, feedforward network matrices, and the embedding layer. The function below calculates the total parameter count from these three parts. It ignores normalization layers and bias terms because their share is very small.

    1. def estimate_dense_params(num_layers, hidden, ffn_hidden, vocab,
    2. num_heads, num_kv_heads):
    3. head_dim = hidden // num_heads
    4. # Q and O projections are hidden x hidden; K and V depend on KV heads
    5. attn = hidden * hidden * 2 + hidden * num_kv_heads * head_dim * 2
    6. # Gated FFN contains gate, up, and down matrices
    7. ffn = 3 * hidden * ffn_hidden
    8. # Input embedding and output layer are counted separately (when weights are not tied)
    9. embed = vocab * hidden * 2
    10. return num_layers * (attn + ffn) + embed
    11. # Assumed configuration: 32 layers, hidden size 4096, FFN size 11008,
    12. # vocab 32000, 32 query heads, 8 KV heads
    13. total = estimate_dense_params(32, 4096, 11008, 32000, 32, 8)
    14. print(f"Approximately {total / 1e9:.2f} B parameters") # about 5.93 B

    This example shows that the feedforward layer accounts for most of the parameters in a single layer. That is also why expanding the feedforward dimension is one of the most direct ways to increase capacity.

    It is also important to understand the conversion between parameter count and memory. When stored in BF16 or FP16, each parameter takes 2 bytes; INT8 takes 1 byte; INT4 takes about 0.5 bytes. For the roughly 5.9B-parameter model above, the weights alone require about 12 GB in BF16 using decimal units. In actual deployment, space must also be reserved for KV cache, activations, framework overhead, and fragmentation. In practice, a 10% to 20% margin is usually reserved.

    4. Dense Architecture vs. Mixture-of-Experts Architecture

    In a dense architecture, every token passes through all parameters, and computation is approximately proportional to parameter count. The structure is simple, and both training and inference behavior are easy to predict.

    A Mixture-of-Experts (MoE) architecture replaces some feedforward layers with multiple expert networks. A router selects the top-k experts with the highest scores for each token to participate in computation. This design allows the model’s total parameter count to be large while the number of activated parameters per token remains relatively small.

    Activated parameters can be estimated as follows:

    Activated parameters ≈ attention parameters + embedding parameters + shared expert parameters + top-k × single expert parameters × number of layers

    The main differences between the two architecture types are summarized below.

    Dimension Dense architecture Mixture-of-Experts architecture
    Compute Proportional to total parameters Proportional to activated parameters
    Storage All parameters must be resident All experts must be stored
    Training complexity Lower Requires load-balancing mechanisms to prevent a few experts from being overloaded
    Communication overhead Lower Routing adds extra communication when experts are distributed across multiple GPUs
    Engineering difficulty Mature and easy to debug Routing, parallelism strategy, and inference scheduling are more complex

    The choice depends on the target scenario. If the service has high concurrency and is sensitive to compute cost per unit, a sparse structure often has advantages. If the deployment environment has limited memory and needs to run on a single machine, a dense structure may be more straightforward.

    5. Evolution of Attention Mechanisms

    The attention mechanism determines how key-value information is shared and directly determines the size of the KV cache during inference.

    • Multi-head attention (MHA): Each query head has its own key and value heads. It has strong expressive capability but the largest cache overhead.
    • Multi-query attention (MQA): All query heads share the same set of keys and values. The cache is the smallest, but quality may decrease.
    • Grouped-query attention (GQA): Query heads are divided into groups, and each group shares one set of keys and values. This is a common tradeoff between quality and efficiency.

    KV-cache size can be estimated with the function below:

    1. def kv_cache_bytes(num_layers, num_kv_heads, head_dim,
    2. seq_len, batch_size, bytes_per_elem=2):
    3. # Keys and values are both stored, hence the factor of 2
    4. return (2 * num_layers * num_kv_heads * head_dim
    5. * seq_len * batch_size * bytes_per_elem)
    6. # Using the configuration above: 32 layers, 8 KV heads, head_dim=128,
    7. # sequence length 4096, batch size 1
    8. size = kv_cache_bytes(32, 8, 128, 4096, 1)
    9. print(f"KV cache is about {size / 1e9:.2f} GB") # about 0.54 GB

    As shown, sequence length and batch size scale the KV cache linearly. As the number of concurrent requests increases, the cache often exhausts memory before the weights do. Therefore, techniques such as GQA or low-rank KV compression provide especially clear benefits in long-sequence and high-concurrency scenarios.

    6. Key Implementation Points for Long-Context Capability

    Supporting long context usually requires coordination across several areas.

    1. Position-encoding extrapolation: When used beyond the training length, position information exceeds the range the model has seen. Methods such as position interpolation and frequency-wise scaling can mitigate this issue.
    2. Training data: The model needs to be trained on longer documents to learn long-distance dependencies.
    3. Attention computation cost: The computation of standard full attention is quadratic in sequence length. Sliding windows, sparse attention, and IO-aware block implementations can reduce actual time and memory overhead.
    4. Cache management: The longer the sequence, the larger the KV cache. Paged management or quantization methods are needed to control memory usage.

    In engineering practice, it is advisable to first measure the real input-length distribution in the target workload, then decide the target context window. In most workloads, long-tail requests account for only a small fraction. Reserving resources for every request based on the longest window often causes waste.

    7. Rough Estimation of Inference Cost

    Inference has two stages: prefill and decode. Prefill processes the input at once and is compute-intensive. Decode generates tokens one by one and is usually limited by memory bandwidth at small batch sizes.

    When the batch size is 1, a dense model must read all weights for every generated token, so there is a theoretical upper bound on single-request speed:

    1. def decode_upper_bound(weight_gb, bandwidth_gb_s):
    2. # For each token, weights are read sequentially; speed is bounded by memory bandwidth
    3. return bandwidth_gb_s / weight_gb
    4. # Assumption: 12 GB weights, 1000 GB/s memory bandwidth
    5. print(f"Theoretical upper bound: about {decode_upper_bound(12, 1000):.0f} token/s") # about 83 token/s

    This is a theoretical upper bound. Actual speed is also affected by compute efficiency, scheduling overhead, and batching strategy. For MoE models, each token reads the weights corresponding to activated parameters. At larger batch sizes, however, different requests activate different experts, so actual reads approach all experts. Estimations need to distinguish between these two cases.

    8. Model Selection and Practical Advice

    1. Clarify task difficulty: Short-text classification, information extraction, complex reasoning, and code generation have very different requirements for model capacity. There is no need to always choose the largest model.
    2. Estimate memory before selecting a model: Add up weights, KV cache, activations, and reserved space, then compare the total against the available memory budget.