# Cutting AI Agent Costs with Trillion-Parameter Sparse MoE Models and Million-Token Context
A next-generation sparse MoE model combines trillion-scale total parameters with million-token context support and shows that capability and cost can improve at the same time: average cost per sample task fell from roughly 4.43 to about 1.67. This article walks through the architecture behind that result—gated linear attention, sparse attention in a 3:1 hybrid layer layout, N-gram embeddings, and four-way gated residual connections—then explains token efficiency, and finally covers the application-level levers that actually show up on the bill: prompt caching, context compression, task-tier routing, deterministic agent scaffolding, and cost observability. It also names the model's real weak spots (terminal execution, software replication) and gives a launch checklist for teams doing domain continued pretraining or agent production deployment.
Introduction: Capability keeps rising, but the bill has to stay controllable
The capability frontier of large models keeps expanding, yet what enterprises care about when they deploy usually comes down to three questions: how much did benchmark scores improve, how much does one real task cost, and is this architecture worth the engineering investment? The marginal return on single-metric leaderboard gains is shrinking. What determines whether something scales is the combined efficiency of capability × cost.
A new generation of sparse MoE models offers a useful data point: trillion-scale backbone parameters, with only tens of billions of parameters activated per token; a hybrid of gated linear attention and sparse attention; N-gram embeddings and gated residual connections; native vision input, with the context window extended into the million-token range. Average cost across official sample tasks dropped from roughly 4.43 to about 1.67, a reduction of roughly 62%.
A note on data provenance: the official sample costs, benchmark scores, and training-stability figures cited here come from the official model release documentation and example pages—see the official model card and technical report sections—published or updated in June 2026. Test conditions follow the official sample task set, default configurations of public benchmarks, and official statements. Actual pricing and evaluation results vary by version, region, and workload, so re-verify the latest numbers before procurement or launch.
This article breaks down the architecture first, then analyzes token efficiency, and finally lands on engineering practice, answering one question: when a model is both stronger and cheaper, how do you convert that value-for-money into business returns?
Part 1: A cost-per-task lens — break the bill down to every token
1.1 From “price per million tokens” to “cost per task”
Traditional model selection looks only at “price per million tokens.” In long-context and agent scenarios, real cost has to be calculated per task:
cost per task =Σ(missed input tokens × input price+ cache-hit tokens × cache price+ output tokens × output price)+ cost of failed retries+ context retrieval and preprocessing cost
The cache price is the rate applied to the portion of the prompt served from cache, typically significantly lower than the standard input price.
Three categories of factors drive cost:
- Architecture: determines compute per token, and therefore unit price;
- Model behavior: determines how many tokens are needed to finish the same task;
- Application design: determines how many tokens can be cached, retrieved, or trimmed.
The new generation’s cost gains come mainly from the first two. Compared with the previous flagship generation, it is priced lower while being stronger. Average cost across official sample tasks dropped from roughly 4.43 to about 1.67, roughly 62% lower. That reduction is not only a price cut: on the high-intensity thinking tier of the Work360 benchmark, token usage fell by about 35%. Under a simplified assumption of unchanged price structure and proportional reduction across the input, output, and cached token components, a 35% token saving corresponds approximately to a 35% cost reduction on its own, with the unit-price cut contributing most of the remaining decline.
Takeaway: procurement evaluation has to watch two tables at once—unit price and token efficiency. If either one falls behind, the total accounting stops being truthful.
1.2 Architecture-side savings: capacity scales, activation does not
In dense models, parameter count almost linearly determines compute per token, so capability gains and inference cost are naturally coupled. Sparse MoE decouples the two: total parameters carry knowledge capacity, while each token activates only a small fraction of them—“scale the capacity, not the compute.”
The cost benefit of this architecture concentrates in three workload classes:
- Long-context tasks: code repository Q&A, contract review, long-report analysis—every turn reprocesses a large volume of input;
- High-concurrency online serving: throughput directly determines per-request cost;
- Batch offline processing: throughput-sensitive, latency-insensitive.
The trade-offs are equally clear:
- All expert parameters must stay resident in GPU memory; memory footprint does not shrink with the activation rate;
- Load imbalance across the router can overload some experts, producing dropped tokens or tail latency;
- Expert parallelism introduces additional communication overhead.
So “cheaper” mainly holds for the compute-bound parts of the pipeline. Deployment cost on the capacity side still has to be absorbed through engineering optimization.
Part 2: Architecture breakdown — four upgrades, two main threads
Official material summarizes the upgrades as gains in attention, residual connections, embeddings, and gated-residual stability. Taken apart, the four changes serve two threads:
- Reduce compute: gated linear attention, sparse attention, N-gram embeddings;
- Stabilize training: gated residual connections.
2.1 Gated linear attention: remembering history with a fixed-size state
Standard self-attention’s compute grows quadratically with sequence length, and the KV cache grows linearly. During the decode phase of long-context work, repeatedly reading the KV cache often costs more than the matrix math itself, becoming the throughput bottleneck. Linear attention in the gated DeltaNet family instead uses a fixed-size state matrix:
- It does not store the full history; it maintains a fixed-size state matrix S and updates it incrementally, token by token;
- Each step performs “forget—retrieve—write”: first decay the old state proportionally, then correct old associations per the Delta rule and write in new content;
- Gating coefficients control the decay rate and write strength, so the state can retain information long-term while being overwritten on demand.
The simplified update looks like this:
# S_t: current state matrix, dimensions d×d# k_t, v_t, q_t: key, value, and query vectors for token t, dimensions d×1# alpha_t: forget gate, value in [0, 1]; beta_t: write gate, value in [0, 1]# I: d×d identity matrixS_t = alpha_t · S_(t-1) · (I − beta_t · k_t · k_t^T)+ beta_t · k_t · v_t^To_t = q_t^T · S_t
Here k_t, v_t, and q_t are d-dimensional column vectors, and S_t is a d×d matrix; k_t·v_t^T and k_t·k_t^T are both d×d outer products. alpha_t and beta_t are gating coefficients between 0 and 1.
Different update rules behave differently:
| Update rule | State update | Behavior |
|---|---|---|
| Naive accumulation | St = S(t-1) + k_t v_t^T | Old values for the same key keep stacking up; new writes cannot correct old associations |
| Delta correction | St = S(t-1)(I − k_t k_t^T) + k_t v_t^T | Erases the old component for that key first, then writes the new value; supports in-place updates |
| Gated Delta | Delta correction plus forget and write gates | Learnable control over retention vs. overwrite, mitigating the limited capacity of a fixed-size state |
The strength of linear attention is that compute grows linearly with sequence length, state size stays constant, and memory footprint does not inflate as context lengthens. But it has an obvious weakness: a finite state cannot precisely preserve all of history, and for “needle in a haystack” exact retrieval or multi-hop retrieval, information tends to be lost. That is exactly where the hybrid layout comes from.
2.2 Sparse attention: only compute the most relevant context
Qwen sparse attention (QSA) works much like in-model retrieval: score micro-blocks of history first, then compute attention only over the high-scoring blocks. The pseudocode below fills in the key functions so the execution path is easy to follow:
import torchimport torch.nn.functional as Fdef chunk(x, block_size):"""Split a sequence into contiguous micro-blocks. x: [B, H, S, D]"""b, h, s, d = x.shapepad = (-s) % block_sizex = F.pad(x, (0, 0, 0, pad))n = x.shape[2] // block_sizereturn x.view(b, h, n, block_size, d)def sparse_attention(q, k, v, score_fn, block_size=128, top_k=8):"""q, k, v: [B, H, S, D]score_fn(query, k_blocks): takes [B,H,S,D] and [B,H,N,block,D],returns a relevance score of each query against each block: [B,H,S,N]"""kb = chunk(k, block_size) # [B, H, N, block, D]vb = chunk(v, block_size) # [B, H, N, block, D]scores = score_fn(q, kb) # [B, H, S, N]idx = scores.topk(top_k, dim=-1).indices # [B, H, S, K]out = 0for j in range(top_k):kidx = idx[..., j] # [B, H, S]kidx4 = kidx.unsqueeze(-1).unsqueeze(-1)kidx4 = kidx4.expand(-1, -1, -1, block_size, kb.shape[-1])ks = kb.gather(2, kidx4) # [B, H, S, block, D]vs = vb.gather(2, kidx4) # [B, H, S, block, D]attn = F.scaled_dot_product_attention(q.unsqueeze(-2), ks, vs) # [B, H, S, 1, D]out = out + attn.squeeze(-2)return out / top_k
Note: the code above is structural illustration. It omits causal masking, padding masks, parallel blocking, and the details of training the indexer. score_fn should be implemented by a lightweight indexer, and block granularity, block count, and indexer precision all need to be traded off between recall quality and overhead.
Take a 1M-token context and estimate roughly one micro-block per token:
- Full attention requires about 1 trillion relevance computations;
- With block_size=128 and top_k=8, each query selects 8 micro-blocks on average, about 128×8 = 1,024 tokens;
- Total relevance computations are about 1M × 1,024 ≈ 1.024 billion pairs;
- Relative to the roughly 1 trillion pairs of full attention, that is about one thousandth;
- If top_k=8 means 8 tokens, it is about 8 million pairs, close to one hundred-thousandth.
Sparse weights do not grow linearly with context length, and KV bandwidth pressure drops accordingly in long-context scenarios.
2.3 The hybrid layout: one sparse layer per three linear layers
The 3:1 alternating layout gives roughly three quarters of the layers to cheap gated linear attention for long-range information compression, and inserts one sparse attention layer every three layers for precise retrieval.
This division of labor resembles human memory: episodic memory carries the overall impression, while the retrieval mechanism handles precise recall on demand. Two engineering details are worth noting:
- State size is the knob for “memory bandwidth.” It determines how much history can be compressed into the fixed state and directly affects performance on long-range tasks;
- A hybrid architecture’s inference engine must support both operator families and the state hand-off between them. If only one family is optimized, the long-context gains cannot be realized.
2.4 N-gram embeddings: bringing table lookup into the backbone
N-gram embeddings, added at the second layer, introduce an extra 328B parameters, but they perform essentially no matrix computation and rely on lookup only:
- Extract contiguous N-grams from the input token sequence and map them to indices;
- Look up the embedding table to obtain vectors;
- Fuse them into the backbone representation.
Why it works:
- Fixed collocations suit lookup: patterns such as terminology, entity names, code identifiers, and API call snippets are cheaper to “recognize” up front than to recompute at every token;
- Capacity decoupled from compute: parameter growth happens in the lookup path, so compute per token barely changes;
- Engineering cost: the embedding table is a memory-intensive structure that needs sharded storage and efficient access. Building the N-gram index and maintaining hash mappings add overhead, so confirm the actual benefit with load testing before production deployment.
2.5 Four-way gated residual: more stable training is a precondition for lower cost
A conventional residual connection can be understood as an identity backbone: a sub-layer’s output is added onto the main path, and information reaches each layer directly without having to “apply” for passage. Once the layer count grows, functions of different layers tend to interfere with each other, and deep representations may degrade. Gated residuals turn inter-layer memory into a learnable, sparse routing scheme:
- Each layer maintains several parallel residual streams—four in the original design—and each stream can carry a different type of information;
- Every sub-layer uses dynamic read/write gates to decide which streams to read from and which to write to;
- Information flows selectively between layers based on content rather than being indiscriminately summed.
This is the same sparse idea as MoE: MoE sparsifies activation along the parameter dimension, gated residuals sparsify activation along the inter-layer pathway dimension, and together they reduce wasted computation.
| Aspect | Standard residual | Four-way gated residual |
|---|---|---|
| Inter-layer pathway | A single identity backbone | Multiple parallel residual streams |
| Information transfer | Indiscriminate summation | Dynamic read/write gates that route by content |
| Deep-layer interference | Functions of different layers interfere easily | Functions can be assigned to separate streams |
| Large-scale training stability | Relies heavily on external measures | A structural prior that helps stabilize |
Why is stability directly tied to cost? In large-scale training, a single loss spike can contaminate days of compute, and both the repair and the rollback consume extra budget. The official technical report states that the 2.4T-scale training run completed without a single loss spike. Combined with the result that “activated parameters are 25% lower than the previous-generation Base, while BPB still drops 5%–13% across domains,” fewer computations buying better modeling quality is already visible at the Base stage. This data comes from the official documentation, with test conditions of 2.4T-parameter training monitoring and official evaluation configurations.
Loss spikes are stochastic events, and a single “zero spike” record cannot prove that a given structure is necessarily more stable. But it does show that this set of designs is engineering-viable. For teams planning domain continued pretraining or fine-tuning, structural stability is a reusable, implicit cost saving.
Part 3: Token efficiency — strong not just in getting answers right, but in taking fewer detours
3.1 The same task, fewer tokens
In the old-versus-new model comparison, the higher the thinking intensity, the more pronounced the token savings:
- On the Xhigh and High tiers of Work360, token usage dropped by roughly 24% and 35% respectively;
- On Terminal-Bench 4.0, the two tiers dropped by roughly 48% and 49%, close to a halving.
This suggests the new model’s improvement is not only about being stronger per token, but about:
- Better planning: planning it through in one pass instead of one step at a time;
- More effective verification: judging correctness by executable results instead of repeated trial and error;
- Less redundancy: fewer duplicate tool calls and less restating of already-confirmed information.
Wasted tokens are an invisible sink in agent cost. Failed retries, looping calls, and repeatedly re-reading large logs all keep billing, while “getting it right the first time” is the most thorough cost reduction available.
3.2 Thinking tiers: pick the tier by task value
The highest thinking tier is not always the best value. Build a task-to-tier mapping:
| Task type | Suggested tier | Rationale |
|---|---|---|
| Text rewriting, information extraction, intent classification | Low | Short path, high determinism; extra thinking adds little |
| Structured writing, routine code generation | Medium | Balances quality and cost |
| Complex troubleshooting, cross-module refactoring, expert reasoning | High | Requires multi-step planning and self-verification |
Signals for triggering a high thinking tier can include: low confidence, failed validation, repeated tool calls with no progress, missing critical fields, and abnormal user feedback.
Run offline evaluation before launch: on the same test set, compare task success rate and average token consumption across tiers, and compute cost per successful task rather than looking only at per-call price.
# Illustration: compare thinking tiers on the same test set and pick by cost per successdef evaluate(report, requests, tiers, model, estimate_cost):for name, params in tiers.items():tokens, cost, passed = 0, 0.0, 0for req in requests:resp = model.chat(**params, messages=req["messages"])tokens += resp.usage.total_tokenscost += estimate_cost(resp.usage)passed += int(resp.output == req["expected"])success_rate = passed / len(requests)report[name] = {"tokens_per_task": tokens / len(requests),"cost_per_task": cost / len(requests),"success_rate": success_rate,"cost_per_success": cost / passed if passed else float("inf"),}return min(report, key=lambda k: report[k]["cost_per_success"])
For production, apply a dynamic budget: route low-risk tasks to the low tier first; escalate when a review signal fires; and set a token ceiling per task so single-task cost cannot run away.
Part 4: Overall capabilities and weak spots — closing gaps matters more than polishing strengths
Official material indicates that the new generation has advantages in software engineering, general-purpose agents, biology reasoning, and legal agents, but still has weak spots on terminal execution and software replication. An excerpt:
| Benchmark | New model | Previous-gen flagship | Leading model A | Leading model B | Leading model C |
|---|---|---|---|---|---|
| Work360 | 52.69 | 47.74 | — | — | — |
| Agents’ Last Exam v1.1 | 46.7 | — | 44.1 | 43.2 | 42.9 |
| DeepSWE v1.1 | 75.7 | — | 72.0 | 69.4 | 73.3 |
| Terminal-Bench 4.0 | 48.5 | — | 65.1 | 67.2 | 64.0 |
| ProgramBench | 31.5 | — | 65.0 | 58.5 | 60.0 |
| BioMysteryBench | 85.0 | — | 81.0 | 75.0 | 78.0 |
| HLAB-Vals-1.1 | 21.3 | — | 9.2 | 5.7 | 10.9 |
The new model leads on software engineering, general-purpose agents, biology reasoning, and legal agents. The legal agent score of 21.3 is above leading model A’s 9.2, and Work360 is up roughly 10% over the previous flagship. But the weak spots are concentrated:
- Terminal execution: Terminal-Bench 4.0 at 48.5 still trails clearly behind leading model A’s 65.1 and leading model B’s 67.2;
- Software replication: ProgramBench at 31.5 is about half of leading model A’s 65.0, roughly 51.5% lower. The official table does not report a previous-generation flagship score for this item, so the comparison here is against leading model A.
The terminal weakness may be an architectural trade-off rather than an accident. Gated linear attention compresses history into a fixed state, which suits long-range modeling but sacrifices verbatim retention of precise detail—and terminal tasks depend on exactly that kind of precise recall: the exact output of the previous command, which line of which file, the name of a given environment variable. Once such details are distorted in state compression, subsequent operations drift off course. Sparse attention layers can recover some of the detail, but they are limited in number and cannot fully compensate.
Software replication has a different cause. These tasks require a multi-turn closed loop of “look at the UI — write code — run it — compare,” which places very high demands on visual localization and long-horizon execution control. The model already supports vision input natively, which shows multimodal is a focus area, but understanding fine visual detail and closing the execution loop remain hard.
| Capability profile | Typical behavior | Selection guidance |
|---|---|---|
| Strength: long context, expert reasoning, legal/biology reasoning | Long-document analysis, domain agents | First choice |
| Conditional: terminal execution | Exact CLI output, log troubleshooting | Needs structured tooling, deterministic validation, and compensation mechanisms |
| Weak spot: software replication | High-fidelity UI replication, complex software rebuilds | Evaluate cautiously or combine models |
For dimensions where the official table provides no like-for-like comparison—chart understanding, agent competitions, and so on—this article makes no ranking judgment. Public leaderboards and your own traffic distribution often diverge, so build your own benchmark: sample 200–500 real tasks, label success criteria, cover high-frequency, high-value, and high-risk scenarios, and record average tokens, cost, and success rate as a baseline for selection and iteration.
Part 5: Engineering practice — turning architectural headroom into bill reduction
Architecture and token efficiency set the ceiling on a model’s value-for-money; application design determines how much of it an enterprise actually realizes. The five layers below are ordered by return on investment.
5.1 Prompt caching: pay for the system prompt once
Prompt caching comes in two forms: explicit and implicit. Explicit caching usually means the developer declares a cache prefix or cache object; implicit caching usually hits automatically based on shared prefixes. Developers should understand the difference: explicit caching offers more control, while implicit caching depends more on routing and prefix stability.
Price definitions need to be consistent. The cost function in this article uses a cache price of 0.075, a standard input price of 1.5, and an output price of 4.5, where 0.075 is about 95% below 1.5. If a provider announces that “cache prices drop by roughly 70%,” the corresponding cache price is about 0.45 (1.5 × 0.3). The two are not the same convention—the code only demonstrates the calculation, and actual billing per the provider governs.
The key to a higher hit rate is a stable prefix:
- Keep system prompts, tool definitions, and few-shot examples fixed and versioned;
- Push timestamps, random IDs, and user-specific content later;
- Order long documents as “stable part first, changing part last.”
[fixed] system instructions + tool definitions + a few examples[semi-static] knowledge-base documents, project notes[dynamic] this turn's user input, live data
Points to watch:
- Unchanged content does not guarantee a hit; cache lifetime, server load, and instance scaling all affect the hit rate;
- Caching is not free—a miss may incur extra overhead, and a very short prefix may not pay off;
- Caching is no substitute for privacy boundaries; multi-tenant scenarios require strict isolation and content review.
def estimate_cost(usage):price = {"input": {"regular": 1.5, "cache": 0.075}, # per million tokens"output": 4.5,}in_tokens = usage["input_tokens"]hit = usage.get("cache_tokens", 0)miss = in_tokens - hitreturn (miss / 1e6 * price["input"]["regular"]+ hit / 1e6 * price["input"]["cache"]+ usage["output_tokens"] / 1e6 * price["output"])
5.2 Context compression: retrieve on demand instead of stuffing everything in
A million-token context is a capability, not a quota that must be filled. Three reasons: input tokens are always billed; long context raises latency; and irrelevant information distracts the model’s attention, creating context pollution.
| Strategy | Approach | Fits |
|---|---|---|
| Retrieval instead of full context | Fetch relevant chunks on demand | Knowledge-base Q&A, code repository search |
| Rolling summarization | Periodically compress earlier conversation | Multi-turn long sessions |
| Trimming tool output | Return only summaries and relevant lines from large logs/files | Terminal execution, log troubleshooting |
| Structure instead of raw text | Use tables or JSON summaries in place of full text | Report analysis, data reconciliation |
5.3 Task-tier routing: not every task deserves the flagship model
Use a two-dimensional “task complexity × failure cost” matrix to decide routing:
| Failure cost / complexity | Low | High |
|---|---|---|
| Low | Light model + low thinking tier | Flagship model + medium thinking tier |
| High | Flagship model + medium thinking tier + rule-based validation | Flagship model + high thinking tier + human review |
A safer approach is “small first, large second”: let the light model handle the request, escalate when confidence is low or validation fails, and keep most simple requests in the low-cost band.
def select_tier(task):if task.risk == "high":return {"thinking": "high", "verify": True, "human_review": True}if task.estimated_steps <= 2 and task.domain in SIMPLE_DOMAINS:return {"model": "light", "thinking": "low"}return {"model": "flagship", "thinking": "medium", "verify": True}
5.4 Agent engineering: use deterministic code to backstop an uncertain model
Long-horizon agent failures usually happen not in a single reasoning step but in losing control of the process. Four principles can constrain that:
- Idempotency: attach a request ID to write operations so retries cannot cause duplicate side effects;
- Budget: set maximum steps, maximum tokens, and maximum cost; abort and report on breach;
- Checkpoints: validate key nodes with deterministic means such as compiling, testing, and checksums;
- Structured output: constrain tool-call arguments with a JSON Schema and validate them in code.
In long-context scenarios the message list keeps growing, so pair it with rolling summarization and tool-output trimming to keep per-turn input size in check. Restate critical early information into the recent context periodically, so the model does not lose sight of the original goal and constraints.
5.5 Cost observability: make unit cost visible per task class
Track at least the following metrics:
- Token level: input/output tokens per task, cache hit rate;
- Cost level: cost per task, cost per successful task, savings from caching;
- Quality level: task success rate, human rework rate, average retries;
- Performance level: time to first token, end-to-end P95 latency.
Reference alerting thresholds: warn when cost per successful task rises 20% week over week, when cache hit rate drops 30%, or when failure rate rises 10% week over week.
How to implement it:
- Log the model, tier, usage, cache hit status, and task tags on every call;
- Aggregate into a logging service or data warehouse, and drill down by business line, scenario, and version;
- Use monitoring and alerting to flag sudden cost spikes and sharp drops in cache hit rate.
On a cloud platform, this pipeline can be assembled from general-purpose capabilities: object storage for archiving long texts and task artifacts; message queues to support asynchronous tasks and decouple agents; container platforms to host inference and execution environments; and logging plus monitoring for usage aggregation and alerts.
Part 6: Conclusion — value-for-money is designed, not discovered
- Architecture side: sparse MoE delivers capacity without proportional compute; hybrid attention makes million-token context computationally affordable; N-gram embeddings trade table lookup for capacity; gated residuals provide training stability at scale.
- Model side: token efficiency determines how many tasks the same unit price can complete.
- Application side: the cost-reduction room enterprises actually control lies in prompt caching, context compression, task routing, and cost observability.
Launch checklist:
- Is the cache hit rate meeting expectations?
- Is cost per successful task traceable?
- Are budget alerts and token ceilings in place?
- Are failure rate and retry counts under control?
- Is quality being regression-tested against the evaluation set on a regular basis?
Three things worth remembering when selecting a model: make decisions on cost per successful task rather than price per million tokens; build a benchmark that fits your own business instead of relying only on public leaderboards; and use engineering to backstop the model’s weak spots. Get these three right, and “stronger and cheaper” turns into sustainable business returns.
