Modern LLM Architecture Explained: A Deep Dive into Parameter Counts and Design
This article breaks down the structure of modern large language models (LLMs), from the overall Decoder-Only Transformer skeleton to its key components—RMSNorm, RoPE, SwiGLU, grouped/latent attention, and Mixture-of-Experts (MoE). It shows how to estimate parameter counts for both dense and MoE models, explains why "activation parameters" matter more than total parameters, and connects architecture choices to real engineering costs: GPU memory, KV Cache, training parallelism, and inference optimization. By the end, you'll understand the triangle of capability, cost, and latency and how to apply these principles to model selection, capacity planning, and deployment.
Note: All model names, version numbers, and parameter scales mentioned in this article are illustrative examples used to explain structural principles and calculation methods. They do not represent the actual configuration of any specific product.
1. Introduction: Why Understanding Structure Matters More Than Memorizing Parameters
Over the past two years, the number and iteration speed of large language models has far exceeded expectations. When comparing models, many readers first focus on “how many parameters it has.” But remembering a single number rarely tells you anything about a model’s actual capability, resource consumption, or fit for a given use case. There are three main reasons:
- Structures differ significantly within the same scale. Among dense models of the same ~70 billion parameter class, subtle differences in normalization, feed-forward design, or attention can lead to different training stability and inference efficiency.
- Sparsification changes what “parameters” even mean. For Mixture of Experts (MoE) models, the total parameter count and the activation parameters (the parameters that actually participate in computation for each token) can differ by more than tenfold. So “200 billion parameters” is not equivalent to a dense 200-billion-parameter model.
- Deployment cost depends jointly on memory, bandwidth, and parallelism strategy. Models of the same size can have completely different deployment costs depending on hardware configuration and context length.
For these reasons, this article systematically walks through the structure and scale of modern LLMs in the following order: overall skeleton → key components → how to calculate parameter scale → engineering impact → selection advice.
2. The Overall Skeleton: Why Decoder-Only Transformers Became Mainstream
Today, the vast majority of general-purpose LLMs adopt a Decoder-Only Transformer architecture, which is clearly distinct from earlier BERT-style encoder and encoder-decoder designs. Its core characteristics are:
- The input is a sequence of tokens; each token is first tokenized and mapped to an embedding vector;
- The sequence passes through N Transformer Blocks with identical structure;
- Each block consists of normalization layers, a self-attention layer, a feed-forward network layer, and residual connections;
- Finally, after a normalization layer and an output linear layer, the model predicts the next token.
A schematic of the structure is shown below:
Token IDs│▼Token Embedding ──────────────┐│ │ (some models share weights with the output layer)▼ │┌──────────────────────────┐ ││ RMSNorm │ ││ Self-Attention (GQA) │ ││ + residual connection │ ││ RMSNorm │ ││ FFN (SwiGLU) / MoE │ ││ + residual connection │ │└──────────────────────────┘ ││ × N layers │▼ │RMSNorm ─────────────────────┘│▼Linear layer → Softmax → next token
Below is the approximate parameter count for each layer. Note: implementation details (such as whether bias terms are used) introduce minor deviations, so always refer to each model’s published technical report as the source of truth.
- Embedding and output layers: parameters are roughly
V × d, where V is the vocabulary size (commonly from tens of thousands to over two hundred thousand) and d is the hidden dimension. Some models bind the input embedding and output projection weights (weight tying), saving one copy of the parameters; an untied version typically adds anotherV × d. - Self-attention layer: standard multi-head attention includes four projection matrices—Q, K, V, and O—each on the order of
d × d, totaling roughly4d². - Feed-forward layer: dense models commonly use two fully connected layers, giving roughly
2d × d_ffparameters. As gated structures like SwiGLU have become widespread, the count often becomes3d × d_ff(three matrices), and the intermediate dimension d_ff is adjusted accordingly. - Normalization layers: these contain only a small number of scaling parameters and can be ignored.
As an example, consider a dense model with a hidden dimension of 4096 and 32 layers:
- parameters per layer are roughly
12 × 4096² ≈ 200 million; - the entire backbone is roughly
6.4 billion, and adding the embedding and output layers brings the total to about 7 billion.
This is exactly one of the common structural configurations behind the industry’s “about 7 billion parameters.”
3. Key Components: The “Standard Upgrades” of Modern LLMs
3.1 Normalization: RMSNorm + Pre-Norm
Traditional Transformers use LayerNorm, which involves computing the mean and variance plus a learnable bias. Modern LLMs widely adopt RMSNorm, which scales only by the root mean square without mean centering:
import torchimport torch.nn as nnclass RMSNorm(nn.Module):def __init__(self, dim, eps=1e-6):super().__init__()self.weight = nn.Parameter(torch.ones(dim))self.eps = epsdef forward(self, x):# RMS-only normalization: fewer parameters and less compute than LayerNormnorm = x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)return self.weight * norm
The benefits are simpler computation and better numerical stability. In addition, modern LLMs commonly use Pre-Norm (normalizing before each sublayer), so the residual path preserves an identity mapping. This helps with training deep networks and maintaining stability during large-scale parallel training.
3.2 Feed-Forward Layer: Gated Activations Like SwiGLU
Early Transformers used a feed-forward network (FFN) of “two linear layers + ReLU/GELU.” Modern LLMs have largely upgraded to the Gated Linear Unit (GLU) family, with SwiGLU as the typical representative:
# SwiGLU: project the input into two paths; one is passed through the Swish# activation, then multiplied element-wise with the otherdef swiglu_forward(x, W_gate, W_up, W_down):return (F.silu(x @ W_gate) * (x @ W_up)) @ W_down
Because SwiGLU introduces a third projection matrix, the intermediate dimension is usually adjusted to about 2/3 of the original (e.g., 8/3×d) to keep the parameter count roughly the same. Its representational power is stronger than a plain GELU-FFN, making it a common choice in current general-purpose LLMs.
3.3 Positional Encoding: RoPE and Long-Context Extension
Self-attention is inherently position-agnostic, so positional information must be injected explicitly. Early approaches used absolute positional encodings (sinusoidal or learnable). Modern LLMs widely adopt Rotary Position Embedding (RoPE): it applies position-dependent rotations to the Query and Key by rotating complex-valued vectors, so attention scores naturally depend on relative position and extrapolate more easily.
To further extend context length, common approaches include:
- scaling different frequency dimensions of RoPE by different ratios (position interpolation / frequency-scaling methods);
- adjusting the temperature coefficient and enlarging the training context length;
- combining sliding-window attention, sparse attention, and similar mechanisms to reduce compute for long sequences.
3.4 Attention Structure: MHA → MQA / GQA, and KV Compression
In traditional Multi-Head Attention (MHA), each Query head has its own independent K and V heads. During autoregressive decoding, the Key and Value of all historical tokens must be cached (the KV Cache), whose memory overhead grows linearly with context length—one of the main bottlenecks for long-context inference.
Common optimizations in modern LLMs:
- MQA (Multi-Query Attention): all Query heads share a single set of K and V, significantly shrinking the KV Cache, though quality may be slightly affected;
- GQA (Grouped-Query Attention): Query heads are grouped to share K and V. It is the mainstream compromise between quality and efficiency—for example, 32 Query heads split into 8 groups of 4, where each group of 4 shares one set of K and V;
- MLA (Multi-head Latent Attention): compresses K and V into a low-dimensional latent vector for caching, then up-projects during inference, greatly compressing the KV Cache while retaining strong modeling capability.
KV Cache memory can be estimated with the following formula:
KV memory ≈ 2 × layers × cached elements per token per layer × sequence length × batch size × precision bytes
The coefficient is 2 because there is one copy each for K and V. For example, for a 64-layer model that caches 4096 elements per token per layer at FP16 precision, a single sequence of 1024 tokens occupies roughly 2 × 64 × 4096 × 1024 × 2 ≈ 1 GB of memory, and a 128K context needs about 128 GB—and that’s not counting the weights themselves.
3.5 Sparsification: MoE and “Activation Parameters”
In a dense model, every token passes through all parameters. When a model scales to hundreds of billions or trillions of parameters, compute cost grows linearly. The MoE (Mixture of Experts) structure replaces the feed-forward layer with multiple expert networks + a routing network (Router):
- Each token is routed by the router to the Top-K experts (commonly K=1 or 2) and passes through only the selected experts’ parameters;
- It is often combined with “shared expert” or “fine-grained expert” designs;
- During training, a load-balancing loss is used to avoid routing collapse.
A schematic implementation is shown below:
# Each expert is an independent FFN; the Router picks the Top-K experts per tokenclass MoELayer(nn.Module):def __init__(self, d_model, n_experts, top_k=2):super().__init__()self.router = nn.Linear(d_model, n_experts, bias=False)self.top_k = top_kself.experts = nn.ModuleList([FFN(d_model) for _ in range(n_experts)])def forward(self, x):scores = torch.softmax(self.router(x), dim=-1)topk_scores, topk_idx = scores.topk(self.top_k, dim=-1)# Only selected experts run the forward pass; the rest contribute nothing to this tokenout = torch.zeros_like(x)for slot in range(self.top_k):for expert_id in topk_idx[:, slot].unique():mask = topk_idx[:, slot] == expert_idout[mask] += topk_scores[mask, slot].unsqueeze(-1) * self.experts[expert_id](x[mask])return out
The essence of MoE is trading parameters for compute: the total parameter count is large (determining memory and knowledge capacity), but each token activates only a small portion of them (determining compute). This also explains why many “hundred-billion-parameter” models actually have only a few billion to a few tens of billions of activation parameters.
4. How to Calculate Parameter Scale: From Billions to Trillions
4.1 The Empirical Formula for Dense Models
For a Decoder-Only Transformer with hidden dimension d and L layers, the backbone parameters can be approximated as:
N ≈ 12 × L × d² (standard attention structure)
Adding the token embeddings and output layer: N_total ≈ 12Ld² + 2Vd (or 12Ld² + Vd when weights are tied).
Using GQA (fewer K/V heads) or SwiGLU (three projection matrices, with the intermediate dimension designed around 8/3d) changes the coefficient slightly, but the order of magnitude stays the same. For example:
- d=4096, L=32, V≈150K: backbone ~6.4 billion, embeddings ~1.2 billion (untied), total ~7.6 billion;
- d=8192, L=80, V≈150K: backbone ~64.4 billion, embeddings ~2.4 billion (untied), total ~67 billion.
4.2 Parameter Calculation for MoE Models
For MoE models, you need to distinguish the “total” and the “activated” parameter counts:
- Total: the sum of all experts’ parameters, growing linearly with the number of experts;
- Activated: estimated by the number of experts each token passes through, usually only a single-digit percentage up to about a quarter of the total.
For example (illustrative numbers): a model has 64 layers, most of whose FFN layers are MoE-structured, with 256 experts and 8 activated per token. Each layer’s FFN intermediate dimension is 2048 and d_model is 7168, so:
- a single expert has about
3 × 7168 × 2048 ≈ 44 millionparameters; - a single MoE layer has about
256 × 44 million ≈ 11.2 billiontotal parameters, with activated parameters around8 × 44 million ≈ 350 million; - if roughly 58 of the 64 layers are MoE, the MoE portion totals about 650 billion, and adding attention, embeddings, and other parts pushes the total into the hundreds-of-billions scale, while the activated parameters stay only in the tens-of-billions range.
4.3 Parameter Scale Map (Illustrative)
| Scale range | Typical form | Main use cases | Deployment difficulty |
|---|---|---|---|
| Below 1B | Small dense models | On-device, lightweight tasks | Low |
| 1B–10B | Dense models | General dialogue, content generation | Medium |
| 10B–100B | Dense or MoE | Complex reasoning, long context | High |
| 100B–1T | Large-scale MoE | Frontier general capabilities | Very high |
As we can see, bigger is not always better. Parameter scale is strongly tied to the scenario, latency, and cost.
5. From Structure to Engineering: The Real Cost of Parameter Scale
5.1 Estimating Memory Usage
Inference memory is mainly composed of three parts:
- Weights: about 2 bytes per parameter in FP16, and about 0.5 bytes in INT4. A 67-billion-parameter model needs about 134 GB just for weights (FP16), which a single GPU can hardly hold;
- KV Cache: grows linearly with context length and concurrency; in long-context scenarios it can even exceed the weights themselves;
- Activations and runtime overhead: batch size and framework implementation both affect peak usage.
A rough estimate: memory ≈ weights + KV Cache + activation and fragmentation overhead. In practice, it’s recommended to reserve a 20%–30% margin.
5.2 Training Compute and Parallelism Strategies
The forward + backward compute for training a dense model is roughly 6 × N × D FLOPs (N is the parameter count, D is the number of training tokens). Training a hundred-billion-parameter model on trillion-scale tokens corresponds to on the order of 6 × 10²³ FLOPs, requiring a cluster of over a thousand GPUs and several weeks.
To support large-scale training, mainstream solutions combine multiple parallelism strategies:
- Data Parallelism (DP): splits the data, using ZeRO/FSDP-style optimizer-state sharding to reduce memory;
- Tensor Parallelism (TP): splits each layer’s matrices by rows/columns across multiple GPUs; communication-intensive, best suited to high-speed intra-node interconnects;
- Pipeline Parallelism (PP): splits layers across different devices, requiring management of the bubble problem;
- Sequence Parallelism (SP): splits along the sequence dimension to reduce activation memory for long sequences;
- Expert Parallelism (EP): distributes experts across devices for MoE models, requiring handling of routing-induced communication overhead.
5.3 Inference Serving: Throughput, Latency, and Quantization
- Quantization: INT8/INT4 quantization can significantly compress weight memory but may cause accuracy loss, so it needs validation with benchmarks;
- Continuous Batching: combines tokens from different requests into a dynamic batch to improve GPU utilization;
- Speculative Decoding: uses a smaller model or draft tokens to speed up generation from a large model;
- Long-context optimization: PagedAttention-style paging management of the KV Cache, prefix caching, and similar techniques reduce repeated computation for long texts.
6. Selection and Deployment Advice for Developers
- Define the task first, then choose the scale. Simple classification or extraction tasks can prioritize small models; complex reasoning or long-document understanding needs larger models or MoE models.
- Calculate resources with formulas rather than guessing. Use the formulas in 4.1/4.2 to estimate parameters and 5.1 to estimate memory, then do capacity planning based on concurrency and context length.
- Pay attention to activation parameters and architectural details. When comparing models of “equivalent total size,” activation parameters, attention structure (GQA/MLA or not), and context length often matter more to real performance and cost than total parameters.
- Prefer mature platform capabilities. Building your own cluster is costly and complex to operate, so most teams are better off getting to production quickly through cloud-hosted LLM services or containerized inference solutions, scaling elastically on demand, and using logging and monitoring/alerting to continuously observe latency and cost.
- Build your own evaluation set. Public leaderboards are for reference only; accuracy, stability, and response latency in your business scenario are the ultimate standard.
7. Conclusion
The structure of a modern LLM can be summarized as: a Decoder-Only Transformer skeleton + RMSNorm + RoPE + SwiGLU + GQA/MLA + MoE sparsification. Parameter scale ranges from billion-level dense models to trillion-level MoE models. What truly determines compute consumption is the activation parameters, and what truly determines deployment cost is weight memory, the KV Cache, and parallelism efficiency.
Understanding structure and scale is essentially understanding the triangle of capability–cost–latency. Once you master these principles, you can make model selection, capacity planning, and performance optimization decisions with confidence and clear reasoning.
