Efficient LLM Architectures Explained: Hybrid Linear Attention and Sparse Mixture-of-Experts
Large language models face rising compute and memory costs as context lengths and parameter counts grow. This article explains how hybrid linear attention and Mixture-of-Experts (MoE) architectures address these challenges, covering the cost structure of standard self-attention, gated linear attention with fixed-size state, sparse expert routing, and practical guidance on training, inference, and evaluation trade-offs. Includes NumPy and PyTorch code examples.
1. Background: The Dual Pressure of Long Sequences and Large Parameter Counts
The capability gains of large language models come mainly from two directions: increasing the number of parameters, and extending the context length a model can process in a single pass. Both directly raise compute and memory costs. During training, the parameter count determines the compute required for each forward and backward pass; during inference, context length determines the attention compute and cache footprint.
When engineering teams design model architectures, they typically focus on two questions. First, how to keep per-token compute from growing rapidly with context length. Second, how to keep the number of parameters actually involved in each inference step under control as the total parameter count grows. Hybrid linear attention and Mixture-of-Experts (MoE) models are two common approaches targeting these problems.
2. Where the Cost of Standard Self-Attention Comes From
The self-attention of a standard Transformer can be written as:
Attention(Q, K, V) = softmax(Q K^T / sqrt(d)) V
where Q, K, and V are the query, key, and value matrices, and d is the dimension of each attention head. For a sequence of length n, the attention score matrix is n × n, so compute time scales with n². Scaling a sequence from 4K to 400K tokens increases the number of elements in the score matrix by roughly a factor of 10,000 — this is the main bottleneck for long contexts.
Inference also introduces the KV cache problem. When generating each new token, the model must read the keys and values of all previous tokens. The cache size can be roughly estimated as:
Cache bytes ≈ 2 × layers × KV heads × head dim × sequence length × bytes per element
As an example, consider a hypothetical configuration: 32 layers, 8 KV heads, head dimension 128, sequence length 128K, and BF16 precision (2 bytes per element). The cache for a single request is about 2 × 32 × 8 × 128 × 131072 × 2 bytes, roughly 17 GB. This shows that even if the model weights fit in GPU memory, the cache for concurrent requests can exhaust resources first.
3. Linear Attention: Replacing the Full Matrix with a Fixed-Size State
The core idea of linear attention is to replace softmax with a factorizable feature map φ, allowing the order of matrix multiplications to be rearranged:
output = φ(Q) (φ(K)^T V)
This makes it possible to first accumulate a fixed-size state matrix S, then compute the output token by token. The recurrence form is:
St = S{t-1} + φ(k_t) v_t^T
o_t = φ(q_t)^T S_t / (φ(q_t)^T z_t)
where z_t is a normalization term accumulated from all historical φ(k). Compared with standard attention, the total compute of this recurrence grows linearly with sequence length, and the state size required for single-step inference is independent of sequence length. Here is a NumPy illustration to make the data flow easier to understand:
import numpy as npdef elu_plus_one(x):# ELU(x) + 1, ensuring the feature map output is positivereturn np.where(x > 0, x + 1.0, np.exp(x))def linear_attention_recurrent(q, k, v, eps=1e-6):"""q, k: [T, d_k]; v: [T, d_v]; returns output of shape [T, d_v]."""T, d_k = q.shaped_v = v.shape[1]S = np.zeros((d_k, d_v)) # fixed-size state matrixz = np.zeros(d_k) # normalization accumulatorout = np.zeros((T, d_v))for t in range(T):phi_k = elu_plus_one(k[t])phi_q = elu_plus_one(q[t])S += np.outer(phi_k, v[t])z += phi_kout[t] = phi_q @ S / (phi_q @ z + eps)return out
Pure linear attention also has clear weaknesses. A fixed-size state must compress all historical information into a finite matrix, so early information tends to be overwritten by later writes. As a result, on tasks that rely on precise long-range retrieval, such as exact recall and multi-hop reasoning, pure linear attention often underperforms standard attention.
4. Hybrid Linear Attention: Interleaving Linear Layers with Full Attention
To compensate for the shortcomings of pure linear attention, a common engineering practice is a hybrid design: most layers use linear attention or its variants, while a small number of layers keep standard full attention. The former keeps compute and cache costs under control for long sequences; the latter handles precise long-range retrieval.
The mixing ratio must be determined experimentally. More full-attention layers make retrieval capability more robust, but increase compute and cache costs. More linear layers improve efficiency, but require better state design to compensate for reduced memory capability.
A common class of improvements introduces gating or incremental update rules, so that state updates can selectively erase old information and write in new information. The form can be written as:
St = (I - β_t k_t k_t^T) S{t-1} + β_t k_t v_t^T
where β_t is a write strength between 0 and 1, and k_t is assumed to be normalized. When β_t is close to 0, the state barely changes; when close to 1, the new key-value pair overwrites the old memory associated with that key. The following code shows a single update step:
def delta_update(S, k, v, beta):"""S: [d_k, d_v]; k: [d_k], normalized; v: [d_v]; beta: scalar between 0 and 1."""S = S - beta * np.outer(k, k @ S) # corresponds to (I - beta k k^T) SS = S + beta * np.outer(k, v) # write the new key-value associationreturn S
When β is 1 and k is normalized, retrieving with the same k returns the v that was just written, which shows the rule supports overwriting old values by key.
5. Mixture-of-Experts: Separating Total Parameters from Active Parameters
An MoE layer replaces a single feed-forward network with multiple feed-forward networks (the experts) and uses a router to select a few experts for each token. A model’s total parameter count can be very large, while the parameters actually computed per token depend only on the number of activated experts.
Suppose a layer has 64 experts and each token activates 2 of them. The active fraction of expert parameters is 2/64, about 3.1%. Parameter capacity and per-inference compute are therefore decoupled to some extent.
The routing process has four steps: compute a score for each expert, select the top-k experts, normalize the selected scores, then compute a weighted sum of the expert outputs. Example code:
import torchimport torch.nn.functional as Fdef moe_forward(x, router, experts, top_k=2):"""x: [tokens, hidden]; router outputs scores of shape [tokens, num_experts]."""logits = router(x)weights, idx = torch.topk(logits, top_k, dim=-1)weights = F.softmax(weights, dim=-1) # normalize only among selected expertsout = torch.zeros_like(x)for j in range(top_k):for e in range(len(experts)):mask = idx[:, j] == eif mask.any():out[mask] += weights[mask, j:j + 1] * experts[e](x[mask])return out
This code uses nested loops for readability. Production systems typically use grouped matrix multiplications and expert capacity limits to improve throughput.
Training also requires load-balancing constraints. If the router always picks a few experts, those experts become overloaded while the rest are undertrained. A common approach is to add an auxiliary loss to the objective that encourages each expert to receive a roughly uniform number of tokens. An expert capacity limit is also set; tokens exceeding capacity are usually skipped for that layer via the residual connection.
In distributed training, experts are often spread across multiple accelerators. Tokens must be sent through all-to-all communication to the devices hosting the corresponding experts, and the results are gathered back after computation. Communication overhead is often the bottleneck for MoE, so it must be planned together with data parallelism, pipeline parallelism, and expert parallelism.
6. Coordinating Architecture Design with Training and Inference
Architecture choices affect every stage of training and inference.
For training, note the following:
- Long-context capability is usually built up in stages. Train on shorter sequences first, then progressively extend the context length while adjusting position encoding parameters accordingly.
- Data mixtures should cover code, document reasoning, multi-turn dialogue, and other scenarios. Different tasks depend on attention types to different degrees, and a single data source easily leads to unbalanced capabilities.
- Learning rates, initialization, and normalization for hybrid structures may need separate tuning. The gradient scales of linear layers and full-attention layers can differ, and shared parameters can lead to training instability.
For inference, note the following:
- The state size of linear layers is fixed, so memory growth in long-conversation scenarios is much gentler than with standard attention.
- Full-attention layers still depend on the KV cache, which requires separate capacity planning. Techniques such as cache quantization and sliding windows can reduce the footprint.
- MoE inference suffers from low expert utilization at small batch sizes, while at large batch sizes communication and load imbalance become the main issues. Batching strategies should be tuned to actual traffic.
7. How to Evaluate Whether an Architecture Is Worth Adopting
Scores on public leaderboards are only a reference. Engineering teams should build evaluation sets aligned with their own business and track both quality and efficiency. Comparison experiments must control variables, including identical training data, identical training token counts, and identical inference frameworks and hardware.
Start with the following five categories of metrics:
- Quality metrics: measure accuracy on your own task sets. For long-context scenarios, use a “needle in a haystack” retrieval test — insert key information at different positions and measure the model’s recall rate.
- Code task metrics: use unit tests as the pass criterion. If each problem is sampled n times and c samples pass, compute pass@k with the unbiased estimator — the probability that at least one of k samples passes.
- Latency metrics: time to first token (TTFT) and average time per output token, measured separately for short and long inputs.
- Throughput metrics: tokens processed per unit time, tested at different concurrency levels and context lengths.
- Resource metrics: peak GPU memory, cache usage, and accelerator utilization. Resource metrics determine deployment cost and should be compared alongside quality metrics.
8. A Trade-off Checklist for Engineering Adoption
Before deciding whether to adopt hybrid linear attention or sparse expert architectures, check the following items one by one:
- Does the business really need ultra-long context? In most scenarios, inputs are within a few thousand tokens, where retrieval augmentation or segmented processing is often cheaper.
- Can the deployment environment’s memory budget hold weights, cache, and concurrent requests simultaneously? An MoE model’s total parameter count may far exceed a single card’s capacity, so multi-card sharding must be planned in advance.
- Does the inference framework support the chosen attention variants and expert routing? The maintenance cost of custom operators must be included in the total cost.
- Is routing causing expert load imbalance? Monitor each expert’s hit rate in production, and adjust routing or load-balancing parameters promptly when long-term skew appears.
- Do the license terms of the open-source weights you use permit the intended use, and do the training and evaluation data meet compliance requirements?
