Technical Breakdown: LLM Architecture and Parameter Scaling
This article provides a technical breakdown of Large Language Model (LLM) architectures and parameter scaling. It covers the foundational Transformer skeleton, the evolution of attention mechanisms, the differences between dense and Mixture of Experts (MoE) models, and practical methods for estimating parameter counts and memory requirements. Furthermore, it offers strategic insights for model selection and deployment practices to help developers optimize performance, cost, and resource utilization.
1. Why LLM Architecture and Parameter Scaling Matter
When selecting an LLM, parameter scale directly determines VRAM usage, inference latency, and per-request cost. The model architecture defines the capability ceiling and efficiency at a given scale. These two factors are interrelated; focusing solely on parameter numbers can lead to misjudgments, while looking only at architecture names makes it difficult to quantify resource requirements. Therefore, understanding the conversion relationship between architecture and scale is essential for evaluating models.
2. The Basic Skeleton of Mainstream Architectures
2.1 Decoder-Only Transformer
Most current general-purpose LLMs adopt a decoder-only Transformer structure. The model consists of several identical stacked layers, each containing two core modules: a multi-head self-attention module for modeling dependencies between tokens, and a feed-forward network (FFN) module for applying non-linear transformations to each position’s representation. Residual connections and normalization layers ensure stable training for deep networks.
2.2 Evolution of Attention Mechanisms
Standard Multi-Head Attention (MHA) equips each query head with independent key and value heads, offering strong expressiveness but large Key-Value (KV) cache usage during inference. Common improvement schemes include:
- Multi-Query Attention (MQA): All query heads share a single set of key/value heads, minimizing cache but potentially degrading quality.
- Grouped-Query Attention (GQA): Query heads are grouped, with each group sharing a set of key/value heads, achieving a balance between quality and cache footprint. This is currently the most widely applied.
- Low-rank Compression Schemes: Project key/value information into a low-dimensional latent space before caching, further reducing VRAM pressure.
2.3 Positional Encoding and Long Context
Positional encoding determines how a model perceives token order. Rotary Position Embedding (RoPE) is the mainstream choice, applying rotational transformations to queries and keys so that attention scores depend only on relative positions. To extend context from training length to longer sequences, position frequency interpolation or scaling is usually required, accompanied by continued training on long-text data. As context lengthens, the growth of the KV cache becomes significant and must be evaluated separately during deployment.
3. Dense Models vs. Mixture of Experts (MoE)
3.1 Dense Models
In dense models, every token passes through all parameters. The parameter count is approximately proportional to the computational volume. The structure is simple, and training and deployment behaviors are predictable. The downside is that more parameters mean higher computational cost per inference.
3.2 Mixture of Experts (MoE) Models
MoE models use multiple FFNs as “experts,” with a router selecting a few experts per token for computation. Two key metrics must be distinguished:
- Total Parameters: The sum of all experts and shared components, determining the model’s storage size.
- Activated Parameters: The parameters actually involved in a single forward pass, determining inference computational volume.
Let’s illustrate the difference with hypothetical numbers. Suppose the shared part is 2B, a single expert is 5B, there are 8 experts, and each token routes to top-2 experts:
- Total Parameters = 2B + 8 × 5B = 42B
- Activated Parameters = 2B + 2 × 5B = 12B
This means the model’s storage requirement is close to a 42B scale, while the per-call computational cost is similar to a 12B dense model. Note that more experts exacerbate routing imbalance and expert parallelism communication issues, typically requiring auxiliary load balancing loss to constrain the routing distribution.
4. Parameter Scale Estimation Methods
4.1 Parameter Count Estimation
For a standard decoder-only Transformer, ignoring bias and normalization parameters, the attention projection per layer is roughly 4h², and the FFN (with an intermediate dimension of 4h) is about 8h², totaling about 12h² per layer. Adding the vocabulary embedding parameters V×h, the total parameter count can be approximated as:
Total Params ≈ L × 12h² + V × h
Where L is the number of layers, h is the hidden dimension, and V is the vocabulary size. The following code implements this estimation:
def estimate_dense_params(num_layers: int, hidden: int, vocab_size: int, ffn_mult: int = 4) -> int:attn = 4 * hidden * hidden # Q, K, V, O projection matricesffn = 2 * ffn_mult * hidden * hidden # Up and down projectionsembed = vocab_size * hidden # Input embeddings, output head not includedreturn num_layers * (attn + ffn) + embed# Example: 32 layers, hidden dimension 4096, vocab size 32000print(f"{estimate_dense_params(32, 4096, 32000):,}") # Approx. 6.57B
4.2 Memory Estimation
Weight Memory = Parameter Count × Bytes per Parameter. Using FP16, each parameter takes 2 bytes, so the weights of the 6.57B model above require about 13 GB. Quantization reduces this footprint: INT8 is about 1 byte per parameter, and INT4 is about 0.5 bytes.
The KV cache memory grows linearly with context length, calculated as:
KV Cache Bytes = 2 × Layers × KV Heads × Head Dimension × Sequence Length × Bytes per Element
def kv_cache_bytes(layers: int, kv_heads: int, head_dim: int,seq_len: int, dtype_bytes: int = 2) -> int:# The coefficient 2 corresponds to two caches: keys and valuesreturn 2 * layers * kv_heads * head_dim * seq_len * dtype_bytes# Example: 32 layers, 8 KV heads, head dimension 128, sequence length 8192, FP16print(kv_cache_bytes(32, 8, 128, 8192) / 2**30, "GiB") # 1.0 GiB
If the same model is changed to 32 KV heads (standard MHA), the cache for the same sequence increases to 4 GiB. Thus, the choice of attention architecture greatly impacts concurrency capabilities. In actual deployment, VRAM requirements should be the sum of weights, KV cache, activations, and runtime overhead, with a certain buffer reserved.
5. Scale Tiers and Model Selection Strategy
The industry typically categorizes models by parameter count into small (under billions), medium (tens to hundreds of billions), and large (hundreds of billions and above). This tiering is an empirical division and does not represent an absolute ranking of capabilities. Consider the following dimensions when selecting a model:
- Task Complexity: Tasks like classification, extraction, and format conversion usually don’t require large models. Multi-step reasoning, complex code generation, and long document analysis demand higher model capabilities.
- Latency Requirements: Interactive scenarios are sensitive to time-to-first-token and generation speed; models with fewer activated parameters have an advantage.
- Throughput and Cost: Concurrent requests determine the total KV cache, requiring evaluation combined with GQA or quantization schemes.
- Context Requirements: Long-text scenarios should specifically test the model’s performance at the target length, rather than just looking at the nominal length.
- Deployment Environment: Self-owned hardware, private clouds, and public clouds differ significantly in VRAM specs and network conditions; calculate before selecting.
6. Practical Deployment Recommendations
In engineering practice, the following steps are recommended:
- First, define an evaluation set covering real business inputs, and record quality, latency, and cost metrics.
- Use the estimation formulas in this article to project weight and cache VRAM to confirm if a single-card or multi-card solution is viable.
- Test candidate models in both original and quantized precision to observe if quality loss is acceptable.
- Configure monitoring and alerting for inference services, paying attention to VRAM levels, queue times, and error rates to prevent cascading failures during peak hours.
- Include models, configurations, and evaluation results in version control for easy rollback and reproducibility.
When deploying in the cloud, the model service can be split into components like general compute resources, object storage, container orchestration, logging, and monitoring. The advantage is that during model version upgrades, you only need to replace the inference image and weight files, keeping other components unchanged. If using Baidu AI Cloud services, you can set up the inference environment using the same layered approach and choose an elastic scaling strategy based on your workload.
7. Summary
Understanding model architecture and parameter scaling requires simultaneously looking at total parameters, activated parameters, attention design, and context length. With the estimation methods above, developers can quickly determine if VRAM and cost align during the model selection phase, reducing trial and error. Model capability still needs to be validated through business evaluation; parameter numbers cannot replace this step.
