Chapter 54
Efficient Frontier Models and Reasoning Training
On this page
Recent frontier systems show that capability is increasingly a co-design problem across architecture, data, optimization, precision, communication, and inference-time computation.
Sparse activation changes the economic unit¶
DeepSeek-V3, a December 2024 foundation for this discussion, reports 671 billion total parameters while activating 37 billion parameters per token. Its technical report describes 14.8 trillion pretraining tokens and 2.788 million H800 GPU-hours for the official training run, including context extension and post-training but excluding prior research and ablation experiments. This is not the total research-and-development cost. The architecture combines a mixture-of-experts design, Multi-head Latent Attention, multi-token prediction, and an auxiliary-loss-free load-balancing strategy.
The system lesson is not that every model should copy one expert layout. Sparse activation separates three quantities that dense scaling often conflates:
- total parameter capacity, which affects checkpoint storage and aggregate expert memory;
- active parameters per token, which more directly control token-level compute;
- routed communication and imbalance, which can erase theoretical savings.
An MoE capacity plan therefore needs distributions, not only averages. Measure tokens per expert by layer and workload slice, overflow or dropped-token behavior, all-to-all bytes, hot-rank tails, expert memory residency, and useful throughput after communication. A balanced global histogram can still hide transient microbatch hotspots.
The mechanisms behind the state ledger¶
Part I introduced token-addressable history, compressed token records, and recurrent summaries. The dated model map in the optional research snapshot uses all three. The following derivations explain the operations behind those names before we compare specific hybrid configurations.
Multi-head Latent Attention: compress before caching¶
DeepSeek-V2 introduced Multi-head Latent Attention, or MLA, as a learned low-rank representation of K/V history with a separate position-handling path. Its serving attraction is avoiding storage of the fully expanded per-head keys and values. The low-rank representation is learned with the model; it is not a lossless compressor applied afterward to an arbitrary GQA checkpoint.
The underlying algebra can be understood with a simplified single-head, position-free example. Let a token's latent vector be c of width r, with k=W_k c and v=W_v c. Its score against query q is q^T W_k c, which equals (W_k^T q)^T c. Transform the query once, then compare it with cached latent vectors. Likewise, Σ a_i W_v c_i = W_v(Σ a_i c_i): aggregate latents first and expand the output afterward. This avoids reconstructing every old value on every step.
These equalities require compatible linear operations. Position-dependent rotations cannot generally be absorbed into one constant matrix, which is why the actual architecture separates positional and non-positional components. Normalization, head grouping, and projection layout also belong in the real execution plan. A kernel that expands all K/V vectors before attention can give back much of the intended bandwidth benefit.
For an illustrative comparison, ordinary GQA with eight KV heads of width 128 stores 2*8*128=2048 values per token per layer. A hypothetical latent cache of width 512 plus 64 positional values stores 576. At two bytes each and 32 layers, that is 128 KiB versus 36 KiB per token. This is a storage calculation, not a claim that the hypothetical models have equal quality or equal compute. Projection weights, workspaces, and any replicated latent state remain additional costs.
Sparse attention: selection becomes part of the model¶
Sparse attention replaces the full set of eligible keys with a smaller set. A local window is a fixed rule; a learned indexer predicts relevant positions; block-sparse methods select groups to improve memory locality. The resulting operator can be exact on its selected support, but it is generally not the same result as dense softmax over all history.
For example, if a selector drops the only key containing a required constraint, an exact attention kernel over the retained keys cannot recover it. Selector recall matters independently of kernel correctness. Here, selection also creates index and gather work that must be included in the comparison.
Native Sparse Attention makes learned hierarchical selection a first-class computation, combining compressed global summaries, selected token blocks, and a local window in a hardware-aligned design trained end to end. The DeepSeek-V4 report further combines token compression with sparse retrieval through compressed and heavily compressed attention paths. Compression reduces the candidates' representation cost; selection reduces which candidates receive expensive attention. They are distinct levers, and neither implies unbounded lossless memory.
Let context length be S, selected count k, index cost I(S), and full per-key attention cost a. Sparse work is closer to I(S)+ak than simply ak. A selector that scans a compact representation of all positions can still be linear in S, though with a smaller constant than full attention. At short contexts, index launches and gathers may cost more than dense attention. If k>=S, a correct fast path can skip selection and attend to all valid positions.
Test repeated identifiers, many similar distractors, multiple required passages, and evidence outside the local window. Measure selector time, index memory, top-k validity, gather locality, attention time, and the dense/short-context fallback. Report the quality budget separately from the speedup.
From an attention history to a matrix memory¶
A simple unnormalized linear associative memory stores a matrix S with shape [value_dim, key_dim]. At each position, it adds an outer product v k^T; a query reads S q. Expanding the recurrence gives a weighted sum of past values, with weights k_i^T q. In this raw-dot-product example the weights need not be positive or sum to one; some other linear-attention formulations add positive feature maps and a normalizing state. A fixed-size matrix also cannot retain arbitrarily many independent associations without interference.
For example, start at zero and write scalar values 2 and 5 with the same unit-norm key. Reading with that key gives 7 under a plain additive update, not the latest value 5. The delta rule corrects what the memory already predicts for the incoming key instead of repeatedly adding the whole value.
Gated DeltaNet: forget globally, correct selectively¶
The Gated DeltaNet paper combines a decay gate with a key-directed correction. In a simplified head, let alpha be the retention gate, beta the update gate, and let k have unit norm:
Decay applies to the old memory before the correction is computed.
The error is the incoming value minus the decayed memory's prediction for this key.
The rank-one correction targets one key direction; the query then reads the updated memory.
Take a one-row state [2, 9], key [1, 0], and incoming value 5. With both gates equal to one, the prediction is 2, the error is 3, and the new state is [5, 9]. The unrelated second direction is preserved. With alpha=0.5 and beta=0.5, decay gives [1, 4.5], the error is 4, and correction gives [3, 4.5]. Gates therefore control two different operations. The tests in tests/test_sequence_models.py check these exact examples and state replay.
This recurrence is the teaching mechanism, not a complete model block. Real implementations add learned projections, head grouping, short convolutions, gates, normalization, and output projections. State dtype can be wider than the input dtype because repeated updates accumulate error. Unit-norm keys make the overwrite interpretation particularly clear; do not assume that behavior for arbitrary key norms.
Kimi Linear extends this family with Kimi Delta Attention and combines linear-attention layers with MLA layers. Its reported KV and throughput gains are results for the evaluated architecture, kernels, contexts, and quality comparisons—not a drop-in guarantee for another model. For a hybrid, measure both the recurrent layers and the remaining full-attention layers; their state sizes and decode work differ.
Training need not execute a Python loop over all tokens. Rewriting a step as an affine state map permits composition of chunks. For maps S -> S A_1+B_1 and then S -> S A_2+B_2, the combined map is S -> S(A_1 A_2)+B_1 A_2+B_2. Associativity creates parallelism, although a practical kernel exploits structure instead of materializing large dense transition matrices. Decode uses the recurrent form because one new token arrives at a time. The two schedules should agree numerically within a declared tolerance.
State-space models and selective recurrence¶
A state-space layer also summarizes history, but its parameterization is not the delta rule. A simple discrete system has hidden state h_t, input u_t, and output y_t:
Transition, input, and readout maps control what is retained, written, and observed.
Part I develops the fixed-decay scalar recurrence. Change its retention to A=0.25 while keeping B=C=1, zero initial state and inputs [2,0,4]: the outputs become [2,0.5,4.125]. The contribution of the first token to the third state falls from 0.5 to 0.125; the state size is unchanged. The old input decays instead of remaining as an individually addressable KV entry. Structured transitions make larger states affordable. Selective state-space models make aspects of the transition/write/read depend on the current input, so different tokens can be retained differently rather than following one fixed convolution.
Mamba-2 develops structured state-space duality and an efficient chunked computation connecting these recurrences to structured matrix operations. “Transformers are SSMs” in that paper's title does not mean every full-softmax transformer can be replaced by the same fixed-size state with identical outputs. The useful connection concerns structured computations and schedules, with architectural assumptions.
Compare the scalar example with attention: a later query cannot necessarily recover the exact first input from the single value 4.5. Many input histories lead to that state. Increasing state size, learning selective retention, or adding attention layers changes the capability/resource tradeoff; it does not eliminate compression. During serving, preserve the recurrent state and any local-convolution history together. During training, validate chunked outputs and gradients against a sequential reference on short sequences before trusting a fast scan implementation.
These mechanisms explain why cache reuse and speculative rollback need architecture-specific handling. In a hybrid, a saved prefix must bind attention entries to the corresponding recurrent matrices and any convolution history. A rollback that truncates only the attention cache leaves the recurrent layers in the wrong state. Retain supported snapshots or replay from a consistent boundary.
Residual routing and learned lookup memory¶
Manifold-Constrained Hyper-Connections studies multiple residual streams and constrained mixing between them. A doubly stochastic mixing matrix has nonnegative entries with every row and column summing to one. The intent is to retain richer routing without unconstrained amplification in the residual transport. This is a training architecture change, not a post-hoc serving flag.
For an independent two-stream example, the matrix [[0.75,0.25],[0.25,0.75]] maps scalar streams [2,10] to [4,8]. Each new stream is a convex combination; the sum remains twelve. By contrast, multiplying both streams by two doubles the sum at every layer. The constrained example illustrates transport stability, not a proof that an entire nonlinear network cannot diverge. Layer transformations, gates, finite-iteration constraint enforcement, and optimizer behavior still matter.
Compare depth selection with stream transport¶
Attention Residuals, March 2026 v1, replaces fixed residual accumulation with learned selection over earlier layer outputs at the same token position. A layer-specific learned pseudo-query scores normalized source representations; a softmax weights the original representations as values. The query is learned, while its weights depend on the input through the keys. Block AttnRes reduces the retained sources to the embedding, completed block sums, and the current partial block sum when present.
Original schematic of two different routing axes. AttnRes selects sources across depth for one token. mHC transports a widened set of streams at the current depth and separately reads, transforms, and writes a layer update. Neither drawing is token-to-token attention.
For one coordinate of three vector-valued sources, values [2,4,10] and illustrative attention weights [0.2,0.3,0.5] produce 0.2*2 + 0.3*4 + 0.5*10 = 6.6. The full source vectors determine the weights. This is a selected aggregate, not the two-stream transport [2,10] -> [4,8] above. The mHC formulation, January 2026 v2 keeps readout and writeback mappings separate from its constrained residual transport; finite Sinkhorn iterations approximate the doubly stochastic constraint.
The engineering comparison therefore measures different state: earlier depth outputs or block summaries for AttnRes, versus widened current-depth streams and mixing work for mHC. These are activation and training-architecture costs, not interchangeable reductions in historical token KV. Compare matched training budgets, loss, activation memory and end-to-end execution. The figure does not establish which architecture wins.
Engram explores learned conditional memory through n-gram-based lookup as a complement to conditional expert computation. The basic distinction is computation versus lookup: a short token pattern selects stored vectors, while contextual processing determines how useful those vectors are. A lookup table can hold recurring local associations without recomputing them through every dense layer. Hash collisions, table size, placement, and the quality of the contextual gate are engineering concerns.
This is not the same as retrieving current documents from an enterprise corpus. Learned lookup parameters do not automatically provide citations, per-user permissions, or instant factual updates. Nor does discussing Engram establish that a particular released model uses it; require that model's own architecture evidence. Similarly, a fixed lookup-time complexity says little about host/device transfer latency or cache misses.
Reasoning from reinforcement learning¶
The January 2025 DeepSeek-R1-Zero study reports that large-scale reinforcement learning without a supervised fine-tuning warm start can elicit stronger reasoning behavior, but also reports readability and language-mixing problems. DeepSeek-R1 adds cold-start data and a multi-stage training process before and after reinforcement learning. The report also releases distilled dense models from 1.5B through 70B parameters and reports that reasoning behavior can transfer into smaller students.
This evidence changes the post-training design space in three ways.
- Verifiable rewards are high leverage. Mathematics, code, formal constraints, and tool outcomes support scalable outcome checks, but a reward is only as sound as its verifier and sandbox.
- Capability and presentation are separate objectives. A policy can improve task reward while degrading readability, language consistency, calibration, or safety.
- Distillation is a deployment lever. A high-compute teacher can create traces or targets for a smaller model, but the student still requires independent quality, contamination, and serving evaluation.
Reward design must account for false acceptance, reward hacking, length incentives, duplicated samples, and train-evaluation overlap. Log the full rollout policy, sampling configuration, verifier version, reward components, rejected trajectories, and update batch. Without those artifacts, an apparent algorithmic gain may be an unrepeatable data-selection effect.
From reasoning rewards to agent environments¶
The DeepSeek-V4.1 technical report, section 5.1, explicitly retains supervised fine-tuning, reinforcement learning, and on-policy distillation. It attributes the release's post-training advances to task synthesis, interactive environment construction, filtering, deduplication, and difficulty calibration rather than a new optimization algorithm. Its training unit includes a problem, an environment, and a verification system. This is a broader unit of curriculum design than an isolated answer with a scalar reward. The cited report file is pinned to repository revision 53e70b17d9acb8e0c423f0e4fe5702f25562b63d; the publisher's file metadata and reviewed assertion are recorded in the edition ledger.
Kimi K3's report, version 2, likewise connects long-context agentic RL to persistent rollout and sandbox state. A long trajectory consumes environment lifetime, tool execution, checkpoint storage, and policy-freshness budget as well as tokens. The infrastructure must distinguish a slow but productive rollout from a stuck tool, an invalid environment, or a policy exploiting its grader.
In on-policy distillation, a teacher provides learning targets on states visited by the student rather than only a fixed collection of teacher-generated solutions. This can reduce the mismatch between training states and deployed student behavior, but the teacher and its feedback remain fallible. Part II develops the post-training objectives and Part V the asynchronous rollout accounting; these model reports illustrate why the data and environment systems now matter as much as the named objective.
A causal comparison should hold the base checkpoint, rollout budget, verifier, environment family, and evaluation harness constant while changing one training ingredient. Then test unseen environment families, tool errors, changed task wording, and held-out verifiers. Separate gains from additional task diversity, longer reasoning, a different teacher, and a stronger optimizer. A same-base post-training claim, such as GLM-5.3's, does not by itself identify which of those ingredients caused the improvement.
Test-time scaling is a family of systems¶
Recent reasoning systems spend variable inference compute rather than mapping every request to one fixed decode. Test-Time Scaling in Reasoning LLMs, version 2, dated August 31, 2026, formalizes three regimes:
- single-trajectory scaling: extend one sequential reasoning path;
- leaf-level scaling: sample completed candidates and reduce them with voting, ranking, or verification;
- prefix-level scaling: branch or search over unfinished states.
These regimes have different state, parallelism, and failure behavior. Sequential scaling increases latency and retained context along one path. Leaf-level scaling is naturally parallel but can waste correlated samples and needs a trustworthy reducer. Prefix search introduces a frontier, partial-state ownership, pruning policy, and potentially large KV reuse opportunities.
A correct test-time compute budget includes input and output tokens, cached-prefix work, verifier or judge calls, tool execution, failed branches, communication, and wall-clock constraints. Accuracy at N samples is not comparable when one system uses a hidden candidate bank, a stronger verifier, or more expensive tools.
Choose an inference budget B against product value, latency, cost, and failure exposure rather than accuracy alone.
Design Exercises¶
- Design an MoE experiment that distinguishes expert imbalance from network saturation.
- What evidence would show that a reasoning RL gain comes from reward hacking?
- Compare the scheduler state required for sequential scaling, best-of-N, and prefix search.
- When should a distilled reasoning model replace its teacher in production?
- Why is a million-token context limit insufficient to compare Qwen3.8, Kimi K3, and a hosted model?
- How would you separate a post-training improvement from an architecture improvement?
Worked Solutions¶
- Slice expert load by layer, step, sequence class, and rank; replay a fixed routing trace with communication disabled or emulated; compare ideal and observed all-to-all time; and inspect whether the slowest expert or link predicts step time.
- Use hidden verifiers, adversarially varied problem forms, manual trace audits, reward-component ablations, and pass rates on tasks where superficial shortcuts do not work. Check whether reward rises while independent correctness or readability falls.
- Sequential scaling owns one growing KV history; best-of-N owns independent completed trajectories plus reducer state; prefix search owns a branching frontier, shared prefixes, pruning metadata, and branch-specific RNG. Their cancellation and memory-reclamation semantics differ.
- Replace the teacher only when the student meets slice-level quality and safety floors, lowers end-to-end cost or latency under the real workload, and has a fallback for tasks where compression removed necessary capability.
- Record native versus extended context, input modality, model revision, cache/recurrent layout, numerical format, and long-range quality. A supported length does not establish equal memory, latency, recall, or account access.
- First hold the base checkpoint and evaluation harness fixed while changing post-training. Then compare architecture changes with training data, compute, effort, and harness differences explicitly recorded. GLM-5.3 and GLM-5.3-Flash illustrate why related names do not imply the same base.