ARCHITECTURE INDEXTransformer / training reference

MODEL MECHANICS / REFERENCE

One equation for a Transformer training step

Kimi K3.1 Pro is the architecture reference. The optimiser and training procedure on this page are illustrative.

A training step is one map from a batch and a state to the next state. This is a framework with explicit choices, not a claim that every architecture uses the same operators. Kimi K3.1 Pro supplies the reference wiring. Its public model card and configuration describe the architecture; they do not specify a reproducible complete training run.

The single equation

(θ', m', v', n+1) =
  let h₀ = Assemble(Embed(tokens), Project(Vision(images)))
      z  = Head(RMSNorm(GraphFold[θ, graph, routes](h₀)))
      L  = Σ_{t∈U} [a_t + ln Σ_v exp(z_tv − a_t) − z_t,y_t] / |U|,
           a_t = max_v z_tv, U = valid next-token target positions
      g  = ReverseGraph[forward values, fixed discrete choices](∂L/∂z)
      m' = β₁m + (1−β₁)g
      v' = β₂v + (1−β₂)g²
      θ' = (1−ηλ)θ − η [m'/(1−β₁^(n+1))]
                       / (sqrt(v'/(1−β₂^(n+1))) + ε)
  in (θ', m', v', n+1)

The optimiser above is an illustrative AdamW option, not an attribution to Kimi. Learning rate and decay can be per parameter group. Skip globally empty supervision rather than dividing by zero; keep the true valid-target denominator across data-parallel workers and microbatches. The loss shown is next-token cross-entropy; RL, auxiliary terms and masked objectives are separately specified functions. Real-valued derivations do not specify floating-point reduction order, quantisation, routing tie-breaking or distributed scheduling.

Three graphs inside the fold

In a topologically ordered unrolling, each node is a written operator evaluated on earlier nodes. In reverse order, for every incoming edge x → y, add J_(y,x)^T · bar(y) to bar(x). Here bars are adjoints; the following local rules compute those products without materialising Jacobians.

Token mixing: dense, sparse and recurrent

Causal or sparse softmax attention

Q = XW_Q, K = XW_K, V = XW_V
s_ij = q_i · k_j / sqrt(head_dim)
A_ij = exp(s_ij − a_i) / Σ_{r∈J_i} exp(s_ir − a_i), j∈J_i; zero otherwise
a_i = max_{r∈J_i} s_ir; O = A V
J_i = {j : j≤i} for dense causal; a nonempty causal subset for sparse

For an incoming adjoint bar(O): bar(V)=Aᵀbar(O), bar(A)=bar(O)Vᵀ, and row by row bar(s)=A⊙(bar(A)−Σ_j A_j bar(A)_j), zero outside support. Then bar(Q)=bar(s)K/√d and bar(K)=bar(s)ᵀQ/√d. For a gathered sparse implementation, scatter-add adjoints at repeated key positions. Multiple heads concatenate and apply an output projection. The formulas hold within a fixed sparse support, not for arbitrary changes in the selection.

Kimi Delta Attention (KDA)

Using one head, column vectors, and S ∈ R^(d_key × d_value):

T_t = diag(α_t) S_(t−1)
e_t = v_t − T_tᵀ k_t
S_t = T_t + β_t k_t e_tᵀ
o_t = S_tᵀ q_t

This is the rank-one form of the published delta recurrence: expand the outer product to recover (I−β_t k_t k_tᵀ) diag(α_t) S_(t−1)+β_t k_t v_tᵀ. It does not require building the square transition matrix. Kimi's projections, causal short convolution, gates and output normalisation surround this cell. For the recurrent backward sweep add q_t bar(o_t)ᵀ to the state adjoint from the next position, call the total G. Then:

bar(q_t) = S_t bar(o_t)
bar(e_t) = β_t Gᵀ k_t;  bar(β_t) = k_tᵀ G e_t
bar(k_t) = β_t G e_t − T_t bar(e_t)
bar(v_t) = bar(e_t);  bar(T_t) = G − k_t bar(e_t)ᵀ
bar(S_(t−1)) = diag(α_t) bar(T_t)
bar(α_t)_i = Σ_j bar(T_t)_ij S_(t−1)_ij

These are the adjoints for the written recurrence, not a claim about Moonshot's actual kernel or scheduling. Chunkwise memory schedules can implement the same recurrence without the same intermediate storage.

Kimi K3.1 Pro gated sparse attention

An indexer scores causal candidate positions; J_i is its top-k shortlist, at most 2,048. A documented DSA-family index score is I_(t,s) = Σ_h w_(t,h) ReLU(q^I_(t,h) · k^I_s), distinct from the selected-position attention scores; take J_t = TopK over s≤t. The release-specific serving code supplies the actual projections and shortlist wiring. The selected keys then participate in the sparse softmax above, using the latent attention projections. The output gate multiplies each head's channels by a sigmoid before the output projection. The release uses 32 index heads of width 128; the main latent attention and the indexer are different paths. This is no longer the dense gated MLA of the Kimi K3 antecedent. Hard shortlist membership is locally constant away from switching boundaries. If scores affect the objective only through membership, the ordinary gradient to indexer-only parameters is zero there. To train them, specify an auxiliary objective or an estimator; DeepSeek's public indexer objective is one example, not a claim about Moonshot's training.

Depth mix and mixture of experts

For a depth-attention module, form candidates c_j from the embedding, completed block summaries and the available partial block. Use the learned depth query w:

a_j = softmax_j(wᵀ RMSNorm(c_j))
module_input = Σ_j a_j c_j

This softmax is over depth candidates, not token positions. A block summary is the sum of its module outputs; the partial summary excludes modules not yet evaluated. Its backward pass uses the same weighted-sum and row-softmax rules above, with a separate direct value path to c_j plus the score path through RMSNorm. Ordinary residual addition is a different depth mix.

For normalized sigmoid top-k MoE and one token x:

s_e = σ((W_r x)_e)
J = top-k(s + routing_bias)
p_e = s_e / Σ_{j∈J}s_j  for e∈J
z = W_down x
u = Σ_{e∈J} p_e Expert_e(z)
MoE(x) = Σ_{shared} Expert_shared(x) + W_up RMSNorm(u)
Expert(z) = W₂ ([4 tanh(g/4) · σ(g)] ⊙ [25 tanh(a/25)])
g=W_gate z, a=W_expand z

The bias in this routing formulation changes expert selection, not the uncorrected mixture numerator. For u's adjoint G, each selected expert receives p_e G, and bar(p_e)=Gᵀ Expert_e(z). If Z=Σ_selected s, then bar(s_e)=(bar(p_e)−Σ_j p_j bar(p_j))/Z on the selected support, followed by the sigmoid derivative. Shared experts also receive their own branch gradients. Hard top-k membership is piecewise constant and non-differentiable at switching boundaries; load-balancing rules, any surrogate and the procedure for updating routing bias must be specified separately. For dense feed-forward layers, use the single expert expression without routing.

Useful scalar derivatives: σ'(x)=σ(x)(1−σ(x)); (c tanh(x/c))'=1−tanh²(x/c). Backpropagate through the displayed SiTU product by the product rule. For any linear matrix Y=XW+b, bar(X)=bar(Y)Wᵀ, bar(W)=Xᵀbar(Y), bar(b)=column sums of bar(Y); integer token/vision slots scatter adjoints to their selected input rows.

Normalisation, the loss and the actual reference

For a row vector x, RMSNorm γ⊙x/r, r=√(mean(x²)+ε), has input adjoint g/r−x·mean(g⊙x)/r³, where g=γ⊙bar(y). Scale adjoints sum bar(y)⊙x/r across rows. In ordinary LayerNorm replace x by x−mean(x), and replace the first term g/r by (g−mean(g))/r; add the bias adjoint if a bias is present. For the written cross-entropy, bar(z_t)=(softmax(z_t)−one_hot(y_t))/|U| on valid positions and zero elsewhere. This zero on the output head does not mean that dropping prompt tokens upstream is valid.

Moonshot's Kimi K3.1 Pro model card and pinned release config specify 93 text layers, 69 KDA and 24 gated DSA (layers 4, 8, …, 92, 93), width 7,168, one dense feed-forward layer, and 896 routed experts with 16 selected plus two shared. The routed latent width is 3,584. The public card describes an open-weight multimodal model post-trained from Kimi K3, not a released optimiser trace or exact training recipe. The Kimi K3 report is the source for the antecedent KDA/AttnRes/LatentMoE equations. vLLM's Kimi DSA implementation is evidence about inference wiring, not training. This page expands the mathematical operators and explicitly separates the unknown parts; it does not claim a bitwise Kimi reproduction or an empirically measured Kimi speedup.

Where SAT, Lean and measurement fit

SAT means Boolean satisfiability. Use Boolean switches for module placement, optional sharing or a fixed finite set of sparsity choices. Ask whether any design obeys dependency, memory and cost constraints, and tighten a cost cap for optimisation. Integer or rational resource constraints can be expressed in SMT or integer programming rather than enumerated as bits. Hard architecture choices and continuous training are separate: differentiable or explicitly quantised optimisation needs its own formulation. Lean can check exact rewrites, constraints or an optimality certificate; a solver's candidate is not evidence of measured latency or quality.

Start with an identity such as masked-head compaction, rank-one KDA, or stable tiled softmax. Compare logits, loss, all parameter gradients and one update, including tied embeddings if applicable. Then profile a full step on the same GPU and record time, memory, communication and precision. A better algebraic count does not establish a faster training run.

Local derivative checks

Eight small CPU FP64 central finite-difference checks covered dense and fixed-support sparse attention, the KDA cell with a future-state adjoint, normalized MoE on fixed support, RMSNorm, LayerNorm, SiTU and masked cross-entropy. The largest absolute mismatch was 1.04×10⁻⁹, against a tolerance of 10⁻⁷. These checks do not verify a full model, optimiser, Lean proof or speedup.

Watch the animated explainer

4 min 52 sec. Follow one token through attention, the loss and the weight update. English captions are available in the player.

Download MP4 · Download text transcript

Read the transcript

A training step is a map

What does it mean to put a transformer training step in one equation? Not that the network is a single matrix. It means we can name every operation that carries a batch and its current state to a new state.

Read the equation in three passes. First run the forward graph. Then measure errors at selected positions. Finally send those errors backwards to update the weights and the optimiser’s memory.

Words become vectors

Begin with the phrase, the cat sat. Each token ID selects a row from a learned table. We keep the order of these rows; the vectors carry the features the model can use.

In a multimodal model, a vision encoder and projection can supply additional vectors. Assembling the inputs does not yet let the cat read the other words. The token graph determines who can read whom.

Compare, then forbid the future

Make three views of each token: a query, a key, and a value. The query is what the position asks for. The key is what another position offers to match. A dot product gives a score, scaled by the square root of the head width.

The camera follows the middle row. Cat may look at the and at itself, but not at sat. The mask removes future columns before softmax, so their final weight is exactly zero.

Turn scores into a weighted read

Within that permitted row, scores zero and log three become positive weights one and three before normalisation. Divide by their sum and we get one quarter and three quarters. These are illustrative numbers, not a model measurement.

Take a quarter of the first value and three quarters of the second. That is the new information for this position. A practical softmax first subtracts the largest permitted score. That leaves the weights unchanged and keeps exponentials in range.

Keep a path around each update

Token attention mixes positions. Depth is a separate graph: it connects module outputs across the network. One familiar block normalises its input, applies attention, and adds the result back to the original vector.

A feed forward module then transforms each position’s features, again with a normalisation and a skip path in this example. Some designs instead mix earlier depth summaries by attention. If a block loops with shared weights, every visit counts in the gradient.

Route each token to a few modules

Another graph routes tokens to experts. In this toy example four experts are available and two are selected. A routing bias can change which experts win, without entering the mixture weights we use to combine their outputs.

Selected experts are weighted and added. A shared expert can also contribute without competing for those slots. The gradient can flow through the selected branches, but it does not automatically teach the hard selection boundaries. Those need separately specified training rules.

Only valid targets count

The head produces one score per candidate next token. Cross entropy asks what probability the model gave the correct answer. If that probability is one quarter, the loss at this position is log four. Higher probability means lower loss.

Average over the valid target positions across the batch. Padding and unsupervised positions contribute no direct loss. But an unsupervised prompt token may still influence a supervised prediction through attention, so masking the loss is not the same as deleting the prompt.

Run the graph in reverse

Now reverse the arrows. At each arrow, the chain rule maps the downstream sensitivity to its input. When a tensor feeds two paths, their contributions add. This applies to residual branches, and to any repeated uses of shared weights.

An optimiser turns those gradients into a new state. Adam W, for example, keeps moving averages of gradients and squared gradients, corrects their initial bias, and applies decoupled weight decay. It illustrates our equation; it is not a claim about Kimi’s optimiser.

A proof is not a benchmark

Kimi K three point one Pro provides a concrete public wiring example. Its published configuration lists ninety three text layers: sixty nine Kimi Delta Attention layers and twenty four gated sparse attention layers. It selects sixteen routed experts from eight hundred and ninety six, plus two shared experts.

That tells us how the architecture is wired, not how to reproduce its training. Lean can check an algebraic rewrite; satisfiability can check a discrete design constraint. Neither tells us how fast the whole step runs. Compare logits, losses, gradients and the update, then actually measure time and memory.

Binary weights: how much activation precision is enough?

3 min 26 sec. An animated derivation of the best scale for fixed codes, a counterexample after the matrix multiplication, and what the native GPU measurements actually show.

Download MP4 · Download transcript · Reproduce: code, Lean and tested checkpoints on Hugging Face

The closed form, and its limit

For original activations x, fixed low-bit codes q, and nonnegative importance weights w, minimise Σi wi(xi − αqi)² with α ≥ 0. Let A = Σi wiqi² and B = Σi wixiqi. If A > 0, the exact solution is α = max(0, B/A); if A = 0, the objective is flat. Lean checked the algebra and a separate counterexample to treating this as a whole-model optimum.

Example: x = (2,1), q = (1,1), projection W = (1, −2). The exact projected input is zero. Weighting the two activation errors by 1 and 4 gives α = 6/5 and projected squared error 36/25; α = 0 gives zero projected error. Optimising the input approximation is not the same as optimising the projection.

Actual GTX 1660 SUPER results

Binary weights, activation modeHeld-out bits/byte ↓Prefill p50, ms ↓Combined index ↑
W1 / FP32 activations3.951871.1515100.00
W1 / 4-bit groups of 323.957270.884114.05
W1 / 2-bit groups of 8, weighted exact scale4.418920.863Did not qualify
W1 / 2-bit groups of 8, absmax scale4.506910.8739Did not qualify

Two frozen small research checkpoints, separate held-out WikiText-2 windows, batch one and 128 input positions. The native CUDA path matched 11,440,128 sampled integer group dots to a separate integer reference. Unlike activation reconstruction error, language quality was measured end-to-end. Qualifiers had to stay within 0.15 bits/byte of FP32 in both seeds; the index is the geometric mean of the loss and prefill ratios versus FP32, multiplied by 100. This is not a decode speed, full training or 890B result.

Follow-up: training with quantisation in the loop

In a separate matched training experiment, two-bit A2/G8 reached 3.94377 bits per byte, A4/G32 reached 3.94063, and FP32 activations reached 3.92031. The two-bit model improved from 4.41105 to 3.94377 when both checkpoints were tested using the same two-bit inference mode. Both fitted low-bit modes met the 0.15 bits-per-byte cutoff in both seeds. The two-bit group size used more scale overhead in this setup (48 KiB versus 40 KiB for the largest operand). This follow-up is distinct from the frozen-checkpoint audit shown in the video.

Read the video transcript

Two bits, one scale

01 | Two bits, one scale The weights of this tiny transformer are already binary: each weight stores a sign. But the activations, the numbers moving between layers, can use more bits. Here we compare full precision, four bits, and ternary codes stored in two bits, without retraining the model. The experiment asks two different questions. Can we make the activation approximation more accurate? And does that make the model read held-out text as well, at lower time and memory cost?

02 | Codes keep shapes; scales set size Take a small group of activations. A ternary code says negative, zero, or positive. The shared scale tells us how large the nonzero values should be. Four-bit codes have more levels, so they can keep differences the ternary codes erase. In the packed kernel, binary weight and activation planes are combined with bitwise AND and population count. The integer partial sums are exact for the encoded values. Multiplying by group scales afterwards does not undo the initial quantisation.

03 | Find the bottom of the parabola Fix the codes. Sum the squared reconstruction errors with nonnegative weights. Expanding gives a constant, minus twice the scale times the weighted dot product, plus the scale squared times the weighted code energy. When the energy is positive, completing the square locates the minimum at the dot product divided by the energy. If that value is negative, the best nonnegative scale is zero. With no code energy the loss is flat. Lean checks these exact algebraic cases.

04 | Input error is not output error Here is the trap. The true output is two minus twice one, which is zero. Using the same scale on both codes, the reconstructed output is the scale minus twice the scale. Its squared error is the scale squared, so zero is the optimum. The diagonal proxy instead weights the first input error by one and the second by four. It picks six fifths, giving true squared error one point four four. Why? It drops the cross term, where two input errors can cancel each other.

05 | A better A2 still misses the gate We tested two frozen tiny checkpoints on fresh WikiText Two windows, on a GTX sixteen sixty class GPU. Over eleven million sampled grouped integer dot checks agreed with the reference. The experiment did not train either checkpoint. Full precision activations gave three point nine five two bits per byte. Four-bit activations stayed close. The weighted two-bit fit beat its own absmax baseline, but was still about point four seven bits per byte worse than full precision. That misses the allowed margin of point one five.

06 | Four bits qualified here At batch size one and a one hundred twenty-eight byte prompt, four bits cut median prefill from one point one five two to point eight eight four milliseconds. It was the only alternative that met the quality gate. The qualifying index was one hundred fourteen point zero five against a baseline of one hundred. Smaller codes do not guarantee a smaller whole model or lower peak memory. These two-bit groups also need more scales, and the measured prefill allocation did not fall. This is an inference pilot, not a training or large-model speed claim.

Can checkpoint compression teach us a better binary training rule?

3 min 53 sec. Follow a four-bit weight update, the closed form of its unrounded limit, the rounding counterexample, and what an archive can and cannot reveal.

Download MP4 · Download transcript · Download the checked Lean proof

What actually compressed

On sampled packed four-bit training components, Brotli stored 96,284 of 212,896 bytes (45.23%); zstd-3 stored 105,294 bytes (49.46%). The four-bit embedding/head sample reached 36.25% and the feed-forward down sample 49.03%. Packed signs and seven-bit residuals were nearly incompressible in this run. The experiment checked 2,020 lossless round trips over 43 component groups with zero altered bytes. Size-only archival compression did not measure training speed, quality or full-checkpoint size.

The update and its closed form

The forward pass uses only the sign of nonzero state q. Divide the gradient by a per-matrix RMS (plus epsilon), clip this normalised value z to [−4,4], compute (7/8)q − (2/5)z, round to nearest even, clamp the integer to [−7,7] and map zero to the previous sign. The nonzero signed code fits in a nibble. The archive codec is not part of those numerical steps.

For the ideal real recurrence without rounding or clamping, qt = λtq0 − ηΣj=1…tλt−jzj. The Lean proof checks that exact expression and a counterexample to using it for the real rounded state. From q0 = 1 and z = 0.5, the actual rule proposes 0.675 and rounds to +1 at every step. The ideal recurrence instead reaches −311/4096 at step four. Neither path hits a saturation rail in this example.

Two sign vectors can also have the same simple compression cost and losses of 0 and 64. Compressibility is not a substitute for held-out evaluation. To infer an update rule from checkpoint changes, compare aligned packed state bits rather than entropy-coded archive bit offsets. Record gradients and preserve independent transitions for exact replay tests; sparse changes alone do not identify a training rule.

Can the bit changes recover the update?

In a separate replay experiment with actual packed-four states, aligned state XOR changed 2.84% of the bits, while the overlapping prefix of a Brotli archive changed about 49.97%. Reusing the preceding aligned bitmap predicted 30.65% of the next changed bits. With three calibration transitions and their actual gradients, fitted coefficients 0.874995 and 0.400003 missed 40 of 14,942,208 packed bits across six unseen one-step updates. More than one coefficient pair matched the calibration data, so this does not uniquely identify the trainer. It also does not demonstrate a better rule or compressed-domain matrix arithmetic.

Read the video transcript

Lossless compression of packed Transformer state

01 | Lossless compression of packed state A binary transformer can read one bit per weight while keeping more information for training. Here, the packed four-bit training samples compressed to forty-five point two three percent of their raw size. That is a saving of fifty-four point seven seven percent. Every tested byte came back exactly. To understand why, separate the one-bit sign used by the model, the small state changed by training, and the reversible codec that stores that state.

02 | What is actually stored? The sign determines the value used by each binary matrix in the forward calculation. Packed four stores an integer per coefficient, two four-bit codes to a byte. The sign of that integer supplies the forward value. Its magnitude carries additional training information. The seven-bit error feedback example is a different method. It keeps one sign bit plus seven feedback bits. It is not packed four with extra precision. For these packed four samples, the measured archive is equivalent to about one point eight one bits per stored weight. That is an archive average, not random-access memory or inference precision.

03 | Inside the four-bit update First divide the transient gradient by its matrix root mean square plus a tiny epsilon. Then clip that normalised gradient to minus four through plus four. Multiply the old integer state by seven eighths, and subtract two fifths of the normalised gradient. Round to the nearest integer, clamp to minus seven through plus seven, and if the result is zero, replace it with the old sign at magnitude one. Pack the resulting code again. The bounds and rounding constrain training; they are not archive compression.

04 | What the closed form says Turn rounding, saturation and the zero rule off, and hold the normalised gradient sequence fixed. Now the simplified update is linear. After each step, the previous state and the earlier gradient contributions are multiplied by lambda once more. The closed form is the decayed starting value minus a weighted sum of the gradients. Lambda is seven eighths; eta is two fifths. This formula does not solve the exact packed training trajectory, and real gradients depend on model and data.

05 | The ideal path can be wrong Start from plus one and use a normalised gradient of one half. The actual rule proposes zero point six seven five, then rounds back to plus one. The same thing happens again at every step. The ideal path carries that fraction forward. It is still positive at step three, but goes negative at step four. That difference is real information lost in the update, not a decompression error. Clipping and the zero rule are separate ways the exact path can differ.

06 | Different parts compress differently The CPU study checked forty-three real component groups across several representations. The packed four-bit subset is about two hundred and thirteen thousand sampled bytes, not an entire checkpoint. The tied embedding and output head stored at about thirty-six percent with Brotli eleven. The feed-forward up and down samples needed about forty-eight and forty-nine percent. Different byte patterns can lead to different ratios. This sample does not say why all those tensors differ, or tell us the result for a different model.

07 | Choose the codec for the job Z-standard level three stored about forty-nine point four six percent, with an encode time around one point one milliseconds. Brotli eleven got down to forty-five point two three percent but took around two hundred and sixteen milliseconds to encode. These timings are sums of per-component medians on one CPU thread. The already packed signs became slightly larger, and the seven-bit feedback barely shrank. Smaller storage here is not proof of faster training or better intelligence.

08 | Check the bytes, then the workload To validate a whole checkpoint, round-trip its actual contents and compare the bytes, then check full reload and the next update. Include metadata and state beyond the weight sample. Measure save and load cost on the real training path before changing it. Low precision and lossless compression answer different questions. One says what state survives an update. The other says whether those exact state bytes return. This clip reports the sampled experiment, not a result for the very large production model.