A Breakdown of Modern LLM Architectures and Parameter Count Estimation
This article explains why model architecture and parameter count matter for memory usage, inference latency, and training cost. It walks through the shared decoder-only Transformer backbone, common attention variants (MHA, MQA, GQA, MLA) and their KV cache implications, dense and Mixture-of-Experts feed-forward layers, and normalization and positional encoding choices. It then provides formulas and runnable code for estimating parameter counts and memory requirements, a worked example with a hypothetical configuration, and a checklist for reading technical reports. All numbers are illustrative assumptions and do not correspond to any specific model.
1. Why Model Architecture and Parameter Count Matter
Parameter count determines a model’s memory footprint, inference latency, and training cost. Architecture determines how much capability you get from a given parameter budget and how efficiently the model runs at inference time. Together, they tell you whether a model can run on specific hardware at an acceptable cost.
This article covers three layers of the topic: first, the shared backbone used by mainstream models; second, common refinements to attention and feed-forward networks; and finally, methods for estimating parameter counts and memory usage, with runnable example code. All figures are hypothetical configurations for demonstration purposes and do not correspond to any specific model.
2. The Shared Backbone: Decoder-Only Transformers
The vast majority of general-purpose LLMs today use a decoder-only Transformer architecture, trained to predict the next token given the preceding context. The data flow looks roughly like this:
- Input tokens pass through an embedding layer and are mapped to vectors of dimension d_model.
- The vectors flow through N identically structured blocks, each containing an attention sublayer and a feed-forward sublayer.
- The final hidden states are normalized and mapped by an output layer to a probability distribution over the vocabulary.
Each block typically uses a Pre-Norm structure: normalization is applied before each sublayer, and residual connections add the input back to the output. This design stabilizes gradients in deep networks and is now standard practice.
The attention layer applies a causal mask, ensuring that position t can only attend to positions 1 through t. This is the foundation of autoregressive generation.
3. The Evolution of Attention Mechanisms
3.1 Multi-Head Attention (MHA)
Standard multi-head attention gives each head its own query (Q), key (K), and value (V) projections. More heads allow the model to attend to more patterns in parallel, but the key-value cache (KV Cache) required at inference grows accordingly.
3.2 Multi-Query and Grouped-Query Attention (MQA and GQA)
Multi-query attention lets all query heads share a single set of K and V. Grouped-query attention (GQA) is a compromise between the two: query heads are divided into groups, and each group shares one set of K and V. GQA significantly reduces the KV Cache while retaining most of the model’s expressive power, which is why it is common in large models.
3.3 Multi-Head Latent Attention (MLA)
The low-rank compression approach projects K and V into a lower-dimensional latent space before caching, then reconstructs them during computation. It further shrinks the cache at the cost of slightly more computation and implementation complexity.
3.4 Estimating KV Cache Memory
When inferring long sequences, the KV Cache often consumes more memory than the weights themselves. Its size can be estimated with the following formula:
def kv_cache_bytes(n_layers, n_kv_heads, d_head, seq_len,bytes_per_elem=2, batch=1):# The factor of 2 accounts for separate K and V cachesreturn 2 * n_layers * n_kv_heads * d_head * seq_len * bytes_per_elem * batch
Take a model with 32 layers, 128-dimensional heads, a sequence length of 4096, and fp16 precision:
- With 8 KV heads (GQA), the cache for a single sequence is about 0.5 GB.
- With 32 KV heads (MHA), the cache grows to about 2 GB.
For the same model, the attention type alone can create a 4x difference in memory requirements for long-context inference.
4. Feed-Forward Networks and Mixture of Experts (MoE)
4.1 Dense Feed-Forward Networks
Modern feed-forward layers typically use the SwiGLU activation, with three matrices: gate, up projection, and down projection. The parameter count is roughly 3 × d_model × d_ff, where d_ff is the intermediate dimension, usually a multiple of d_model.
4.2 Mixture-of-Experts Architecture
Mixture of Experts (MoE) replaces a single feed-forward layer with multiple parallel feed-forward networks (experts). A router selects the top-k highest-scoring experts for each token, and only those experts participate in the computation.
This architecture introduces two key metrics:
- Total parameters: the sum of all experts and shared components, which determines storage requirements.
- Active parameters: the parameters actually used to compute each token, which determine per-step inference cost.
For example, if a layer has 8 experts and each token selects 2, the activation ratio of that layer’s feed-forward portion is 25%. Total parameters far exceeding active parameters is a hallmark of MoE models. When reading specifications, you must distinguish between these two numbers and not treat total parameters as the compute cost.
The router also needs a load-balancing mechanism to prevent a few experts from being overused, typically implemented via auxiliary losses or bias terms.
5. Normalization, Positional Encoding, and Other Details
- Normalization: RMSNorm removes mean centering and is slightly cheaper to compute than LayerNorm. It is widely used in large models.
- Positional encoding: Rotary Position Embedding (RoPE) injects relative position information by applying rotational transformations to Q and K, making it easier to extrapolate to longer contexts. A common way to extend context length is to interpolate the positional frequencies and continue training briefly on longer texts.
- Vocabulary and embeddings: a larger vocabulary means a larger embedding matrix, but better coverage of multilingual text and code. Input embeddings and the output layer can share weights (tied embeddings) to reduce parameter count.
- Activation functions: gated activations such as SwiGLU deliver more stable results than plain ReLU or GELU at the same parameter budget, which is why they are widely adopted.
6. How to Estimate Parameter Counts
6.1 Formula for Dense Models
Let V be the vocabulary size, d the hidden dimension, L the number of layers, d_ff the feed-forward intermediate dimension, and d_kv the combined dimension of all KV heads. Ignoring small components such as normalization layers, the parameter count is approximately:
- Embedding layer: V × d
- Attention per layer: Wq and Wo are each d × d; Wk and Wv are each d × d_kv; total 2d² + 2d·d_kv
- Feed-forward per layer: 3 × d × d_ff
- Output layer: V × d if embeddings are not tied
6.2 Code Implementation
def estimate_params(vocab, d_model, n_layers, d_ff,n_heads, n_kv_heads, tied=False):d_head = d_model // n_headsd_kv = n_kv_heads * d_headembed = vocab * d_modelattn = 2 * d_model * d_model + 2 * d_model * d_kv # Wq, Wo, Wk, Wvffn = 3 * d_model * d_ff # gate, up, downhead = 0 if tied else vocab * d_modelreturn embed + n_layers * (attn + ffn) + head
6.3 A Worked Example with a Demonstration Configuration
Assume a configuration with V = 32000, d = 4096, L = 32, d_ff = 11008, MHA (32 KV heads), and untied output embeddings:
- Attention per layer: 4 × 4096² = 67,108,864
- Feed-forward per layer: 3 × 4096 × 11008 = 135,266,304
- Total per layer: 202,375,168; across 32 layers, about 6.476 × 10⁹
- Embedding and output layers: 2 × 32000 × 4096 = 262,144,000
- Grand total: about 6.74 × 10⁹, or roughly 6.7B parameters
This configuration is a hypothetical demonstration value used to illustrate the calculation method.
6.4 Rough Memory Estimation
Weight memory is approximately the parameter count multiplied by bytes per parameter. In fp16 (2 bytes per parameter), the weights of the configuration above occupy about 13.5 GB. Inference also requires additional headroom for the KV Cache, activations, and framework overhead, so actual usage is typically higher.
Quantization reduces weight memory. At 8-bit precision, weights are roughly halved; at 4-bit, they shrink to about a quarter. Quantization introduces some accuracy loss, which should be evaluated on your target tasks.
7. How to Read Specifications in Technical Reports
When reading a model’s technical report, check the following items one by one:
- Total vs. active parameters: distinguish storage cost from compute cost.
- Number of layers, hidden dimension, attention heads, and KV heads: needed to estimate weights and cache size.
- Attention type: MHA, GQA, or MLA determines memory pressure for long contexts.
- Number of experts and top-k: applicable only to MoE models.
- Context length and positional encoding method: determines how much text the model can handle.
- Vocabulary size and whether embeddings are tied: affects parameter distribution.
- Training data scale and precision: influences the capability ceiling, but reported numbers must be interpreted alongside the evaluation methodology.
Keep in mind that parameter count does not equal capability. Data quality, training methodology, and post-training alignment matter just as much. For models of the same scale, differences in architecture and training can produce noticeably different results, so never compare models on parameter numbers alone.
8. Practical Recommendations
- Budget first: work backward from your memory or hardware constraints to determine the weight precision and context length you can support.
- Prioritize the KV Cache: in long-context scenarios, attention type often determines peak memory more than parameter count does.
- Match the model to the scenario: for latency-sensitive services, models with fewer active parameters have an advantage; for quality-critical offline tasks, a larger total parameter count may be acceptable.
- Evaluate before deciding: benchmark on datasets close to your actual workload rather than relying on specification sheets.
- For cloud deployments, choose GPU instances based on memory specifications and store model weights in object storage for unified management. Platforms such as Baidu AI Cloud provide general-purpose compute and storage capabilities that can support this kind of deployment; specific choices should be based on the official documentation and your own benchmark results.
Understanding the relationship between architecture and parameter count helps developers make more reliable decisions in model selection, resource planning, and inference optimization.
