LLM Architecture and Parameter Scale: A Practical Guide to Dense Models, MoE, KV Cache, and Estimation

    This article explains how to separate model architecture from parameter scale when reading LLM specifications. It covers decoder-only Transformer building blocks, attention variants and KV-cache sizing, MoE total versus active parameters, long-context structural mechanisms, and scripts for estimating dense-model parameter counts and memory. It closes with a practical checklist and deployment selection guidance.

    1. Clarify Two Concepts First: Architecture and Parameter Scale

    When discussing “what architecture a large language model uses and how large its parameter scale is,” it helps to separate two things. Architecture refers to how the model converts an input token sequence into a probability distribution over the next token. This includes layer count, attention style, feed-forward network form, normalization placement, and expert mechanisms. Parameter scale refers to the number of all learnable weights in the model, usually expressed in B (billions). Architecture determines how many parameters each layer has; layer count and width then determine the total. The two constrain each other.

    The same scale number can also mean different things. Distinguish the following concepts:

    • Total parameters: the sum of all weights in the model, which determines storage footprint.
    • Active parameters: the parameters actually involved in a single forward computation, which determines compute per token. In dense models the two are the same; in mixture-of-experts models they can differ by several times.
    • Precision: the number of bytes each parameter occupies. BF16 and FP16 use 2 bytes, INT8 uses 1 byte, and INT4 uses about 0.5 bytes.

    When reading model documentation, first confirm whether a number refers to total parameters or active parameters, then confirm the corresponding precision and context length.

    2. The Skeleton of Mainstream Architectures: Decoder-Only Transformer

    Most current general-purpose large language models use a decoder-only Transformer structure. Its main components are:

    1. Token embedding layer: maps each token in the vocabulary to a vector of dimension d_model.
    2. Repeated Transformer blocks: each block contains a causal-masked self-attention sublayer and a feed-forward network sublayer, connected through residual connections and normalization.
    3. Output layer: projects the hidden state of the last layer to logits of vocabulary size, then applies softmax to obtain the next-token probability distribution.

    Common implementation choices in the industry include the following.

    • Normalization: most models use a Pre-Norm structure and RMSNorm instead of LayerNorm. RMSNorm avoids mean computation, has lower computational overhead, and is more stable during training.
    • Feed-forward network: the SwiGLU gated structure is common and contains three matrices: gate, up, and down. The parameter count of the three matrices is close to that of a two-layer MLP, so the intermediate dimension is usually set to about 8/3 times d_model, rather than the traditional 4 times.
    • Position encoding: Rotary Position Embedding (RoPE) applies position-dependent rotations to queries and keys, making attention scores depend mainly on relative position and providing a basis for length extrapolation.
    • Embedding sharing: some models let the input embedding and output projection share the same weights to reduce parameter count.

    3. Evolution of Attention Mechanisms and KV Cache

    In standard multi-head attention (MHA), each query head has its own key head and value head. During autoregressive inference, the model needs to cache the K and V of historical tokens. This cache is called the KV cache, and its memory usage grows linearly with sequence length. To reduce this overhead, several common variants have emerged:

    • Multi-query attention (MQA): all query heads share one set of K and V. The cache is the smallest, but model quality may degrade noticeably.
    • Grouped-query attention (GQA): query heads are divided into groups, and each group shares one set of K and V. It balances quality and cache size and is a common choice today.
    • Low-rank compressed KV: K and V are projected into a low-dimensional latent space for storage, then restored during computation or used directly, further compressing the cache.

    The KV cache estimation formula is:

    1. bytes per token = 2 × layers × KV heads × head dim × bytes per element

    The 2 means that both K and V are stored.

    Example: 32 layers, 8 KV heads, head dim 128, BF16 precision. Each token uses 2 × 32 × 8 × 128 × 2 = 131072 bytes, or 128 KiB. If the context length is 131072 tokens, the KV cache for a single sequence is about 16 GiB, not including the model weights themselves. The bottleneck in long-context inference is often memory capacity and bandwidth, not compute.

    4. Mixture of Experts (MoE): Total and Active Parameters Are Separated

    A mixture-of-experts structure replaces the standard feed-forward network with multiple expert sub-networks and uses a router to select top-k experts for each token. Each token passes only through the selected experts, so active parameters are much smaller than total parameters.

    Below is a minimal educational implementation:

    1. import torch
    2. import torch.nn as nn
    3. import torch.nn.functional as F
    4. class TopKMoE(nn.Module):
    5. def __init__(self, d_model, d_ff, num_experts, top_k):
    6. super().__init__()
    7. self.top_k = top_k
    8. self.router = nn.Linear(d_model, num_experts, bias=False)
    9. self.experts = nn.ModuleList(
    10. [nn.Sequential(nn.Linear(d_model, d_ff), nn.SiLU(), nn.Linear(d_ff, d_model))
    11. for _ in range(num_experts)]
    12. )
    13. def forward(self, x): # x: [tokens, d_model]
    14. probs = F.softmax(self.router(x), dim=-1)
    15. weights, idx = torch.topk(probs, self.top_k, dim=-1)
    16. weights = weights / weights.sum(dim=-1, keepdim=True)
    17. out = torch.zeros_like(x)
    18. for k in range(self.top_k):
    19. for e, expert in enumerate(self.experts):
    20. mask = idx[:, k] == e
    21. if mask.any():
    22. out[mask] += weights[mask, k:k + 1] * expert(x[mask])
    23. return out

    The double loop in this code is only for clarity. Production systems use fused operators and expert parallelism. Actual training also requires load-balancing methods, such as auxiliary losses or bias adjustment without auxiliary loss, to avoid a few experts being overloaded for long periods.

    The active parameter estimation formula is:

    1. active parameters ≈ shared parameters (attention, embeddings, etc.) + expert parameters × top_k / total experts

    The following is a fictional example configuration: shared parameters 10B, expert parameters 90B, 64 experts in total, and top-8 selected per token. Active parameters are about 10B + 90B × 8 / 64 = 21.25B, and total parameters are 100B. In other words, single-step compute is close to that of a dense model around 21B, but storage still needs to be provisioned for 100B. If the model also includes shared experts or other routing granularity designs, the formula above needs corresponding correction and should follow the specific configuration.

    5. Structural Support for Long Context

    Extending context length usually involves three aspects at the same time.

    • Position encoding extrapolation: scale or interpolate RoPE frequencies so the model can still maintain reasonable position awareness beyond the training length.
    • Attention computation scope control: sliding-window attention, alternating local and global attention layers, and similar methods limit each token’s attention scope to a certain window, making compute grow approximately linearly with length instead of quadratically.
    • Cache compression: use GQA, low-rank compression, and quantized KV caches to reduce memory usage per sequence.

    Supporting ultra-long context does not mean stable performance in ultra-long context. Evaluation should also examine retrieval accuracy, cross-paragraph information integration, and long-distance reasoning ability, not just the single number of maximum supported length.

    6. How to Estimate Dense Model Parameter Count

    Taking a standard dense Transformer as an example, each layer’s parameters consist of attention and feed-forward parts.

    • Attention: the Q projection is d × (h · d_h), the K and V projections are each d × (h_kv · d_h), and the output projection is (h · d_h) × d.
    • Feed-forward (SwiGLU): 3 × d × d_ff.
    • Normalization: 2 × d; bias terms are ignored.

    Total model parameters = token embeddings + layer count × per-layer parameters + output layer (if not tied to embeddings) + final normalization.

    The formulas above can be written as a function:

    1. def estimate_params(vocab_size, d_model, n_layers, n_heads, n_kv_heads, d_ff,
    2. tie_embeddings=False):
    3. head_dim = d_model // n_heads
    4. attn = d_model * n_heads * head_dim # Q projection
    5. attn += 2 * d_model * n_kv_heads * head_dim # K, V projections
    6. attn += n_heads * head_dim * d_model # Output projection
    7. ffn = 3 * d_model * d_ff # SwiGLU gate, up, down
    8. norms = 2 * d_model
    9. per_layer = attn + ffn + norms
    10. embed = vocab_size * d_model
    11. lm_head = 0 if tie_embeddings else vocab_size * d_model
    12. return embed + n_layers * per_layer + lm_head + d_model
    13. if __name__ == "__main__":
    14. total = estimate_params(vocab_size=128000, d_model=4096, n_layers=32,
    15. n_heads=32, n_kv_heads=8, d_ff=14336)
    16. print(f"{total / 1e9:.2f} B") # Output: 8.03 B

    For this example configuration, the parts are roughly as follows: about 218M parameters per layer, about 6.98B for 32 layers, and about 524M each for the token embedding and output layer.

    Memory requirements can be estimated as “parameter count × bytes per parameter.” With 8.03B parameters and BF16 precision, the weights require about 16.1 GB (about 15 GiB). With INT4 quantization, the weights require about 4 GB. Actual deployment also needs space reserved for activations, KV cache, and the inference framework.

    7. A Practical Checklist for Reading Scale Numbers

    1. Confirm whether the number refers to total parameters or active parameters. The two can differ greatly in mixture-of-experts models.
    2. Confirm precision. Memory requirements are proportional to bytes per parameter.
    3. Confirm context length. KV cache grows with length, and in long-text scenarios it often consumes more memory than the weights.
    4. When comparing different models, use the same evaluation set and the same precision settings to avoid comparisons across settings.
    5. Follow the configuration in official technical documentation. A version number alone does not reflect parameter scale, and different versions in the same series can differ greatly.

    8. Practical Selection Guidance

    Selection should start from the scenario.

    • If the focus is single-inference cost and latency, check active parameter count and compute first.
    • If the focus is storage and hardware required for deployment, check total parameter count and quantization scheme.
    • If the focus is long-text processing, evaluate KV cache size, attention style, and actual long-context performance.

    It is advisable to first use the script above to make theoretical estimates for candidate models and confirm whether memory and compute can meet requirements, then use small-scale stress tests to verify throughput, latency, and quality. Theoretical estimates can quickly rule out clearly infeasible options; stress-test results are what determine the final choice.