LLM Architecture Evolution: Sparse Attention and RL Post-Training

    This article explores the evolution of large language model (LLM) architectures, focusing on the trade-off between efficiency and capability. It covers key advancements such as Mixture of Experts (MoE) for parameter efficiency, sparse attention mechanisms for reducing long-context costs, and reinforcement learning (RL) post-training techniques like verifiable rewards and group relative advantage for enhancing reasoning. It also provides engineering insights on evaluation, deployment, and model selection.

    1. Background: Trade-off Between Efficiency and Capability

    Over the past two years, the enhancement of large language model (LLM) capabilities has primarily relied on two approaches: scaling up parameters and extending training data and context lengths. Both approaches rapidly drive up training and inference costs. Larger models require more compute per inference, and longer contexts lead to faster-growing attention computation overheads.

    Consequently, architectural improvements in new-generation open-source models generally revolve around three questions:

    1. How to control the number of parameters actually involved in computation per token, given a large total parameter count.
    2. How to prevent the attention mechanism from scaling quadratically with sequence length.
    3. How to genuinely train reasoning and tool-use capabilities within a limited training budget.

    Around these three questions, the industry has developed a set of relatively universal technical solutions. Let’s break them down.

    2. Foundational Skeleton: Mixture of Experts and Attention Cost

    2.1 Mixture of Experts Architecture

    Mixture of Experts (MoE) splits the feed-forward network into multiple expert sub-networks, with a router selecting a small number of experts for each token. The model’s total parameter count can be massive, but a single forward pass only activates a fraction of it.

    Here, two concepts need to be distinguished:

    • Total parameters: All trainable parameters included in the model.
    • Activated parameters: The parameters actually involved in computation when processing a single token.

    The router’s design directly impacts training stability. If some experts remain untrained for long periods, model capacity is wasted. Common practices include adding load-balancing losses or using auxiliary-loss-free bias adjustment strategies to keep the usage of all experts balanced.

    2.2 Quadratic Cost of Attention

    Standard self-attention for a sequence of length n requires computing an n × n attention matrix, with both time and memory overheads scaling with n². When the sequence grows from 4K to 128K, the computation for the attention part increases by about 1,000 times. This is the main reason why long-context inference is expensive.

    Therefore, reducing attention cost has become a core direction for architectural improvement. Sparse attention is among the most common approaches.

    3. Sparse Attention: Focusing Only on Key Positions

    3.1 Basic Concept

    The core of sparse attention is that for each query, instead of computing attention with all historical positions, a lightweight module first filters out the top-k most relevant positions, and standard attention is only computed on these selected positions.

    This involves a two-step cost:

    • The filtering stage still requires scoring historical positions, but the computation for the scoring module is much smaller than full attention.
    • The attention computation involves only k positions, thus decoupling the main computation cost from the sequence length.

    The following pseudocode illustrates this process:

    1. def sparse_attention(query, keys, values, indexer, k):
    2. # 1. Lightweight scoring: calculate relevance scores for each historical position
    3. scores = indexer(query, keys) # shape: [seq_len]
    4. # 2. Select the top k positions with the highest scores
    5. topk_idx = top_k_indices(scores, k)
    6. # 3. Compute standard attention only on the selected positions
    7. k_sel, v_sel = keys[topk_idx], values[topk_idx]
    8. weights = softmax(query @ k_sel.T / sqrt(d))
    9. return weights @ v_sel

    This example only illustrates the concept, omitting details like multi-head, causal masking, and batching.

    3.2 Key Issues During Training

    Sparse attention faces two practical issues.

    First, the filtering results are non-differentiable, meaning direct training might prevent the filtering module from learning effective patterns. A common approach is to train with dense attention for a period first, allowing the model to learn basic attention distributions, before gradually switching to sparse mode. This ensures the filtering module’s target distribution aligns with the original attention.

    Second, the benefits on short sequences are limited, and filtering itself incurs extra overhead. Whether to enable sparse attention should be judged based on the typical context length of the target scenario. For most short-text tasks, dense attention remains simpler and more reliable.

    3.3 Engineering Trade-offs

    Dimension Dense Attention Sparse Attention
    Implementation Complexity Low, mature ecosystem Higher, requires an additional filtering module
    Long-text Inference Cost Scales quadratically with length Main cost is nearly linear
    Quality Risk No significant additional risk Filtering errors may lose key information
    Applicable Scenarios Short context, general tasks Long documents, long conversations, codebase retrieval

    4. Post-Training: Enhancing Reasoning with RL

    4.1 Post-Training Pipeline

    The foundational capabilities of LLMs come from pre-training, while reasoning, math, and coding capabilities often require further enhancement during the post-training phase. A common pipeline includes:

    1. Supervised Fine-Tuning (SFT): Using high-quality instruction and response data to teach the model to follow formats and basic tasks.
    2. Reward-based Reinforcement Learning: Having the model generate multiple responses to the same question and adjusting the policy based on reward signals.
    3. Capability Fusion and Safety Alignment: Merging specialized model capabilities from different domains and supplementing training related to safety and refusal.

    4.2 Verifiable Rewards

    In math, coding, and logic tasks, answers can often be verified programmatically. For example, math problems can be checked against the final result, and coding problems can run unit tests. These verifiable rewards are more stable and cheaper than manual scoring.

    For open-ended questions, another model can act as a judge for scoring, but attention must be paid to the judge model’s own biases, and regular manual spot-checks should be conducted for calibration.

    4.3 Group Relative Advantage

    A common RL method samples a group of responses for the same question and calculates advantages using intra-group relative rewards, eliminating the need to train a separate value network. The core computation is as follows:

    1. def group_advantage(rewards):
    2. # rewards: rewards of G sampled responses to the same question
    3. mean = sum(rewards) / len(rewards)
    4. std = std_dev(rewards) + 1e-6
    5. return [(r - mean) / std for r in rewards]

    The benefit of this approach is its simplicity and low memory footprint. The risk is that if all rewards in a group are identical, the advantage value is zero, and this group of samples produces no gradient. Therefore, training data must include problems with a sufficient distribution of difficulty.

    Additionally, policy updates usually include a constraint term against a reference model to prevent the model from deviating too far from its language capabilities in pursuit of rewards.

    4.4 Reasoning Length and Cost

    RL encourages models to generate longer reasoning processes, leading to two direct outcomes: an increase in the number of reasoning tokens, and a subsequent rise in latency and cost per response.

    Engineering measures can be taken to address this:

    • Include a length penalty in the reward function, but the weight should not be too large, otherwise it will harm the quality of answers to complex problems.
    • Set reasoning budget limits for different tasks, using shorter reasoning chains for simple problems.
    • Record accuracy, average output length, and time-to-first-token in monitoring to avoid looking at a single metric.

    5. Self-Verification and Tool Calling

    A common pattern in newer reasoning models is self-checking after generating an answer, such as recalculating key steps or verifying citation information. This pattern can reduce basic errors but increases the number of reasoning tokens.

    In tool-calling scenarios, the model needs to decide when to call external tools and integrate the returned results into the final answer. When training this capability, a common practice is to construct multi-turn tool interaction data and consider in the reward whether the call is reasonable, if the parameters are correct, and if the final answer is accurate.

    6. Engineering Implementation Essentials

    6.1 Evaluation Methods

    Benchmark scores should only be used as a reference. Actual selection requires attention to the following:

    • Whether the test set might appear in the training data requires deduplication and contamination checks.
    • The same model may perform differently under different inference parameters (e.g., temperature, max output length); settings should be unified for comparison.
    • Test sets relevant to your own business should be supplemented, covering real input distributions and edge cases.

    6.2 Deployment and Resources

    • In long-context scenarios, the KV cache is usually the memory bottleneck and needs to be estimated in advance.
    • The benefits of sparse attention depend on the specific inference framework’s implementation; latency and throughput should be tested on the target hardware.
    • Integrate inference services with object storage, message queues, logging services, and monitoring alerts to facilitate tracking costs and anomalies.

    6.3 Considerations for Using Open-Weight Models

    When using open-weight models, it is necessary to confirm whether the license agreement permits the intended use and to assess the model’s risks regarding security, privacy, and content compliance. For internal deployment, input and output filtering and auditing mechanisms should be established.

    7. Summary and Selection Recommendations

    Reviewing this evolution path, three key takeaways can be summarized:

    1. At the architecture level, MoE and sparse attention solve parameter efficiency and long-text cost issues, respectively, and can be used in combination.
    2. At the training level, verifiable rewards and group relative advantage are currently easier-to-implement RL solutions, but attention must be paid to reward design and reasoning length.
    3. At the engineering level, the credibility of evaluation, long-context resource overhead, and compliance requirements are often more decisive for project success than a single benchmark score.

    When selecting a specific model, it is recommended to clarify three things first: typical input length, acceptable inference cost per call, and whether the task can be verified programmatically. These three answers can eliminate most unsuitable options, allowing subsequent evaluations to focus on truly relevant candidates.