LLM Architecture and Parameter Scale: A Complete Technical Guide
This article provides a systematic breakdown of modern large language model (LLM) architecture and parameter scaling. It covers the three main parameter sources (embedding, attention, and feed-forward layers), the evolution of attention mechanisms from multi-head attention to grouped-query attention and sliding window attention, Mixture-of-Experts design with load balancing and shared experts, rotary position embeddings and long-context extension, step-by-step parameter counting formulas with code examples for dense and MoE models, memory estimation for weights and KV cache, training data scaling heuristics, and practical guidance for selecting model sizes in real deployments.
1. Defining the Basics: What Makes Up an LLM
Most mainstream LLMs today use a decoder-only Transformer architecture. The model takes a sequence of text tokens, converts them into vectors through an embedding layer, processes them through a stack of layers that progressively extract contextual information, and finally maps the result back to a probability distribution over the vocabulary via an output layer. To understand model scale, you first need to distinguish three sources of parameters.
1. Embedding and output layers. The input embedding matrix has a size of vocabulary size × hidden dimension. The output side usually has a projection matrix of the same size. The two can share weights or be stored independently. The larger the vocabulary, the more parameters this part contributes.
2. Attention layers. Each layer’s attention module contains four projection matrices: query, key, value, and output. They compute the relevance between tokens.
3. Feed-forward network (FFN) layers. Each layer’s FFN applies a nonlinear transformation to the representation at every position. In most models, the FFN accounts for the largest share of parameters and is the primary determinant of model capacity.
Normalization layers and positional encodings contain negligible parameters and are usually ignored in estimates.
2. The Evolution of Attention: Starting from the Memory Bottleneck
2.1 Multi-Head Attention and the Cost of KV Cache
In standard multi-head attention (MHA), each head has its own keys and values. During autoregressive generation, the model must cache the keys and values of past tokens—known as the KV cache. Cache size scales linearly with the number of layers, attention heads, per-head dimension, and sequence length. In long-context scenarios, the KV cache often exhausts GPU memory before the model weights do.
2.2 Grouped-Query Attention
Grouped-query attention (GQA) lets multiple query heads share a single set of keys and values. With 32 query heads and 8 key-value heads, the KV cache is only a quarter of that of standard MHA, while model accuracy typically degrades only slightly. This approach is simple to implement and is one of the most widely adopted attention optimizations today.
2.3 Sliding Window and Sparse Attention
Sliding window attention restricts each token to attending only to the most recent positions, reducing attention complexity from quadratic to linear in sequence length. In practice, sliding window layers are often interleaved with global attention layers to balance local detail with long-range dependencies.
2.4 Low-Rank Compressed Key-Value Representations
Another approach projects keys and values into a low-dimensional latent space for storage and reconstructs them at use time. This compresses the cache without reducing the number of query heads. The trade-off is additional projection computation, requiring a balance between memory and compute.
3. Feed-Forward Networks and Mixture of Experts
3.1 Dense Feed-Forward Networks
In a dense FFN, every token passes through the same set of parameters. A common implementation is a gated linear unit structure with three matrices: gate projection, up projection, and down projection. With a hidden dimension of 4096 and an intermediate dimension of 14336, a single FFN layer contains roughly 176 million parameters.
3.2 The Basic Idea of Mixture of Experts
Mixture of Experts (MoE) splits the FFN into multiple experts. Each token activates only a few of them, with a router deciding which. This allows the total parameter count to be very large while the number of parameters activated per forward pass stays small.
Below is a simplified illustration of top-k routing:
def moe_forward(x, router_weights, experts, k=2):# x: [tokens, d_model]logits = x @ router_weights # [tokens, num_experts]probs = softmax(logits, axis=-1)topk_probs, topk_idx = top_k(probs, k) # select k experts per tokentopk_probs = topk_probs / topk_probs.sum(axis=-1, keepdims=True)output = zeros_like(x)for expert_id, expert in enumerate(experts):mask = (topk_idx == expert_id) # which tokens selected this experttoken_ids = mask.any(axis=-1).nonzero()if token_ids.size == 0:continueweight = (topk_probs * mask).sum(axis=-1)[token_ids]output[token_ids] += weight[:, None] * expert(x[token_ids])return output
Production implementations use batched dispatch-and-combine operations rather than this kind of inefficient per-expert loop.
3.3 The Load Balancing Problem
If the router consistently assigns tokens to a small number of experts, some experts sit idle and compute becomes unbalanced. Common mitigations include adding an auxiliary load-balancing term to the loss function, or setting a capacity limit per expert so that overflow tokens are handled by other experts or dropped. Design requires a trade-off between model quality and training stability.
3.4 Shared Experts
Some designs retain a small number of always-activated shared experts alongside routed experts to capture general knowledge, while routed experts specialize in particular patterns. This structure reduces knowledge redundancy across experts.
4. Positional Encoding and Long Context
4.1 Rotary Position Embedding
Rotary position embedding (RoPE) encodes positional information as a rotation applied to query and key vectors. It makes attention scores naturally depend on relative distance and is currently the mainstream positional representation.
4.2 Extending from Short to Long Context
Models are typically trained mainly on shorter sequences first, then the sequence length is gradually extended. Common techniques include adjusting the RoPE base frequency or interpolating position indices. After extension, continued training on long-document data is still required, and retrieval-style tasks should be used to verify that the model can genuinely exploit distant information.
4.3 The Engineering Cost of Long Context
The longer the context, the larger the KV cache and the higher the prefill compute. The formula for estimating the KV cache of a single sequence is:
KV cache bytes = 2 × layers × KV heads × head dimension × sequence length × bytes per element
For example, with 32 layers, 8 KV heads, a head dimension of 128, a sequence length of 8192, and 16-bit floating point:
2 × 32 × 8 × 128 × 8192 × 2 = 1,073,741,824 bytes ≈ 1 GiB
This means a single 8K sequence requires about 1 GiB of cache. Under batched inference, memory pressure multiplies accordingly.
5. How Parameter Counts Are Calculated
5.1 Estimating Parameters of a Dense Model
Let the hidden dimension be d, the number of layers L, vocabulary size V, FFN intermediate dimension d_ff, and the GQA key-value dimension d_kv. Ignoring normalization layers, the total parameter count is approximately:
- Input embedding: V × d
- Output projection (when weights are not tied): V × d
- Attention per layer: query and output each d × d; key and value each d × d_kv
- FFN per layer (gated structure): 3 × d × d_ff
The following example configuration verifies the calculation. This configuration is for demonstration only and does not correspond to any actual released model:
def dense_params(d, L, V, d_ff, d_kv, tied=False):embed = V * dhead = 0 if tied else V * dattn = 2 * d * d + 2 * d * d_kvffn = 3 * d * d_ffreturn embed + head + L * (attn + ffn)total = dense_params(d=4096, L=32, V=128000, d_ff=14336, d_kv=1024)print(f"{total / 1e9:.2f} B") # outputs approximately 8.03 B
The result is roughly 8 billion parameters.
5.2 Total vs. Active Parameters in MoE Models
MoE models require distinguishing two concepts. The total parameter count includes all expert weights and determines knowledge capacity and storage requirements. The active parameter count includes only the parameters each token actually passes through and determines per-step compute.
Following the same approach, assume 64 experts per layer, each with an intermediate dimension of 2048, 8 experts activated per token, and standard multi-head attention:
d, L, V = 4096, 32, 128000num_experts, top_k, d_e = 64, 8, 2048attn = 4 * d * d # standard multi-head attentionexpert = 3 * d * d_e # parameters per experttotal = V * d * 2 + L * (attn + num_experts * expert)active = V * d * 2 + L * (attn + top_k * expert)print(f"Total {total / 1e9:.1f} B, active {active / 1e9:.1f} B")# Output: Total 54.7 B, active 9.6 B
The total parameter count is about 5.7× the active count. The size number in a model’s name usually refers to total parameters, while inference speed is closer to what the active parameter count implies. When reading model specifications, confirm which figure is being quoted.
5.3 Converting Parameter Count to Memory
The memory required to store weights is approximately the parameter count multiplied by bytes per parameter. With 16-bit floating point, each parameter takes 2 bytes.
- An 8B dense model requires about 16 GB for weights
- A 54.7B total-parameter MoE model requires about 109 GB for weights
- With 8-bit integer quantization, the above is roughly halved; with 4-bit quantization, roughly a quarter
Actual deployment also requires reserving space for the KV cache, activations, and runtime overhead, so total requirements are typically higher than the weight-only estimate.
6. Training Stages and Scale Selection
6.1 Pretraining Data Volume
A common industry heuristic: under compute-optimal training, the number of training tokens should be roughly 20× the model’s parameter count. This ratio comes from fitting results of several large-scale experiments and is not a strict law. In practice, projects may also choose a smaller model trained on more data when inference cost is a concern.
6.2 Post-Training
After pretraining, models typically undergo instruction tuning and preference alignment so that outputs better meet task requirements and safety standards. The data quality and pipeline design of post-training have a large impact on the final experience—sometimes more than simply adding parameters.
7. Recommendations for Model Selection and Deployment
When choosing a model size, evaluate in the following order:
- Clarify the task type. Classification, extraction, and simple Q&A usually do not require the largest models. Complex reasoning, code generation, and long-document analysis demand more capacity.
- Estimate your memory budget. Start by computing the weight footprint
