Modern LLM Architecture and Parameter Scale: A Complete Breakdown from Transformer Structure to Inference Cost
Most debates about large language models come from two misunderstandings: that they use wildly different architectures, and that a model's parameter count is a single meaningful number. In reality, today's general-purpose LLMs share one backbone (the decoder-only Transformer), and "parameter count" splits into total, activated, and equivalent-dense figures that each govern a different resource. This article walks through the full picture in order: overall architecture, module-by-module breakdown, parameter estimation, cost conversion, and spec interpretation. Every layer includes formulas and worked examples you can reproduce, so you can move from reading numbers to understanding structure when evaluating a model, sizing inference capacity, or planning training resources.
Before We Start: Three Foundational Facts
In engineering practice, most arguments about large language models trace back to the absence of a shared understanding of two basic facts:
- Architecture: Today’s vast majority of general-purpose large models use the same backbone—a decoder-only Transformer. The differences between them live in the details: how attention compresses its cache, whether the feed-forward network is sparsified, and how positional encoding is extrapolated.
- Scale: A model’s “parameter count” is no longer a single number. For sparse models, the total parameter count and the per-token activated parameter count can differ by an order of magnitude, and each governs a different thing—memory capacity versus inference compute.
Two conclusions follow. First, the current technical competition is no longer about which backbone to use but how to trim that backbone: the same Transformer skeleton, paired with different cache strategies and sparsity schemes, can yield several-fold differences in inference cost. Second, judging models by parameter count alone essentially means giving up on evaluation.
So this article unfolds in the order of overall architecture → module breakdown → parameter estimation → cost conversion → spec interpretation, with reproducible formulas and examples at every level.
Overall Architecture: Why Decoder-Only
Three Backbone Paradigms and Their Trade-offs
Since the Transformer was introduced, three main lineages have emerged:
- Encoder-only: bidirectional attention, suited to classification, extraction, and vectorized representations, but awkward for open-ended generation.
- Encoder–decoder: one module encodes the input while another generates output word by word; strong at transformation tasks with clear input/output boundaries such as translation and summarization.
- Decoder-only: causal-masked attention that frames every task uniformly as “given the context, continue it.”
General-purpose chat models eventually converged on the third path, for three reasons:
- Prompts, instructions, chain-of-thought, tool calls, and even code completion can all be expressed as sequence continuation—no need to design a bespoke structure per task type.
- The computation graph is identical at every layer and every position, which makes parallel slicing—tensor parallelism, pipeline parallelism, operator fusion—straightforward, and lets training and inference share the same set of operators.
- Scaling performance grows predictably, which makes it easier to plan compute budgets ahead of time.
The cost is the loss of bidirectional context. A purely autoregressive model cannot see what comes after, so masked language modeling, retrieval-augmented generation, and external tool calls are essentially engineering workarounds for this gap. On tasks like intra-sentence cloze or coreference resolution, it also tends to trail bidirectional encoders slightly. A common practical combination is: a large model handles understanding and generation, while a lightweight encoder model handles vectorization and reranking.
The Full Journey of One Piece of Data
Text│ Tokenization: text → token IDs▼Embedding: look up dense vectors [T, d]│▼ × N layers, each with the same structure├─ Normalization → causal self-attention (with positional info) → residual add└─ Normalization → feed-forward network (dense / sparse) → residual add▼Final normalization▼Output projection: hidden vectors → probability distribution over the vocabulary▼Sampling strategy (greedy / temperature / top-k / top-p) → next token → loop back to the top
Two implementation details are worth noting:
- Pre-normalization has become the default: placing normalization before each sublayer keeps gradients more stable as the network gets deeper.
- Autoregressive inference repeats itself: when processing a sequence of length L, the total forward computation during training scales with L²; but inference generates token by token, and recomputing the entire history at every step wastes enormous compute. This is exactly why the KV cache exists, and it is the basis for the cost analysis later on.
Breaking Down the Key Modules
Tokenization and Vocabulary
Byte-pair-encoding-style tokenizers cut text into subword units, covering open-ended text with a finite vocabulary. The choice of vocabulary size is a trade-off:
- A larger vocabulary means fewer tokens per word on average, shorter sequences, and better context utilization.
- But the embedding layer and the output layer each hold a matrix of size vocabulary × hidden dimension. At a hidden dimension of several thousand, a vocabulary on the order of 100,000 can have a parameter count comparable to the entire attention stack.
Vocabulary size also determines the “tokens per character” for Chinese, code, and multilingual text, which directly affects how much useful information fits into the same context length. So when you swap out the base model, the actual token cost of your existing prompts can change noticeably.
Positional Encoding: From Absolute to Relative
Attention is permutation-invariant, so positional information must be injected explicitly. The mainstream approaches have evolved through three steps:
- Sinusoidal / learnable absolute positions: simple and direct, but weak extrapolation—quality drops noticeably once you exceed the training length.
- Rotary Position Embedding (RoPE): encodes position as a rotation applied to the query and key vectors, so attention scores naturally depend on their relative distance. It has become the de facto standard.
- Long-context extrapolation: applying per-band interpolation or scaling to the rotation frequencies, combined with progressively lengthening sequences during training, extends the context from a few thousand tokens to hundreds of thousands or more.
Note that context length is supported, not equally effective. As length grows, effective attention often concentrates on the first several tokens and a local window—which is the motivation behind designs like sliding-window attention and attention sinks. Also, positional encoding adds no learnable parameters (RoPE has no trainable parameters) yet determines the model’s effective field of view—a “zero-parameter, high-leverage” design.
Attention: An Optimization Battle Centered on the Cache
Standard multi-head attention can be summarized in three steps:
- Each head projects the input into queries, keys, and values, producing tensors shaped [num heads, sequence length, head dim].
- Queries and keys are dotted and scaled, then passed through the causal mask and normalized into attention weights.
- The values are combined using those weights, then concatenated and passed through an output projection.
During inference, the keys and values of historical tokens are cached (the KV cache), but the cache grows linearly with the number of layers and heads, quickly becoming the main memory consumer. So this module has evolved in one direction: reduce the cache without losing too much representational power. Representative schemes:
| Scheme | Idea | Cache change | Impact on expressiveness |
|---|---|---|---|
| Standard MHA | Each query head has its own key/value heads | Baseline | None |
| Multi-query attention (MQA) | All query heads share one set of keys/values | Down to 1/n (n = query heads) | Some drop, often needs distillation to compensate |
| Grouped-query attention (GQA) | Key/value heads shared in groups | Down to 1/group count | Small impact, now the general default |
| Latent vector compression | Compress keys/values into a low-dim latent space to cache, project up on use | Proportional to latent dim | Measured loss is small, implementation more complex |
Beyond the cache, two other directions are worth attention. One is sparse and linear attention: introducing fixed or learnable sparse patterns and kernel approximations to reduce the quadratic complexity in sequence length. The other is hybrid architectures: replacing standard attention in some layers with gated linear units or linear state-space structures, using linear-complexity sequence modeling to carry long-range dependencies. The common goal of these approaches is to hold down both compute and cache cost on long sequences.
Feed-Forward Networks and Normalization
Attention handles information exchange between tokens; the feed-forward network handles position-wise feature transformation and typically accounts for about two-thirds of the parameters in a single layer. The common change is to replace the two linear maps with a “gated” three-matrix structure:
# Gated feed-forward network (SwiGLU-style)def ffn(x, W_gate, W_up, W_down, act):return W_down(act(W_gate @ x) * (W_up @ x))
The hidden width is usually set to roughly 8/3 of the hidden dimension, preserving expressiveness at a fixed parameter count. On the normalization side, RMSNorm (root mean square normalization) has largely replaced earlier approaches because it skips the mean-centering step and is cheaper to compute; some models also normalize the query and key vectors additionally, to suppress numerical spikes during training.
Sparsification: The Role of MoE
Mixture-of-Experts (MoE) is the most important structural change of recent years. The idea is direct: replace a single “large feed-forward network” with several “small feed-forward networks” (experts), where a router network picks the Top-k experts to compute for each token.
# Simplified sketch of the MoE forward passdef moe_forward(x, router, experts, top_k=2):scores = softmax(router(x)) # score of each token on each expertidx, weight = topk(scores, top_k)out = 0for i, w in zip(idx, weight):out = out + w * experts[i](x) # only compute routed expertsreturn out
Its value lies in decoupling “parameter count” from “compute”: total parameters determine knowledge capacity, while activated parameters determine per-token compute and memory-access cost. The costs are equally clear:
- Load imbalance: a few experts get overused, training becomes unstable, and auxiliary losses or lossless routing strategies are needed to balance things out.
- All experts must fit in memory: even if a token only uses two experts, all expert weights must remain resident, so MoE usually needs expert parallelism.
- Heavier distributed communication: tokens must be sent to the devices hosting their routed experts, and communication volume rises with the degree of parallelism—the link most likely to become a bottleneck in engineering.
A common derived design is “fine-grained experts + a few always-on shared experts”: experts are cut smaller and more numerous, while the shared experts handle general-purpose capability. This raises combinatorial flexibility without changing the activated parameter count.
An Easily Overlooked Fact
Among all these modules, what also truly shapes “external behavior” is the training and alignment stage: data mixture, instruction tuning, preference optimization, and reinforcement-learning post-training aimed at reasoning. These barely change the model’s structure, yet can markedly change its behavior. So when you see “this model’s architecture is basically the same as a traditional one,” it does not mean there is no capability gap—the gap very likely lies in the data and the training pipeline.
How Parameter Count Is Actually Calculated
The Estimation Formula for Dense Models
For a standard decoder-only structure, the parameter count can be approximated as:
total params ≈ vocab × d × (1 + tie output layer?)+ layers × [ attention projection + feed-forward + normalization ]where attention projection ≈ d² × (2 + 2 × kv_heads / query_heads)gated feed-forward ≈ 3 × d × d_ff
Take a hidden dimension of 4096, 32 layers, a vocabulary of 128k, and a GQA group ratio of 1
def estimate_dense_params(vocab, layers, d, kv_ratio, d_ff, tie_emb=False):embed = vocab * dattn = d * d * (2 + 2 * kv_ratio) # Q/K/V/O four projectionsffn = 3 * d * d_ff # gated FFN three matricestotal = embed * (1 if tie_emb else 2) + layers * (attn + ffn)return total# vocab=128000, layers=32, d=4096, kv_ratio=0.25, d_ff=12288print(estimate_dense_params(128000, 32, 4096, 0.25, 12288) / 1e9)# ≈ 7.3 (billion)
This magnitude lines up exactly with the industry’s common “7-billion-class” model. Scale layers and d up proportionally and you can quickly estimate the size ranges of 13B, 34B, and 70B models.
The Three Parameter Figures for Sparse Models
MoE models must distinguish three numbers, or any comparison will be distorted:
- Total parameters: the sum of all expert weights; determines memory-capacity requirements.
- Activated parameters: the parameters that actually participate in computation for a single token; determines compute and memory-access cost, and usually includes attention, embeddings, and the Top-k experts.
- Equivalent dense parameters: an empirical ratio that maps activated parameters to a “comparable dense model of equal effect,” used only for rough comparison.
def moe_param_budget(d, layers, n_experts, top_k, d_ff_expert, shared=0):total = layers * n_experts * 3 * d * d_ff_expertactivated = layers * (top_k + shared) * 3 * d * d_ff_expertreturn total, activated
This yields a practical rule: at equal activated parameters, an MoE’s total parameters can be an order of magnitude larger, but memory usage during inference rises accordingly. When deploying, size the memory budget by total parameters and the compute budget by activated parameters—the two must not be mixed.
Scale Tiers and Common Specs
The industry currently falls into roughly four tiers (the numbers are empirical summaries of common ranges; teams vary widely):
| Tier | Typical scale | Deployment form | Common uses |
|---|---|---|---|
| On-device lightweight | Hundreds of millions to a few billion (incl. small-activation MoE) | Single card or even consumer devices | Classification, extraction, on-device assistants |
| General-purpose mainstream | 7B–14B dense | Single or dual card | General chat, code, RAG |
| High performance | Tens of billions to hundreds of billions total, ~10B activated | Multi-card, multi-machine | Complex reasoning, long context |
| Frontier models | Parameters undisclosed, usually larger activation | Large-scale clusters | General assistants and complex tasks |
Keep in mind that the relationship between parameter scale and capability is being reshaped by three things:
- Data scale: training token counts often reach hundreds or even thousands of times the parameter count, far exceeding the early “roughly 20×” compute-optimal rule of thumb. The reason is that inference cost in online serving far outweighs the one-time training cost, so it pays off to carry more training data in a smaller model.
- Inference-time compute: letting the model generate a longer reasoning process before answering, or sampling multiple times and aggregating, improves quality without increasing parameters.
- Post-training: gains from high-quality instruction data and preference optimization often exceed the returns from spending the same compute on parameter scaling.
From Parameters to Real Money: Memory and Bandwidth
The Two Components of Inference Memory
inference memory ≈ weight footprint + KV cache + activations & framework overheadweight footprint = num params × bytes per param (FP16≈2, INT8/FP8≈1, INT4≈0.5)
The KV cache estimate is just as simple:
def kv_cache_gb(layers, kv_heads, head_dim, seq_len, batch=1, bytes_per=2):return 2 * layers * kv_heads * head_dim * seq_len * batch * bytes_per / 1e9
These formulas explain a lot. Take a 7B-parameter model with 32 layers, 8 key/value heads, and a head dimension of 128: in FP16 the weights are about 14 GB; a single 128k-length context produces a KV cache of about 16 GB—already exceeding the weights themselves. This shows two things: first, the main cost of long context is the cache, not the parameters; second, GQA reduces the key/value heads from 32 to 8, cutting the cache to a quarter—the most intuitive example of “structure determines cost.” In practice, engineers often add paged cache management, prefix reuse, and cache quantization to push this overhead down further.
Training Memory: Why Distribution Is Necessary
Take mixed-precision Adam training as an example: each parameter needs about 16 bytes (a half-precision copy of the weights and gradients, plus a single-precision copy of the optimizer state and its momentum terms). For a 7B-parameter model, this alone exceeds 100 GB, before counting activations. So every mainstream training framework is built on three kinds of partitioning:
- Data parallelism: split the data batch, reduce gradients;
- Tensor parallelism: split matrices within a single layer;
- Pipeline / expert / sequence parallelism: split by layers, experts, and sequence respectively.
Only when combined with recomputation and overlapping communication with computation does training ultra-large models become engineering-feasible. Techniques like gradient accumulation, mixed precision, and low-precision communication compression are essentially different facets of the same goal: fitting a larger effective batch into a given memory and bandwidth budget.
A Frequently Overlooked Bottleneck
In the autoregressive decoding stage, generating each token requires reading all activated weights in full, a classic memory-access-bound scenario. So decode throughput is often not determined by peak compute but by memory bandwidth and batch size:
- The larger the batch, the more the weight reads are amortized across requests, and the higher the throughput;
- Once total requests exceed cache capacity, queuing appears and latency jitter increases.
This is also why “sparse activation” can be more valuable on the inference side than the training side: it directly reduces the number of weight bytes that must be moved at each step. Correspondingly, inference-side optimizations like continuous batching, speculative decoding, and operator fusion usually deliver more direct gains than switching to a larger model.
Cloud Deployment: Capabilities and Limits
From a deployment standpoint, the model structure determines the resource profile, and the resource profile determines the cloud configuration:
- Inference serving: choose GPU instance memory by “weights + peak cache,” and estimate bandwidth and concurrency by “daily request volume × average output length”;
- Elastic scaling: scale by queue length rather than CPU utilization, and throttle by token budget for long-output scenarios;
- Data and knowledge: put unstructured material in object storage, hand vector retrieval to a vector-search service, and tier cold data to cut costs;
- Observability: have a logging service collect requests and latency, and cover time-to-first-token, time-per-output-token, cache hit rate, and memory usage with monitoring alerts;
- Elastic training resources: large-scale training relies on distributed scheduling, failure re-scheduling, and nearby storage on a container platform.
On cloud platforms such as Baidu AI Cloud, these capabilities are generally offered as standard cloud services, letting users combine them according to their own resource profile rather than being tied to a specific model architecture.
How to Read a Model Spec Sheet
When facing a model spec sheet, check it in this order and you’ll rarely go wrong:
- Parameter convention: total or activated? Does it include the embedding layer?
- Context length: does the training length match the supported inference length? Was long extrapolation trained?
- Attention structure: the ratio of key/value heads to query heads, which directly determines cache cost.
- Vocabulary size: affects useful information within the same context, and the actual token count billed on inference input.
- Weight precision: FP16 / BF16 / FP8 / INT4, which determines memory and hardware requirements.
- License and restrictions: commercial license, scope of derivatives, and output usage terms.
- Evaluation methodology: how benchmark questions are constructed, whether tool calls are allowed, and whether the model was trained specifically for the benchmark—often more informative than the aggregate score.
Common Misconceptions
- “Bigger parameter count means stronger”: roughly true at equal data and training budgets, but when comparing across budgets, data quality, post-training strategy, and inference-time compute may yield larger gains.
- “MoE saves compute, so it’s cheaper”: it does less compute per token during decoding, but memory must hold all experts, so cost-effectiveness can actually drop in small-scale deployments.
- “Longer context is always better”: effective attention decays with length while cache cost grows linearly, so long context should be paired with retrieval and hierarchical summarization.
- “Structural innovation always brings improvement”: most gains come from the match among structure, data, and training; swapping a single module while keeping the original training recipe often yields negative returns.
Summary
The structure of modern large language models is not mysterious: a stacked backbone of “normalization + causal attention + gated feed-forward network,” plus tokenization, positional encoding, and an output projection, forms the skeleton of the vast majority of models. What truly separates the good from the bad is three sets of trade-offs: how attention compresses the cache, whether the feed-forward network is sparsified, and how positional encoding supports long sequences. Parameter count, in turn, must be split into total, activated, and equivalent-dense figures, then combined with the “bytes per weight × parameters + KV cache” estimate, so that memory, bandwidth, and cost are already worked out at the selection stage. Master this breakdown, and whether you’re evaluating a model spec, sizing an inference service, or planning training resources, you can shift from “reading numbers” to “reading structure.”
