LLM Architecture in 2025: A Practical Guide to Engineering Selection and Resource Trade-offs
This article examines how modern decoder-only large language models are built internally and why architectural choices directly affect memory use, KV-cache size, first-token latency, generation throughput, multi-device communication, and tail latency under concurrency. It covers positional encoding, attention variants such as grouped-query attention and latent compression, gated feed-forward networks, mixture-of-experts routing, normalization and residual design, resource estimation formulas, and a workload-based framework for comparing models and making engineering decisions.
1. Why Similar-Looking Models Behave Differently in Engineering
Looking at recent large language models, many text-generation models still follow a similar basic structure: text is converted into discrete tokens, tokens are mapped to vectors, and the resulting hidden states pass through multiple layers of attention and feed-forward networks before producing a probability distribution over the next token.
This structural continuity does not mean architecture evolution has stopped. The important changes are often hidden inside the computation path: which information must be retained over long periods, how multiple attention heads share historical state, whether all feed-forward parameters participate in computation, and how positional relationships enter attention scores.
From the perspective of developers and enterprise deployment, these design choices directly affect:
- How much device memory model weights consume;
- How much cache space long-context requests require;
- How long the system waits before producing the first token;
- What throughput can be sustained during continuous generation;
- How much communication is required in multi-device deployment;
- Whether the system shows significant latency variation under high concurrency.
Architecture analysis therefore should not stop at listing module names. It should establish causal links among structural design, resource consumption, and serving behavior.
This article focuses on text-generation architectures. Training data, training strategy, and post-training processes affect final capability, but they should not be confused with architectural factors. Two models with similar structures can still perform very differently because of differences in data quality and training investment.
2. A Unified View: What a Decoder Model Actually Computes
2.1 From Tokens to Hidden States
The model first maps token IDs to vectors, forming a sequence of hidden states. The hidden dimension determines how much information each position can carry, and it directly affects weight size, matrix multiplication cost, and intermediate activation memory.
The hidden states then enter multiple computation layers. A common pre-normalization structure can be summarized as:
Input hidden states↓Normalization → causal self-attention → residual addition↓Normalization → feed-forward network → residual addition↓Output hidden states
The final layer’s hidden states pass through an output projection to produce scores over the vocabulary, which are then converted into a probability distribution.
This is only a structural illustration. It does not mean every model uses exactly the same module order. Some designs change normalization placement, add extra normalization, or alter residual paths.
2.2 Causal Constraints Determine Generation Behavior
Autoregressive text generation requires that the current position cannot use information from future tokens. Attention computation therefore needs a causal constraint: a position can attend only to itself and previous positions.
Inference is usually divided into two stages:
Input processing stage: The system processes multiple tokens from the user input at once and generates historical keys and values for each layer. This stage involves larger matrix operations, and input length strongly affects first-token latency.
Token-by-token generation stage: The system processes one new token at a time and uses the saved historical state. This stage is often limited by a combination of weight reads, cache access, and device communication.
The bottlenecks of the two stages are not the same. Optimizing input processing speed does not necessarily improve throughput during long generation. Reducing single-request latency does not necessarily improve high-concurrency serving capacity.
3. Positional Encoding: Representing Order Is Not the Same as Understanding Long Context
3.1 Basic Idea of Absolute Position Representation
One intuitive approach is to provide a position vector for each position and combine it with the token representation. The model can then distinguish the same token appearing at different positions.
If position vectors come from a learnable table with a finite length, handling beyond the training range is constrained. Even if another position representation allows computation over farther positions, it does not guarantee that the model remains reliable over long distances.
Two questions must be distinguished: whether a position can be encoded, and whether the model has learned to use that positional relationship.
3.2 Rotary Position Embedding Changes How Information Enters Attention
Rotary position embedding usually applies position-dependent rotations to part of the dimensions of queries and keys, allowing attention computation to reflect relative position information.
It does not simply add a position label to the input. It changes the geometric relationship between queries and keys. This type of design can incorporate positional differences into the matching process while preserving the vector structure.
However, rotary position embedding does not mean context length can be extended indefinitely. When a model is used on text significantly longer than its training range, position distribution shift, degraded retrieval ability, and imbalanced attention allocation can still occur.
3.3 Long Context Should Be Evaluated at Multiple Capability Levels
“Supporting long input” includes at least three different levels:
- The system can receive and run a request of that length;
- The model can locate relevant information far away;
- The model can integrate multiple distant pieces of evidence to complete an answer.
The first level does not guarantee the latter two. Engineering evaluation should cover different evidence positions, distractor ratios, and cross-section composition tasks rather than only testing whether the input succeeds.
Position scaling, interpolation, and other extension strategies can adjust the range in which positional representations are used, but they usually need to be paired with training adaptation and practical validation.
4. Attention Structure: Balancing Expressiveness and Cache Cost
4.1 Why Multi-Head Attention Works
Multi-head attention projects queries, keys, and values into different subspaces. Each head computes relevance separately, and the outputs are then combined.
Its core computation can be summarized as:
attention output = softmax(query × key transpose / scale factor + causal mask) × value
Multiple attention heads provide different information aggregation paths for the model, but each head should not be mechanically interpreted as a fixed syntactic or semantic function.
In full-sequence computation, standard dense attention involves pairwise interactions between positions, and computation grows quadratically with sequence length. Some exact computation implementations can avoid storing the full attention score matrix, reducing intermediate memory usage, but they do not eliminate those interactions themselves.
4.2 Why Grouped-Query Attention Helps Inference
Traditional multi-head attention usually configures separate keys and values for each head. Grouped-query attention lets multiple query heads share one set of keys and values, reducing the number of key-value heads.
The important benefit occurs in the inference cache: fewer historical keys and values need to be stored, so cache capacity and read overhead decrease.
Common designs can be viewed as a continuous spectrum:
- Query heads each have their own key-value heads: low sharing;
- Multiple query heads share one set of key-value heads: a trade-off between expressiveness and cache;
- All query heads share the same set of keys and values: maximum sharing.
More sharing makes the cache more compact, but it also changes the model’s information representation paths. Whether quality can be maintained at lower cost must be validated against the specific structure and training results; it cannot be inferred from head count alone.
4.3 Latent Representation Compression Further Reduces Historical State
Another approach compresses the information that must be cached into a lower-dimensional latent representation, then uses that information through projections or equivalent transformations during attention computation.
This differs from simply reducing the number of key-value heads: the former mainly compresses the representation space, while the latter mainly reduces the number of independent cache groups.
The engineering effect of such approaches depends on the compression dimension, how position-related information is handled, and whether the inference implementation can avoid repeatedly restoring large intermediate representations. A smaller cache does not necessarily mean lower latency in every scenario.
5. Feed-Forward Networks: From Ordinary Nonlinear Transformation to Gated Computation
5.1 Feed-Forward Networks Carry a Large Share of Parameters and Computation
Attention exchanges information across positions, while the feed-forward network transforms the hidden representation at each position. A typical structure first expands the dimension, applies a nonlinear activation, and then projects back to the original hidden dimension.
Therefore, even though the feed-forward network has no cross-position interaction, it may account for a significant portion of model parameters and computational cost.
5.2 Gated Structures Make Information Flow More Controllable
A gated feed-forward network usually has two projection branches: one generates candidate features, and the other generates a gating signal. The two are multiplied element-wise and then projected back to the output dimension.
A common smooth gated structure can be written as:
output = [SiLU(input × gate weight) ⊙ (input × feature weight)] × output weight
Here, ⊙ denotes element-wise multiplication, and SiLU is a smooth activation function.
Gating provides a more flexible way to modulate information, but it should not be simplified as “replacing the activation function always makes it faster.” Compared with a common two-projection structure, a gated network usually involves three main projection weights. Cost comparisons must consider intermediate dimension, parameter count, and computation implementation together.
If the intermediate dimension is fixed, a gated structure may increase parameters. If the parameter budget is fixed, the intermediate dimension usually needs adjustment. Architecture comparisons must therefore state their comparison conditions first.
6. Mixture of Experts: Total Parameters and Per-Token Computation Begin to Separate
6.1 Basic Mechanism of Sparse Activation
Mixture of experts usually replaces part of the feed-forward layers with multiple expert subnetworks and uses a routing module to select a small number of experts for each token.
The model can therefore have a large total parameter count while activating only a subset for the current token’s computation.
When analyzing this type of architecture, at least the following must be distinguished:
- Total parameter count: affects weight storage, loading, and deployment planning;
- Activated parameter count: reflects the partial computation path used by a single token;
- Actual runtime cost: also includes attention, routing, data movement, communication, and other overhead.
A smaller activated parameter count does not necessarily mean lower overall deployment resource requirements.
6.2 Routing Balance Is Key to Performance Stability
If too many tokens are assigned to a few experts, load imbalance can occur: some devices become congested while others remain idle.
Related designs need to handle expert capacity, routing distribution, and overflow strategy. Different approaches may use load constraints, dynamic adjustment, or other mechanisms, but the goal is to prevent a few experts from becoming system bottlenecks.
Evaluation should not rely only on average throughput. It should also examine tail latency and device load variation under different request compositions.
6.3 Multi-Device Communication Can Offset Computational Savings
When experts are distributed across different devices, token representations need to be sent to the corresponding experts, and results must then be returned or aggregated.
This makes mixture-of-experts models more sensitive to interconnect bandwidth, communication scheduling, and batch organization. In environments with limited compute, weak interconnect capability, or very small request batches, a simpler dense model may achieve more stable performance more easily.
The value of mixture of experts is to expand usable model capacity while controlling part of the computational cost, not to guarantee faster performance on every hardware environment.
7. Normalization and Residuals: Stability Designs That Are Easy to Overlook
Deep networks need to preserve information and gradients through many computation layers. Residual connections provide a relatively direct path for the input, while normalization controls the scale of hidden states.
Common normalization methods include normalization based on mean and variance, and normalization based on root mean square. The latter does not perform the same mean-centering process and has a relatively simpler computation structure.
Whether normalization is placed before or after a sublayer affects training stability and numerical behavior. Adding or changing normalization placement can also affect operation fusion during inference.
These designs usually cannot explain model capability differences on their own, but they form an important foundation for stable large-scale training. Judging their merits should consider network depth, precision settings, and training scheme rather than comparing module names alone.
8. Turning Architecture into Estimated Resource Requirements
8.1 KV Cache Can Be Used for Initial Capacity Estimation
For a conventional cache that stores historical state per key-value head, if keys and values have the same head dimension and storage precision, capacity can be approximated as:
cache bytes ≈2 × layers × concurrent sequences × cache length× KV heads × per-head dimension × bytes per element
The coefficient 2 corresponds to the key and value parts.
This formula shows that context length, concurrent sequence count, and key-value head count all linearly increase cache requirements. It does not directly apply to all latent-compression attention designs, and it does not account for memory alignment, cache paging, metadata, or temporary buffers.
In actual serving, request lengths are not identical, and dynamic allocation and scheduling overhead must also be considered. Estimates must therefore be followed by measurement.
8.2 Weight Capacity Is Not the Whole Device Memory Requirement
Weight usage can be roughly estimated as “parameter count × storage bytes per parameter,” but deployment also needs to reserve space for:
- KV cache;
- Intermediate activations and temporary tensors;
- Communication buffers;
- Memory required for scheduling and execution;
- Auxiliary data related to low-precision storage, such as scaling factors.
Therefore, “weights fit on the device” does not mean “the service can stably handle the target concurrency.”
8.3 Optimization Methods Must Be Distinguished by Layer
Architecture design, numerical representation, inference implementation, and serving scheduling belong to different layers.
Grouped-query attention is an architectural change; quantization is a numerical representation change; operation fusion is an execution optimization; continuous batching and cache management are serving-system optimizations.
The same architecture may perform noticeably differently under different implementations. Conversely, system optimization cannot automatically compensate for a model’s lack of capability on a specific task.
9. Architecture Evaluation Methods for Business Scenarios
9.1 Interactive Q&A: Focus on the Combined Constraints of Latency and Concurrency
First-token latency, per-token generation latency, and tail latency under high concurrency should be measured separately.
Short-request scenarios may depend more on scheduling and weight access; long-input scenarios require closer observation of the input processing stage. A single average response time can hide the actual bottleneck.
9.2 Long-Document Analysis: Validate Both Capacity and Effective Utilization
First calculate cache requirements under the target context and concurrency, then test whether the model can retrieve evidence at different positions, handle repeated and conflicting information, and complete cross-section synthesis.
Test materials should vary evidence position and distractor ratio so that accidental success is not mistaken for stable capability.
9.3 Batch Tasks: Evaluate Throughput and Resource Utilization
For non-real-time tasks, batches can be expanded appropriately to improve device utilization, but input-length variation, output-length variation, and task queuing still need to be considered.
Sparse expert structures should also be monitored for expert load and communication overhead rather than relying only on theoretical computation.
9.4 Resource-Constrained Deployment: Prioritize Overall Carry Capacity
Beyond model size, evaluate cache structure, precision choices, operator support, and target context.
Reducing cache usually solves only part of the memory problem; lowering weight precision does not eliminate all intermediate-state overhead. Deployment plans need joint validation of quality, capacity, and latency.
10. How to Form a Reliable Architecture Comparison Conclusion
A professional comparison should first list known conditions, then state unknown factors, and finally provide verifiable judgments.
A four-layer framework is recommended:
Structural layer: Record layer count, hidden dimension, attention head configuration, feed-forward form, expert layout, and positional encoding.
Resource layer: Estimate weight capacity, KV cache, computation scale, and communication requirements.
Implementation layer: Check how well the target hardware and inference system support the relevant structures.
Business layer: Use real request distributions to validate quality, latency, throughput, and stability.
At the same time, three common misjudgments should be avoided:
- More parameters do not necessarily mean stronger capability;
- Fewer activated parameters do not necessarily mean lower serving cost;
- A longer nominal context does not necessarily mean more reliable long-text understanding.
Conclusion: Architecture Innovation Is Mainly About Reallocating Costs
By 2025, large language models still mainly rely on a relatively stable autoregressive decoder skeleton, but internal designs continue to change. Positional encoding adjustments change how order information is expressed. Grouped-query attention and latent compression change the cost of storing historical state. Gated feed-forward networks enhance feature transformation. Mixture of experts partially decouples model capacity from per-token activated computation.
These changes are not isolated tricks. They are systematic trade-offs around expressiveness, computation, memory capacity, and communication cost.
For engineering teams, the most valuable work is not to search for the “most advanced architecture” in the abstract. It is to define business constraints, build resource models, and validate them with real workloads. Only by connecting architecture, implementation, and serving metrics can technical selection move from conceptual comparison to practical engineering decisions.
