LLM Architecture and Parameter Scale Explained: A Practical Guide

    This article explains how mainstream large language models are structured and what parameter counts actually mean. It covers decoder-only Transformer fundamentals, attention variants (MHA, MQA, GQA), feed-forward networks and Mixture of Experts, parameter estimation for dense and MoE models, memory and KV cache sizing, the relationship between scale and capability, and common engineering practices for deployment—helping engineers turn parameter numbers into actionable storage, compute, and cache cost estimates.

    1. Why Architecture Comes Before Parameter Count

    Parameter count is the easiest number to obtain, yet the hardest to interpret directly. Two models with the same nominal parameter count can differ dramatically in inference speed, memory footprint, and capability. The reason lies in how the parameters are organized: some models activate all parameters on every forward pass, while others activate only a small fraction; some keep history in every attention head, while others compress the cache by sharing keys and values.

    Therefore, when evaluating a large language model, look at the architecture first and the scale second. Architecture determines how parameters are distributed, how compute grows, and where memory pressure lands. Only with these relationships in mind do scale numbers become meaningful.

    2. The Basic Skeleton of Mainstream Architectures

    Nearly all general-purpose LLMs today use a decoder-only Transformer architecture. The model is a stack of identical layers, each containing two core submodules: a self-attention module and a feed-forward network (FFN). Input text is tokenized and mapped to vectors, transformed layer by layer, and finally passed through an output layer that predicts the probability distribution of the next token.

    Each submodule is typically wrapped with residual connections and normalization layers. Most mainstream implementations use pre-norm, where normalization is applied before the submodule computation, which improves training stability in deep networks. Among normalization methods, RMSNorm is widely adopted for its low computational cost and stable behavior.

    2.1 The Evolution of Attention Mechanisms

    Self-attention lets each token read relevant information from the context. Standard Multi-Head Attention (MHA) maintains separate query, key, and value projection matrices for every head. This is expressive, but at inference time the keys and values of every head must be cached, so memory overhead grows linearly with the number of heads.

    To reduce this cost, the industry commonly uses the following variants:

    • Multi-Query Attention (MQA): All query heads share a single set of keys and values. The cache is minimal, but the quality loss is relatively noticeable.
    • Grouped-Query Attention (GQA): Query heads are grouped, and each group shares one set of keys and values. It strikes a balance between cache size and quality, and is currently the most widely adopted approach.
    • Sliding Window Attention: Each token only attends to a fixed-length recent window, bounding compute and cache growth as sequence length increases. It suits long-text scenarios but must be combined with other mechanisms to retain long-range information.
    • Sparse and Linear Attention: These reduce computational complexity through sparse patterns or kernel approximations. They are still under active research, and real-world adoption requires evaluating both quality and engineering maturity.

    2.2 Feed-Forward Networks and Mixture of Experts

    The feed-forward network typically holds the majority of parameters within a layer. The standard design expands the dimension to roughly four times the hidden size, applies a nonlinear activation, and projects back to the original dimension.

    Mixture of Experts (MoE) is a common way to scale up total parameter count. It replaces the FFN with multiple parallel “expert” subnetworks, and a router selects a small number of experts for each token. This way the model’s total parameters can be very large, while the parameters actually activated per token are only a fraction.

    Three key metrics define an MoE layer:

    1. Total number of experts: determines total parameters and model capacity.
    2. Number of experts activated per token (top-k): determines per-inference compute.
    3. Load-balancing strategy: prevents a few experts from being overused while others remain undertrained.

    A router typically scores every expert for each token, picks the k highest-scoring ones, and computes a weighted sum of their outputs. Load balancing is usually implemented via an auxiliary loss or bias adjustment.

    1. # Simplified routing illustration, for concept only
    2. def route(token_hidden, router_weight, k):
    3. logits = token_hidden @ router_weight # one score per expert
    4. top_idx = logits.topk(k).indices # select the top-k experts
    5. weights = logits[top_idx].softmax(dim=-1) # normalize into combination weights
    6. return top_idx, weights

    2.3 Positional Encoding and Long Context

    Transformers are inherently unaware of token order, so positional encoding is required. Rotary Position Embedding (RoPE) is the current mainstream approach: it applies rotational transforms to query and key vectors so that attention scores depend only on relative positions.

    Long-context capability typically relies on three things working together: the extrapolation design of the positional encoding, long-text data used during training, and cache management at inference time. Simply extending the positional encoding’s coverage is not enough to guarantee long-text quality; the model’s actual performance on long-range retrieval and reasoning tasks must also be verified.

    3. What Parameter Scale Actually Means

    When discussing parameter scale, several concepts must be distinguished.

    • Total parameters: The number of all trainable weights, including embeddings, attention, FFNs, and experts.
    • Active parameters: The number of parameters that actually participate in computing a single token. For dense models the two are identical; for MoE models, active parameters are significantly smaller than the total.
    • Non-embedding parameters: The parameter count excluding the vocabulary embedding and output layer, often used to compare the core compute of different architectures.

    A common mistake is estimating inference cost directly from total parameters. In reality, inference compute is mainly determined by active parameters, while memory footprint is mainly determined by total parameters. The two must be estimated separately.

    3.1 Estimating Parameters of Dense Models

    With standard MHA and a 4x-expansion FFN, a single layer has roughly 12d² parameters (where d is the hidden dimension), and adding the vocabulary embedding gives a rough total. The following function provides a quick estimate:

    1. def dense_params(n_layers, d_model, vocab, ffn_mult=4):
    2. attn = 4 * d_model * d_model # Q, K, V, O projections
    3. ffn = 2 * ffn_mult * d_model * d_model # up and down linear layers
    4. embed = vocab * d_model # vocabulary embedding
    5. return n_layers * (attn + ffn) + embed
    6. # Example config: 80 layers, hidden size 8192, vocab 128000
    7. print(dense_params(80, 8192, 128000) / 1e9) # about 65.5 B

    3.2 Total vs. Active Parameters in MoE Models

    MoE models require computing total and active parameters separately. The example below uses a hypothetical configuration and does not correspond to any specific model:

    1. def moe_params(n_layers, d_model, n_experts, top_k, expert_mult, vocab):
    2. attn = 4 * d_model ** 2
    3. expert = 2 * expert_mult * d_model ** 2
    4. total = n_layers * (attn + n_experts * expert) + vocab * d_model
    5. active = n_layers * (attn + top_k * expert) + vocab * d_model
    6. return total, active
    7. # Hypothetical config: 32 layers, hidden size 4096, 64 experts, top-8 active
    8. total, active = moe_params(32, 4096, 64, 8, 2, 128000)
    9. print(total / 1e9, active / 1e9) # about 140.1 B and 19.9 B

    As this example shows, total parameters are about seven times the active count. Model capacity comes from the total, while per-inference cost is close to that of a dense model of roughly twenty billion parameters. This is the core trade-off of MoE design: exchanging larger storage for controlled compute.

    4. Estimating Memory and Cache

    When deploying a model, memory demand comes mainly from three parts: model weights, the key-value cache (KV cache), and runtime intermediate activations.

    4.1 Weight Footprint

    Weight footprint equals total parameter count multiplied by bytes per parameter. At common precisions, FP16 or BF16 uses 2 bytes per parameter, INT8 uses 1 byte, and INT4 uses roughly 0.5 bytes.

    Take a 7B-parameter dense model as an example: weights take about 14 GB in FP16 and about 7 GB in INT8. When parameter counts reach tens of billions, the weights alone require multiple high-memory accelerators to host.

    Note that quantization only reduces weight footprint, not the KV cache. Quantization also introduces accuracy loss, which must be evaluated on the specific task.

    4.2 KV Cache

    KV cache size can be estimated with the following formula:

    1. def kv_cache_gib(n_layers, n_kv_heads, head_dim, seq_len, batch, bytes_per=2):
    2. total_bytes = 2 * n_layers * n_kv_heads * head_dim * seq_len * batch * bytes_per
    3. return total_bytes / 2**30
    4. # 80 layers, 8 KV heads, head_dim 128, context 32768, batch 1, FP16
    5. print(kv_cache_gib(80, 8, 128, 32768, 1)) # about 10.0 GiB
    6. # Same config with 64 KV heads (standard MHA)
    7. print(kv_cache_gib(80, 64, 128, 32768, 1)) # about 80.0 GiB

    The two results differ by a factor of eight, showing that attention variants have an enormous impact on long-context deployment. Batch size and context length also scale the cache linearly, so services with high concurrency and long texts tend to exhaust memory first.

    4.3 Compute and Bandwidth

    The FLOPs of a forward pass are roughly proportional to active parameters—about two multiply-accumulate operations per active parameter per token. The generation phase is usually limited by memory bandwidth, because generating each token requires reading the weights and cache once. As a result, although MoE models have low compute, they can still be bottlenecked by weight-read speed at small batch sizes.

    5. Parameter Scale vs. Actual Capability

    Parameter scale correlates with capability, but not linearly. Training data quality and quantity, training methodology, post-training alignment and instruction tuning, and architectural details all affect final performance. Two models of the same size may excel at different tasks.

    When selecting a model, evaluate along these dimensions rather than fixating on the parameter number:

    • Task type: Code generation, long-document QA, multi-turn dialogue, and structured extraction demand different capabilities.
    • Latency and throughput: Interactive applications care about time to first token; batch processing cares more about throughput per unit time.
    • Cost structure: Memory, compute, and bandwidth usage must all be accounted for.
    • Context requirements: Long context depends on cache design; test directly at the target length.
    • Maintainability: Model update cadence, toolchain maturity, and team familiarity also affect long-term cost.

    6. Common Techniques in Engineering Deployment

    When a single device cannot hold the model, parallelism techniques are typically required:

    • Tensor parallelism: Splits matrices within a layer across multiple devices; suited to environments with high-bandwidth interconnects.
    • Pipeline parallelism: Assigns different layers to different devices, using micro-batches to hide bubble overhead.
    • Expert parallelism: Places different MoE experts on different devices; routing must handle cross-device data dispatch, and communication overhead is the main bottleneck.

    On the inference side, quantization, continuous batching, and cache reuse can further improve throughput. Quantization should be validated for accuracy on the target task; continuous batching must handle scheduling issues caused by varying request lengths; and cache reuse requires attention to isolation and security between requests.

    7. Practical Recommendations

    1. Determine context length and concurrency targets first, then compute the memory required for cache and weights.
    2. Distinguish total from active parameters, and evaluate storage cost and compute cost separately.
    3. When comparing models, confirm the attention variant and vocabulary size—avoid comparing on parameter numbers alone.
    4. Run small-scale evaluations on real business data, recording quality, latency, and cost.
    5. Keep fallback paths for quantization and parallelism schemes to avoid being constrained by a single hardware configuration after launch.

    Once the architecture is understood, parameter scale is no longer just a number—it becomes an engineering metric that can be decomposed into storage, compute, and cache costs.