Sparse Experts, Linear Attention, and an LLM Production Checklist

    This article explains how to evaluate and deploy modern large language models from an engineering perspective. It covers the difference between total and activated parameters, MoE routing and load balancing, linear attention as a cost-saving alternative to full attention, training data requirements for agentic tasks, how to read evaluation reports, and a practical deployment checklist with troubleshooting guidance.

    Introduction

    The focus of LLM competition is shifting from “how much a model knows” to “whether it can get things done.” Models used to be judged mainly on parameter count and knowledge benchmarks. Now, code repair, terminal operation, multi-step tool calling, and office workflow automation are becoming the metrics that matter. These tasks require a model to stay on goal over long horizons and adjust its actions step by step based on environmental feedback.

    Agentic tasks impose three engineering requirements: the model must fit within an acceptable hardware budget, long context must actually work, and training data must support multi-turn actions. This article covers architecture, training, evaluation, and deployment. Each section provides decision criteria, code examples, or checklists you can use directly.

    1. What Is the Difference Between Total and Activated Parameters?

    Total parameters are the count of all learnable weights in a model. Activated parameters are the weights actually involved in computing a single token. In sparse models, the gap between the two can be large: total parameters may reach tens of billions, while each token passes through only a small fraction of them.

    The two numbers correspond to different engineering costs:

    Cost Item Determined by Total Params Determined by Activated Params
    Weight memory Yes No
    Per-token compute (FLOPs) No Yes
    Model loading and weight distribution time Yes No
    KV cache No (grows with context length and concurrency) No
    Runtime activations No (varies with batch size and sequence length) No
    Communication buffers and synchronization overhead No (grows with the parallelism strategy) No

    Inference memory consists of several parts: the weights themselves, the KV cache, runtime activations, and framework buffers. Parallel sharding spreads weights across multiple GPUs—each GPU holds fewer weights, but communication buffers and synchronization overhead increase. Total parameters are therefore only the base term of a memory estimate; the other items must be added one by one.

    Evaluate engineering cost using both numbers. Looking only at total parameters overestimates per-token compute. Looking only at activated parameters underestimates memory and loading pressure.

    2. How Does MoE Routing Avoid Expert Overload?

    Mixture of Experts (MoE) splits the feed-forward layer into multiple expert subnetworks. A router scores each expert for every token and activates only the top-k experts. The code below shows the basic top-k routing logic:

    1. import torch
    2. import torch.nn.functional as F
    3. def topk_route(hidden, gate_weight, k=2):
    4. # hidden: [tokens, d_model], on the same device and dtype as gate_weight
    5. # gate_weight: [d_model, num_experts], initialize with a small std, e.g., 0.02
    6. # requires 1 <= k <= num_experts
    7. logits = (hidden @ gate_weight).float() # softmax in float32 for numerical stability
    8. probs = F.softmax(logits, dim=-1)
    9. topk_p, topk_idx = probs.topk(k, dim=-1)
    10. topk_p = topk_p / topk_p.sum(dim=-1, keepdim=True)
    11. return topk_idx, topk_p

    Three points matter here. First, routing keeps only the k highest-probability experts; the rest do not participate in computing the current token. Second, the selected expert weights are renormalized so the weighted output scale stays stable. Third, some models apply top-k on the logits first and then softmax over the selected experts. The two orders produce different weights, so confirm which one a model uses before reproducing it.

    This example omits three components that are mandatory in production: capacity limits, auxiliary losses, and multi-GPU communication.

    Capacity limits. The number of tokens each expert can process is typically set to capacity = ceil(tokens × k / num_experts × capacity_factor). Tokens exceeding capacity are handled in two common ways: dropped outright, passing only through the residual connection; or forwarded to the next-best expert that still has capacity.

    Tune capacity_factor against the drop rate and throughput. When the drop rate rises, first check whether the load is concentrated on a few experts, then decide whether to increase capacity_factor or improve routing. When the drop rate stays near zero and memory is tight, capacity_factor can be lowered. Alert thresholds for the drop rate are business-specific—for example, quality-sensitive scenarios can set stricter limits.

    Auxiliary loss. Training usually adds a load-balancing loss of the form L_aux = α × N × Σ_i f_i × P_i, where N is the number of experts, f_i is the fraction of tokens assigned to expert i, P_i is the router’s average probability for expert i, and α is the auxiliary loss coefficient. α cannot be omitted; it must be tuned together with the main loss. Too large an α forces routing flat and reduces expert specialization; too small an α leaves load imbalance in place. Start from a small value and judge jointly by downstream task quality and the expert load distribution.

    Communication overhead. In multi-GPU deployments, experts live on different devices. Tokens are first sent to the corresponding device via all-to-all, then aggregated after computation. At small batch sizes, communication latency often dominates compute, so the combination of expert parallelism and tensor parallelism must be planned around the hardware topology. GPUs within the same node are connected by high-bandwidth links, so expert-parallel groups should be kept within a single node whenever possible.

    Monitoring metrics. After going live, monitor at least the following:

    1. The fraction of tokens received by each expert. Collected at the router output, i.e., at the dispatch counting point.
    2. The ratio of maximum expert load to average load. A persistently rising ratio indicates routing concentration.
    3. The token drop rate. Collected at the capacity truncation point.
    4. The share of all-to-all communication time in each step. Collected with timers around the communication operator.

    Alerts can be set as “max-to-average load ratio exceeds a threshold for 10 consecutive minutes” or “all-to-all share keeps rising.” Thresholds should be derived from your own stress tests, not copied from other models.

    3. Can Linear Attention Replace Standard Attention?

    Standard self-attention scales quadratically with sequence length. As sequences grow from a few thousand tokens to a million, attention becomes the main bottleneck. Linear attention replaces the exponential kernel in softmax with a feature map φ and reorders the matrix multiplications, making compute linear in sequence length. It is not an exact equivalent of softmax attention, so you cannot swap it in and expect identical behavior.

    Causal linear attention can be written as:

    out_i = φ(q_i)ᵀ S_i / (φ(q_i)ᵀ z_i)

    where Si = Σ{j≤i} φ(kj) v_jᵀ and z_i = Σ{j≤i} φ(k_j).

    For recurrent computation, S and z can be updated incrementally: Si = S{i-1} + φ(ki) v_iᵀ, z_i = z{i-1} + φ(k_i).

    Several implementation details matter. First, the output of φ should be non-negative, otherwise the denominator φ(q_i)ᵀ z_i may approach zero or go negative. Common choices include non-negative maps such as elu(x) + 1. Second, add a small constant ε to the denominator to prevent division by zero. Third, accumulate S and z in fp32 even if the model body uses bf16 or fp16, because summation error accumulates with sequence length.

    The inference state of linear attention has a fixed size. Each attention head keeps a d × d matrix plus a vector of length d, independent of sequence length. The KV cache of standard attention grows linearly with length. For very long sequences, this difference has a significant impact on memory.

    Linear attention also has costs. It is generally weaker than standard attention on exact retrieval tasks, and precise long-range matching may degrade. Hybrid architectures are therefore common in practice. An example configuration: out of every 4 layers, 3 use linear attention and 1 keeps full attention. The full-attention layers handle precise retrieval while the linear layers reduce overall cost. This ratio is only an example, not a universal conclusion. The optimal ratio depends on the task and evaluation results and should be determined through ablation experiments.

    Measure two numbers for long context. The window length is an interface parameter: the maximum number of tokens the model can accept. The effective context length is the range within which the model still works reliably. The two often differ substantially. To measure effective context:

    1. Run needle-in-a-haystack tests at multiple lengths and positions—insert a key fact at different depths in a long document and check whether the model finds it.
    2. Run multi-document QA and plot accuracy against total document length.
    3. Define effective context as the maximum length at which accuracy stays above 90% of the short-context baseline, and state this definition in the report.
    4. Record prefill and decode latency, along with memory usage at each length.

    A measurement report should include: the length tiers tested, the list of insertion depths, the short-context baseline accuracy, the computed 90% threshold, prefill and decode latency, and memory usage per tier. Without any one of these, readers cannot judge whether the results are reproducible.

    4. What Data Does Agentic Training Require?

    Agentic tasks differ from QA tasks mainly in data format. QA data is typically a single-turn question plus a reference answer. Agentic data contains multi-turn interactions, where each turn includes the model’s action, the tool’s response, and a final state judgment.

    Training this capability generally requires three categories of data.

    The first is tool-call trajectories. A trajectory must record parameter formats, call ordering, and error recovery. For example, after a failed file write, the model rechecks the path and retries—this recovery process is itself a valuable training signal.

    The second is environment state snapshots. Key steps of each trajectory should record the environment state before and after execution, so it is possible to verify whether an action actually took effect.

    The third is final outcome labels. These indicate whether the task was completed, usually as automatically verifiable assertions—for example, whether tests pass or file contents match expectations.

    Before a trajectory enters the dataset, it must pass a validation pipeline with at least these steps:

    1. Schema validation. Check every tool call’s parameter names, types, and value ranges against a schema. Non-conforming steps are flagged and excluded from the training set.
    2. Deduplication. Deduplicate by action sequence and final state so the same path is not counted many times.
    3. Privacy sanitization. Remove personal information, account credentials, keys, internal network addresses, and customer data. Sanitization must happen before ingestion, not as an afterthought. After sanitization, sample-check for residue.
    4. Error recovery annotation. Mark the cause of each failure and the recovery action, so the model learns how to return to the correct path after an error.
    5. Outcome verification review. Manually review a sample of automatically judged outcomes to confirm the assertions themselves are correct.

    The compliance baseline: any trajectory containing real personal information or usable credentials must never enter the training corpus. When such content is found, delete the segment and log the incident—do not merely replace a few characters.

    5. How to Read Evaluation Reports

    Evaluation results are often misread. When reading a report, confirm the following first.

    Parameter accounting. Does the report cite total or activated parameters? The cost conclusions differ and must not be mixed.

    Context setting. What maximum context length was used? Were scores measured at the window length or within the effective context range? The gap can be large.

    Decoding settings. Temperature, sampling method, maximum generation length, and number of repetitions all affect results. If the report does not state them, the results are not comparable.

    Environment versions. Agentic evaluations depend on tools, images, and environment versions. With different versions, the same model’s success rate can vary considerably.

    Metric definitions. Task success rate, average step count, error recovery rate, and per-task cost are common metrics. The denominator of each metric must be clear. For example, is the success rate denominator all tasks, or only tasks that could start normally?

    Use this checklist for a quick review of any evaluation report:

    • Does it state the parameter accounting and context length?
    • Does it state decoding parameters and repetition counts?
    • Does it state environment and tool versions?
    • Does it define each metric and its denominator?
    • Does it compare against baseline models in the same environment?
    • Are scores directly compared across different benchmark suites? If so, readers should be warned that such comparisons are unreliable.

    6. System Deployment

    Before deployment, complete a memory budget. The budget should cover four items—weights, KV cache, runtime activations, and framework buffers—calculated at the target concurrency and maximum context length. Estimating only the weights commonly leads to out-of-memory failures under high concurrency after launch.

    Deployment checklist:

    1. Is weight distribution time acceptable? Total parameters determine the loading volume; cold-start time must be measured.
    2. Does the parallelism topology match the hardware? Are expert-parallel groups placed within the same node?
    3. Have batch size and maximum sequence length been stress-tested? The KV cache grows with concurrency; measure peak memory at maximum concurrency.
    4. Does monitoring cover expert load, drop rate, all-to-all share, and p50/p99 latency?
    5. Is there a canary release and rollback plan? A new version should first receive a small share of traffic, with the ability to switch back to the previous version quickly.
    6. Do logs contain keys, user data, or complete tool trajectories? Logs need sanitization and a defined retention period.

    Troubleshooting directions for common problems:

    • Latency suddenly rises. Check the all-to-all share first. If it rises, check whether experts are distributed across nodes or whether load is concentrated on a particular GPU.
    • Drop rate rises. Check whether the load is concentrated on a few experts. If so, adjust routing or the auxiliary loss, and evaluate whether capacity_factor needs to increase.
    • Output quality degrades. Check whether the drop rate rose at the same time. Dropped tokens pass only through the residual connection, and quality degradation is usually related to this.
    • Out of memory. Break down KV cache usage by concurrency and context length. If the KV cache is the largest component, consider capping the maximum context length or reducing concurrency.
    • Poor long-context performance. Compare against the effective-context measurements to confirm whether current input lengths already exceed the effective range.

    Deployment is not a one-time task. Models, tools, and business traffic all change, and monitoring metrics and evaluation sets need regular updates. Keeping the pre-launch checklist, post-launch monitoring items, and troubleshooting steps in the same document reduces incident diagnosis time.