Training and Serving Sparsely Activated Large Models
Sparse activation spends compute on the parameters a token actually needs rather than shrinking the model. This article explains how to train and serve those models for coding assistants, tool use, and multi-step agents, covering architecture, post-training, attention, serving, and evaluation.
Sparse activation does not make a model “smaller.” It spends computation on the parameters the current token actually needs. For coding assistants, tool calling, and multi-step agents, the bottleneck is rarely another benchmark score. It is whether the model can reliably retrieve context, edit code, call tools, and check its own work within acceptable latency and memory. The sections below separate that problem into architecture, post-training, attention, serving, and evaluation.
Separate total parameters from active parameters
A Mixture of Experts (MoE) model splits each feed-forward network into multiple expert subnetworks. At every layer, a router selects a small number of experts for the current token, and only those experts run. Two sizes therefore appear together: total parameters set capacity and storage, while active parameters are closer to the compute of a single forward pass.
That split has three direct consequences.
First, capacity and compute can be decoupled. A large total parameter count helps the model retain diverse coding styles, tool protocols, and domain terminology. A smaller active count keeps a single inference pass inside a deployable compute budget. Second, routing quality sets the ceiling. If similar tokens always land on a few experts, the rest sit idle. That wastes storage and can collapse performance on long-tail tasks. Third, parallelism has to be redesigned around experts. Classic tensor parallelism assumes every layer’s weights are sliced evenly across devices. With sparse expert activation, the pattern becomes “route first, then move only the selected experts.” Device count on one machine is no longer a natural sharding grain. In practice, expert parallelism, pipeline parallelism, and sequence parallelism are usually combined.
In production, track observable metrics rather than the parameter table alone: expert load balance (variance of how often each expert is chosen), drop rate (share of tokens discarded when capacity is insufficient), routing entropy, and the actual FLOPs that correspond to active parameters. If load stays skewed, adjust the load-balancing loss and the capacity factor before increasing total parameters.
Post-training is the main lever for usable capability
With the architecture held fixed, repeating post-training can still change agent and coding behavior substantially. Pretraining mainly learns a general next-token distribution. Tool use, terminal actions, and multi-step planning depend on “which action to take in which state.” Those behaviors can be shaped with smaller, higher-quality data through supervised fine-tuning and reinforcement learning.
A conservative post-training order is:
- Start with supervised fine-tuning. Examples should cover real call formats: function names, parameter constraints, error returns, retries, and the final answer. Format errors get amplified by later reinforcement learning, so this stage should favor fewer, cleaner samples.
- Filter with rejection sampling or self-consistency. Generate multiple trajectories for the same task and keep only those that pass unit tests, static checks, or validation of tool results, then use them for a second round of supervision.
- Apply reinforcement learning with verifiable rewards. For coding, rewards can be whether tests pass, whether the build succeeds, and whether the diff is minimal. For tools, rewards can be whether arguments are valid and whether the task finishes within a step budget. Rewards must be judged automatically. Do not substitute vague preference scores.
- Replay out-of-distribution failures. Resample intermediate states from failed trajectories and train specifically on “how to recover after an error,” not only on a clean path that succeeds once.
Data quality matters more than example count. Repeated, templated function calls teach surface format without teaching missing arguments, permission failures, or partial success. Each trajectory should keep the user goal, the available tool schema, step-by-step observations, and a final verifiable result. Open-ended chat that cannot be verified should not dominate agent post-training.
Long context needs attention compression, not an unbounded window
Coding and agent workloads often place repository fragments, terminal logs, and tool results in context at once. Full attention makes both compute and the key-value cache grow roughly quadratically or linearly with sequence length, so long logs can exhaust memory. A common mitigation is hybrid attention: denser attention inside a local window, and compressed or sparse access to older history, keeping only the keys and values that matter for the current prediction.
Separate two kinds of information. Nearby lines of code and a just-returned error usually need high fidelity. Earlier directory structure and summaries of completed steps can often be compressed into shorter memory. Treating all history as equally important makes the cache grow linearly and worsens time to first token.
In engineering, control three things together: the maximum context, the cache reuse policy, and when history is folded into a summary and written back. Folding must remain reversible for critical facts, such as files already changed, names of tests that failed, and tools not yet called. Keeping only a natural-language summary and dropping structured state makes later steps repeat the same mistakes.
Inference cost comes from the active path, the cache, and kernel implementation
Fewer active parameters do not automatically mean a lower bill. Real cost also depends on batch size, sequence length, expert communication, and the key-value cache. A useful split of one request is compute (tied to active parameters and generation length), memory (weights plus cache), communication (expert routing and cross-device collectives), and queue time.
If weights stay resident, decoding is often limited by cache bandwidth. If the sequence is very long, attention during prefill becomes the dominant cost again. Claims such as “compute is some fraction of the previous generation” or “memory drops to some fraction” must be tied to batch size, precision, context length, and hardware topology. They should not be compared across unrelated settings.
At the kernel level, a mature approach is to implement the hot paths in routing, aggregation, and attention as portable kernels, and to lock results with the same numerical tests. Binding to one vendor’s acceleration library can raise short-term speed and also raise migration cost. A more stable design exposes a stable service interface, allows kernels to be swapped internally, and keeps output differences for the same checkpoint within an agreed threshold at the target precision. Precision can be mixed by layer—for example, higher precision for routing and normalization, lower precision for large matrix multiplies—but the check must be regression on real coding and tool tasks, not perplexity alone.
Keep the service interface stable and model versions traceable
Callers depend on the request protocol and a reproducible model snapshot, not on a marketing version name. Agent workloads typically need system instructions, multi-turn messages, a tool schema, tool results written back into the conversation, and optional structured output. Those capabilities can be expressed with fields compatible with common chat-completion APIs, or with a response-style interface aimed at “one task, multiple tool round trips.” Both can coexist, but the server should compile them into one internal trajectory format so the two post-training targets do not drift apart.
For versioning, an external model name may point at “the currently recommended snapshot,” while every internal request records the snapshot identifier, sampling parameters, tool-schema version, and random-seed policy. Otherwise, when online quality regresses, routing changes, post-training changes, and prompt changes cannot be told apart.
For pricing, peak/off-peak or time-of-day rates are a general cloud practice used to shift elastic batch work into low-load periods. Whether to use them, and at what factor, should follow capacity and queue length. They should not be written into a model card as a fixed story tied to capability. What developers need is a clear statement of how input and output are metered, whether tool results count toward context, and whether a long-cache hit is discounted. Those rules have to be clear before cost can be regressed.
Attach multimodality outside the text base
Once the text base is stable, vision is usually added through an external vision encoder and a modality-alignment module: an image becomes visual tokens, then an alignment layer maps them into the language model’s representation space. Tool calling and coding on the text side do not have to be rebuilt. The cost is that alignment data, resolution, and the number of visual tokens change the context budget. Before launch, run the same agent tasks on a text-only path and an image path, and confirm that the vision branch does not crowd out the context needed for code and tools.
Evaluate by failure type, not by a single score
Agent and coding evaluation should at least separate four task types: whether a single-file patch passes tests, whether a multi-file edit keeps interfaces consistent, whether the model can continue from an error in a terminal environment, and whether a tool chain reaches the goal within a step limit. For each type, break down failures: illegal format, wrong tool, hallucinated arguments, retry loops, declaring success too early, and context drowned by logs.
When comparing two post-training runs, freeze the tool schema, temperature, maximum steps, and test split. A single aggregate score does not say what data to add next. A more useful report is pass rate, average steps, average tokens, cost per successful task, and the share of each failure type above. A small gain in pass rate with a higher cost is not necessarily worth releasing.
A minimum checklist before launch
- Routing: expert load is balanced, and long-tail domains are not fixed onto empty experts.
- Data: post-training trajectories are verifiable, and failed states are replayed.
- Cache: memory and time to first token under long logs still meet the service level.
- Interface: tool-schema changes are versioned, and older clients can still parse responses.
- Regression: coding tests, tool validity, and safety refusals share one baseline.
- Observability: every online request can be traced by snapshot identifier.
None of these checks depends on a vendor-specific model name. They answer the same engineering question: whether the sparse model spends compute on paths that finish the task, whether post-training turns “can talk” into “can finish,” and whether serving makes cost and failure causes measurable. Iterating inside this frame is closer to maintainable production capability than chasing a single leaderboard rank.
