Kimi K3: the paper and proofs side by side

I wanted to work through K3's equations with the model and its proofs side by side. Kimi K3 is an open-weight model from Moonshot AI that works with text, images, and video, and its technical report describes 2.78 trillion learned parameters and a context window of up to one million tokens. It mixes attention with recurrent memory and picks a subset of its experts for each token. Kimi K3 technical report ↗ TorchLean gives us tensor programs and model definitions; FloatLib lets us specify their arithmetic. We'll start with one expert, then follow the recurrent state, attention, routing, and the sequence as a whole.

Read by chapter

Taking autoformalization into ML

Mathematicians have been putting research papers into Lean for years, and the Liquid Tensor Experiment and the Polynomial Freiman–Ruzsa project showed how people could work through substantial mathematics together (writing the definitions and filling in the arguments until Lean could check the proofs). I want us to do that for machine-learning papers too.

Now AI is helping with the translation itself. In September 2026, Anthropic reported a complete Lean formalization of Fermat's Last Theorem, building in part on Kevin Buzzard's community project. This is what people mean by autoformalization: taking mathematics written for people and producing definitions and proofs a proof assistant can check. Seeing this happen for research mathematics makes me want to push further with ML :)

There's also recent work around the Riemann hypothesis. OpenAI's Lean formalization of the quasi-Riemann hypothesis describes a zero-free region \(\operatorname{Re}(s)>7/8\) for the Riemann zeta function (the Riemann hypothesis itself would put every nontrivial zero on \(\operatorname{Re}(s)=1/2\), so the zero-free-region result is a different statement). What interests me here is the practice of publishing the mathematical argument together with a formal statement that you can open and inspect yourself.

A model report contains equations we can translate into tensor functions: how a recurrent state changes, how attention reads a cache, how a router chooses experts, and how their outputs are combined. Then we can ask whether an implementation computes those equations and prove properties that matter when we use it. Because those definitions can take different weights and dimensions, the proofs can cover a whole family of models. I'd call this model autoformalization. AI could help translate the equations and find proofs while Lean checks the arguments, but in this post I want us to work through the calculations ourselves, starting with small examples before the full tensor equations.

We can write the tensor computations and their mathematical properties together, and FloatLib supplies arithmetic definitions and rounding theory for the next question: what changes when we calculate with finite precision? That matters in ML, where the choice of precision and accumulation order can change a model's output. I want those choices to be part of the formalization, close to the equations that use them.

I think K3 is a good place to start because several of its architectural choices interact. Kimi Delta Attention (KDA) updates a recurrent memory, while Multi-head Latent Attention (MLA) looks back at individual cached tokens. It also retrieves summaries from earlier layers and sends each token through selected groups of weights (called experts), and an image goes through a vision encoder before it joins the language model. To formalize the model, we have to understand how those calculations share their inputs and state. Figure 2 and §2, pp. 3–4 ↗ Does splitting a sequence into two chunks preserve the output when we carry the state between them? Does the graph of tensor operations compute the same function as the paper equation? How large can a capped activation become? We can answer these with theorems about the definitions, and later ask how rounding changes the calculations.

In the Kimi team's introduction to K3, the architecture serves a larger ambition: a model that can keep working through long coding and research tasks. I like that they explain the memory and routing choices behind it, because those choices also give us mathematical questions we can settle. If a serving system pauses a calculation, resumes from a cache, or changes how it groups tokens, you'd want to know which changes preserve the function and which change its numerical behavior.

I'll start with the transformer calculations that K3 builds on, then work through its memory, attention, experts, and vision model, keeping the report beside the explanation. After that, the training and evaluation sections give us another part of the story: how the authors used those mechanisms and what they measured.

Start with a transformer

At each generation step, a language model looks at the preceding context and assigns probabilities to the next token. K3 does this with 93 layers, 2.78 trillion parameters, and a million-token context, but a plain transformer gives us a good starting point for understanding the calculations that K3 changes.

  1. 1

    Tokenize. First the text gets split into vocabulary pieces called tokens (roughly word fragments), and each gets an integer ID. "unhappy" might become two tokens: "un" and "happy." Everything downstream works with these integer IDs.

  2. 2

    Embed. Each token ID selects a learned vector from a lookup table. A vector is just an ordered list of numerical coordinates (K3 uses 7,168 of them per token), and training adjusts those numbers so the later layers can use them when predicting the next token. A concept need not live in one particular coordinate.

  3. 3

    Compute match scores. Three learned matrices project each token's vector into a query, a key, and a value. A dot product compares the current query with each key, and those scores determine how much each value contributes to the attention output.

  4. 4

    Mask the future. When predicting the next token, a position can only look at itself and earlier tokens, never later ones. This causal mask leaves future positions out of the weighted sum, and the usual attention notation writes their scores as negative infinity.

  5. 5

    Weight the answers. Softmax converts all the match scores for one token into nonnegative weights that sum to one (in the real-valued equation). Weights of 0.4 and 0.3, for example, multiply their value vectors by those amounts, and adding the weighted values gives the attention output.

  6. 6

    Update and continue. A residual connection adds the old vector back to the attention output. Then a feed-forward network processes that updated vector, and another residual addition carries the result to the next layer. So the residual path lets a block add an update to the vector it already has rather than replace it entirely.

Steps three through five fit into one line of the standard attention equation, where capital letters stand for tables with one row per token: holds the queries, the keys, and the values.

  1. takes every allowed query–key dot product. A dot product multiplies matching coordinates and sums them, giving one match score per position pair.
  2. Dividing by controls the scale of those scores. If the coordinate products are independent and each has variance one, their sum has variance , and this division brings it back to one (otherwise large score differences can make softmax concentrate heavily on one position). That variance argument is why people scale this way, but it isn't a law that every wider learned key must produce a larger score.
  3. is zero at allowed positions and is written as negative infinity at forbidden positions, excluding them from the normalization.
  4. Multiplying by at the end forms a weighted combination of the value vectors from all allowed positions.

Negative infinity here is shorthand for excluding a position, because a finite negative score still has a positive exponential over the real numbers, however small it is. So the real-valued hard-mask definitions give forbidden positions exactly zero weight. If a numerical implementation uses a finite sentinel instead, you have to check that sentinel against the masking behavior you intend.

Conventional multi-head attention runs this calculation across many attention heads in parallel. Each head uses its own separate query, key, and value projection matrices, so different heads can learn to pay attention to different things: one might track syntactic structure, another semantic role, another pronoun reference. K3 uses 96 heads. Their outputs get concatenated and projected back to the model width. A conventional cache with separate keys and values for every head multiplies its payload by the head count, while K3's MLA cache keeps a shared latent representation instead (we'll count that smaller representation separately).

Dot products alone don't encode where a token occurs in the sequence. Many transformers add positional information for that, and rotary positional embeddings (RoPE), for example, rotate query and key coordinates according to position. K3 uses NoPE MLA, whose shared-key coordinates stay unrotated, and its KDA layers carry order through sequential state updates (change the order of the inputs and you change which state each update receives).

Every block computes , and the representation going into the next block is . If is small, the original vector survives nearly unchanged. Over many layers the residual stream accumulates the blocks’ contributions, so a later block receives information written at several earlier depths in one sum, and K3’s AttnRes keeps those earlier block sums available for separate retrieval.

Most of the model's parameters live in the feed-forward half of each block. It takes the current hidden vector, projects it up to a wider hidden space, applies a nonlinearity, and projects back. In K3 this becomes a mixture-of-experts layer rather than one dense network, and each token only activates a small fraction of the available capacity. But the basic pattern is the same.

Training processes many token positions in parallel, but inference is different: the model generates one token, appends it, and runs again. Keys and values from previous steps don't change, so implementations save them in a KV cache that grows by one entry per token per attention layer. That's the trade-off the original transformer design made. Instead of compressing history into a fixed recurrent state (like an LSTM would), it keeps the full history directly accessible, and storing that history costs more as the context grows. K3's hybrid attention is one way to manage the growing cache.

The Attention Is All You Need paper from 2017 made this pattern work at scale. Later decoder models have changed normalization, positional encodings, activations, and attention layout, but the alternating rhythm (attention to mix between positions, then feed-forward to transform within one position, then residual addition, then the next layer) stayed recognizable all the way through to K3.

The cost of a longer, larger model

We can make a transformer larger by adding layers, widening its vectors, or using longer sequences. Longer sequences enlarge the attention cache, and more experts mean more weights to store even when each token uses only a few. Let's look at how K3 handles these costs.

Attention and a growing cache

For a full causal sequence of length , one attention layer has permitted query–key pairs. Efficient kernels can avoid storing the full score matrix, but they don't turn quadratic attention into a constant-size recurrence, and during generation the KV cache still grows by one entry per new token in every full-attention layer.

So how do you shrink that cost? Models do it in two broad ways: store less information for each previous token, or replace the growing table with a fixed state that is updated after every token. K3 uses both. Multi-head Latent Attention (MLA) keeps one compressed entry for each earlier token, so a layer can still look back at individual positions. Kimi Delta Attention (KDA) keeps a fixed-size recurrent matrix instead, so its memory does not grow with sequence length.

More parameters, more matrix work

In a transformer, the feed-forward network often owns most of the parameters. Sparse mixture-of-experts models keep many feed-forward networks but route each token through only a few, and the Switch Transformer demonstrated this at trillion-parameter scale. Only the selected experts compute an output for a token, but all the expert weights still need storage (and routing adds load-balancing and communication costs on top).

One residual stream across many layers

A conventional residual stack carries a single running sum. By layer ninety, that vector contains contributions from every earlier block, so what if the current layer wants one particular old representation? It can't pick that out directly. It receives the sum. Attention Residuals changes the depth path: block summaries remain visible and the current layer retrieves a weighted mixture. K3 stores summaries of groups of layers, rather than a separate summary for every layer.

Bringing images into the sequence

A vision transformer turns an image or video into patch tokens. A multimodal language model must decide where those tokens enter, how their feature width matches the language backbone, and whether training treats visual and text examples as one sequence from the beginning. In my formalization I have to pin down the projection to the language backbone's width and where the visual tokens enter the sequence.

Kimi's earlier Kimi Linear work developed Kimi Delta Attention as a gated delta-rule recurrence and paired mostly recurrent layers with occasional full attention. K3 brings that hybrid into a much larger system, adds depth retrieval and a latent expert space, and trains the result as a native multimodal model.

K3's architectural choices

KDA and MLA split the sequence problem: KDA carries a fixed-size summary forward, while periodic MLA layers can still inspect individual cached tokens. AttnRes retrieves earlier summaries across depth, and Stable LatentMoE expands capacity across width without running every expert. MoonViT-V2 turns images and video into vectors the language backbone can consume.

Put together, that's a model with 2.78 trillion parameters that activates 104 billion of them for each token, accepts text, images, and video, and supports a context window of 1,048,576 tokens. And Moonshot released the weights! That matters to me, because it gives the formalization a concrete object to aim at instead of an architecture reconstructed from an API description.

2.8Ttotal parameters
→
104Bactive per token
·
1Mmaximum context
  • sequence

    KDA compresses the earlier tokens into a fixed-size matrix that changes after each new token.

  • global

    Three KDA layers are followed by one MLA layer to look back at individual cached tokens, and layer 93 is forced to MLA as well.

  • depth

    AttnRes keeps block summaries so a later layer can choose among earlier depth states instead of receiving only one running sum.

  • width

    LatentMoE sends each token through 16 of 896 experts. An expert is a separate feed-forward network, and sparse routing avoids running all 896.

  • vision

    MoonViT-V2 pools images and video into visual tokens with the same 7,168-wide representation expected by the language model.

Together they let K3 grow in context, depth, and parameter count while accepting both text and visual inputs. Figure 2 and §2, pp. 3–4 ↗

Across the architecture, data, and training recipe together, the Kimi team reports about 2.5× better scaling efficiency than Kimi K2. That number comes from a fitted loss-versus-compute curve on a validation set deliberately different from the training data, so it's an empirical result (not a serving-speed measurement, and not a Lean theorem). So which of those changes helped most? I can't tell you, because the report doesn't split the gain among KDA, AttnRes, LatentMoE, data, and optimizer changes. §3.2 and Figure 7, pp. 10–11 ↗

The report also gives results for coding, search, tool use, and web development, and I'll come back later to the scores and the evaluation conditions behind them. Abstract and Figure 1, pp. 1–2 ↗

The explicit equations are enough to get started :) We can take one expert, write its matrix products and activation in Lean, and prove that the graph computes that equation. Then we can use the expert inside a routed layer. Once that calculation is clear, I want to ask what changes when we store the weights and run the operations at lower precision, which is where FloatLib's arithmetic definitions and rounding bounds come in.

Reading the paper with Lean beside it

Okay... imma try something a little different here :) I'd like to read the paper on one side and follow the Lean definitions and proofs alongside it. This is how I imagine working through an ML formalization: we read an equation, try a small tensor example, and see exactly what we've proved about it before moving to the next part of the model.

Click “Open PDF” on the left and follow along. I'll start with one expert, then work through K3's recurrent memory, attention, and complete decoder, and you can change the numerical examples as we go and open the corresponding Lean source. I'd love future model reports to be shared this way, with the mathematics and its formalization close enough to read together.

Report Figure 2, p. 3

Recurrent memory, depth attention, and experts

I find Figure 2 easier to follow as three separate directions of information flow. Along the token sequence, KDA remembers and MLA looks back globally. Along model depth AttnRes chooses earlier summaries, and across model width LatentMoE chooses a small set of experts.

Sequence, depth, and width Sequence KDA carries state forward;MLA reads earlier tokens. 93 layers DepthAttnRes retrievesearlier block sums. Width LatentMoE selects16 of 896 experts.
It's still one 93-layer stack, in which KDA and MLA mix information across tokens, AttnRes retrieves across depth, and LatentMoE selects transformations across width.
In Lean

You can see the same separation in the types: KDA and MLA are sequence mixers, AttnRes owns the depth state, and LatentMoE is a channel mixer.

Writing one expert in Lean

An “expert” sounds like a whole model, but here it's a feed-forward network with three learned matrices. Two of them make the gate and value branches, SiTU combines their coordinates, and the third matrix produces the output. Routing decides which experts to call, but I'd rather understand this one function before worrying about choosing among 896 of them.

Ok let's start with the sums and shapes. We'll write the tensor function, build the same calculation from graph operations, and use the existing equality theorem on a tiny example. The proof uses real-valued tensors. Rounding the arithmetic is a further question we can tackle once those two descriptions agree.

Lean keeps the program and the proof together

What I find useful about Lean is that it's both a programming language and a theorem prover, so we can define a layer as a function, run a supported numerical version of it, and state a theorem about the definition in the same language. Its tensor types record the input and output shapes too.

For example, K3 caps the two branches of its SiTU activation before multiplying them. I'll write that as a function of two real numbers and ask how large its result can get. With the paper's caps of 4 and 25, the theorem below bounds the scalar output by their product, 100, for every pair of real inputs, and you never need to choose particular weights to prove this property of the equation.

/-- Smoothly cap a scalar at magnitude `cap` using `cap * tanh (x / cap)`. -/
def softCap {α : Type} [Context α] (cap x : α) : α :=
  cap * MathFunctions.tanh (x / cap)

/-- With Kimi K3's caps `4` and `25`, every coordinate is bounded by `100`. -/
theorem paper_caps_bound (gate up : ℝ) : |scalar 4 25 gate up| ≤ 100 := by
  have h := abs_scalar_le_mul_caps (gateCap := (4 : ℝ)) (upCap := (25 : ℝ))
    (by positivity) (by positivity) gate up
  norm_num at h ⊢
  exact h
Full source

Let's evaluate the cap at 2 and then the full SiTU response at gate 2, up 6. These commands use Float so we can run the calculation. Hover over softCap or the theorem name to inspect the types and assumptions. Those two decimal outputs are rounded evaluations, while the theorem below is about real numbers.

import KimiK3.FeedForward.Activation

open KimiK3.SiTU

-- Float gives us a runnable value; the real-valued theorem quantifies over every input.
#eval softCap (4 : Float) 2
#eval scalar (4 : Float) 25 2 6
#check softCap
#check paper_caps_bound
Lean output
1.848469

9.585417

KimiK3.SiTU.softCap {α : Type} [TorchLean.Context α] (cap x : α) : α

KimiK3.SiTU.paper_caps_bound (gate up : ℝ) : |scalar 4 25 gate up| ≤ 100

Dependent types catch a different class of bug. A KDA state carries its two dimensions in the type Tensor α [keyDim, valueDim], so a matrix with those axes reversed has a different type (as long as those dimensions differ). When the graph connects an output wire to the next layer's input, Lean checks that the shapes agree, which catches incompatible shapes before execution (though if two axes have the same size, the type can't tell you that you swapped them).

I also build the calculation as a graph: the GraphSpec files in this example connect typed tensor operations such as multiplication and tanh. Evaluating those nodes over real numbers should return exactly the same tensor as the reference function, and a denotation theorem proves that equality, which lets us check the graph's wiring against the equation.

To connect a fused GPU implementation to this equality, we'd need a bound on how much its arithmetic can change the answer. Here we'll work through the real-valued calculation.

We'll use this approach for the recurrent update and the sequence of decoder steps too, and even though their statements are larger, we can still follow the function, its assumptions, and the proof.

Writing the model in Lean

I write each layer as a function between tensors, and a recurrent layer also takes a state and returns an updated one. Here's the KDA step: it updates the memory, then reads from that new memory to produce the current token's output.

A recurrent step and its return type

In a Lean definition, the colon separates a name and its arguments from its type. In the block below, step takes a state and an input and returns a pair (the updated state and an output tensor), and that return type appears after the final colon. Since the state type is the same before and after the call, the update must preserve the matrix dimensions. Then comes :=, which means "is defined to be," and everything after it is the actual calculation.

/-- One recurrence step returns the updated state and its current-token output. -/
def step (state : State α keyDim valueDim) (input : KDA.Input α keyDim valueDim) :
    State α keyDim valueDim × Tensor α [valueDim] :=
  let next := update state input
  (next, read next input.query)
Full source

You can try this with a zero memory, a key and query of [1, 0], and a value of [3]. Then the update writes into the first row, and reading that row returns 3. Hover over memory, token, or step to inspect their types.

import KimiK3.Sequence.KDA
import TorchLean.Tensor.Literal

open TorchLean

-- One head with two key coordinates and one value coordinate.
def memory : KimiK3.KDA.State Float32 2 1 := [[0], [0]]
def token : KimiK3.KDA.Input Float32 2 1 :=
  { query := [1, 0]
    key := [1, 0]
    value := [3]
    retention := [1, 1]
    writeStrength := 1 }

-- Read the first output coordinate.
#eval (KimiK3.KDA.step memory token).2.getScalar ⟨0, by decide⟩
#check KimiK3.KDA.step
Lean output
3.000000

KimiK3.KDA.step {α : Type} [Storage α] [Context α] {keyDim valueDim : ℕ} (state : KimiK3.KDA.State α keyDim valueDim)
  (input : KimiK3.KDA.Input α keyDim valueDim) : KimiK3.KDA.State α keyDim valueDim × Tensor α [valueDim]

Scalar types and tensor shapes

The Greek letter α (alpha) names the scalar type. Most proofs here use real numbers, while an executable calculation can use a finite format such as a 16-bit float. Definitions that leave α open specify the operations they need, so we can reuse their tensor layout with different arithmetic, but a theorem about real arithmetic still needs a refinement argument before it describes rounded execution.

A type like Tensor α [4, 2] means a tensor of α-values with four rows and two columns. That shape [4, 2] is right there in the type, not hidden in a runtime assertion, so Lean checks these dimensions when it typechecks the program and connecting incompatible shapes produces a type error before the calculation runs.

Here's a small shape puzzle before the larger equations: how many values does a tensor with no axes hold? One! Tensor α [] holds a single scalar (no axes doesn't mean no values), while Tensor α [0] is an empty vector, because its one axis has length zero. Since the number of entries is the product of the axis lengths, and the product of no lengths is one, a reduction can return a scalar tensor without introducing a different container type.

Indices, tensors, and growing caches

Fin n pairs a natural number with evidence that it's less than n, so an expert ID of type Fin 896 ranges from 0 to 895. Passing 1000 would require a proof of the false inequality 1000 < 896 (good luck with that), so Lean rejects it.

The public sequence API takes tensors and returns tensors. Some internal caches use a List because they grow as tokens arrive, while the graph takes packed tensors with fixed shapes for one step. To relate the two we need to show that packing the cache preserves the update and the output, since fixing the shape alone would leave the order of the cached entries unchecked.

Definitions and theorems

A structure bundles named fields. A model record can hold weight matrices, a cache record can hold state, and a probability record can pair a number with evidence that it's positive. To see how those fields affect the model, follow the functions that consume them.

A def defines a function or value. It consumes structures and produces new ones (or produces tensors). This is where the actual computation happens. A theorem makes a claim about what a def returns: after theorem, everything up to := by is the statement being proved, and the lines after by are tactic commands that Lean uses to build a proof term that its kernel verifies. If you see simp or ring or linarith, those tactics simplify expressions, normalize polynomial identities, or solve linear inequalities, and Lean checks the proof terms they produce.

Describing tensor operations with Term

For the graph version, we use Term Γ shape, which is a typed expression in a computation graph. Its result is a tensor of shape shape, and Γ lists the shapes of its available inputs. You build expressions by composing Term values with Term.op, naming each primitive operation explicitly. Then Term.eval gives the graph a mathematical meaning by plugging in actual tensors, and specFwd evaluates a whole graph model at once.

We'll often prove an equality of this form: model.specFwd params inputs = referenceFunction inputs. It says the graph and the reference function produce the same result, so we can inspect the function first and then check how the graph implements each operation.

From an expert equation to its graph

Let's put an equation next to each part of Expert.forward. I'll use a row vector for the input, matching the [input, output] matrix layout in my source, because that convention matters when we write the products.

Three matrix products and SiTU

Write \(d\) for the input width, \(h\) for the hidden width, and \(o\) for the output width. The expert has gate and up matrices \(G,U\), and a down matrix \(D\):

Input and the two projection matrices.
Output projection and hidden branches.

A projection makes each hidden coordinate by weighting and adding the input coordinates. For \(0\le j<h\), the two sums are:

Gate projection.
Up projection.

Now take positive caps \(c_g,c_u\). The sigmoid \(\sigma(t)=1/(1+e^{-t})\) lies between zero and one, and SiTU uses it to gate two smoothly capped branches, giving a hidden vector \(z\):

The SiTU hidden coordinate.
The final output projection.

Notice that the sigmoid sees the original \(g_j\), before capping. Applying it to \(c_g\tanh(g_j/c_g)\) instead would give a different activation, even though every tensor shape would still match. That's one of the choices our equation and graph need to agree on.

/-- Evaluate one SiTU-GLU expert. -/
def forward (expert : Expert α inputDim hiddenDim outputDim) (gateCap upCap : α)
    (x : Tensor α [inputDim]) : Tensor α [outputDim] :=
  let gate := Tensor.vecmat x expert.gateWeight
  let up := Tensor.vecmat x expert.upWeight
  Tensor.vecmat (SiTU.vector gateCap upCap gate up) expert.downWeight
Full source

Here's the same calculation in Lean. Both gate and up have shape [hiddenDim], so SiTU can combine matching coordinates, and the final multiplication returns [outputDim].

Each weight matrix has one axis for the incoming coordinates and another for the outgoing ones. For an input of width inputDim, both gateWeight and upWeight have shape [inputDim, hiddenDim], so the two products meet at the same hidden width, where SiTU combines matching coordinates. Then downWeight has shape [hiddenDim, outputDim], and just reading those shapes tells you which matrix acts at each stage before you inspect any values.

The same calculation as a graph

/-- Typed forward expression for one SiTU expert, given input and parameter terms.

Use this form to embed an expert in a larger graph such as Stable LatentMoE.
-/
def term {Γ : List Shape} (inputDim hiddenDim outputDim : Nat)
    (input : Term Γ [inputDim])
    (gateWeight upWeight : Term Γ [inputDim, hiddenDim])
    (downWeight : Term Γ [hiddenDim, outputDim])
    (gateCap upCap : Term Γ []) : Term Γ [outputDim] :=
  let gate := Term.op (PrimOp.broadcastVecMat [] [] [] inputDim hiddenDim
      (Shape.CanBroadcastTo.refl []) (Shape.CanBroadcastTo.refl []))
    (.cons input (.cons gateWeight .nil))
  let up := Term.op (PrimOp.broadcastVecMat [] [] [] inputDim hiddenDim
      (Shape.CanBroadcastTo.refl []) (Shape.CanBroadcastTo.refl []))
    (.cons input (.cons upWeight .nil))
  let cappedGate := GraphSpec.softCapTerm [hiddenDim] gateCap gate
  let sigmoidGate := Term.op (PrimOp.sigmoid [hiddenDim])
    (.cons gate .nil)
  let gated := Term.op (PrimOp.mul [hiddenDim])
    (.cons cappedGate (.cons sigmoidGate .nil))
  let cappedUp := GraphSpec.softCapTerm [hiddenDim] upCap up
  let hidden := Term.op (PrimOp.mul [hiddenDim])
    (.cons gated (.cons cappedUp .nil))
  Term.op (PrimOp.broadcastVecMat [] [] [] hiddenDim outputDim
      (Shape.CanBroadcastTo.refl []) (Shape.CanBroadcastTo.refl []))
    (.cons hidden (.cons downWeight .nil))
Full source

The graph keeps those operations visible. Its two matrix products make \(g\) and \(u\), softCapTerm makes each capped branch, and the sigmoid node reads the uncapped gate. A multiplication then combines them before the down projection, and Lean checks the shape of every connection.

I'm checking two things here. The types tell us that the dimensions fit, and the equality theorem tells us that this particular wiring computes the intended function. Swap two same-shaped matrices and you'd pass the first check, but you'd generally change the equation we have to prove.

A tiny expert we can work through

For a hand calculation, I'll take two input coordinates, two hidden coordinates, and one output. These toy matrices make the first two products easy:

Toy input and gate weights.
Toy up and down weights.

Then \(g=(1,2)\) and \(u=(2,6)\). With the paper's caps of 4 and 25, we get these values to six decimal places:

Illustrative hidden activation.
Illustrative output.

Here's how I instantiate the graph theorem for that example. The square brackets construct tensors because the weight fields and input have tensor types, and Lean checks the rows and columns while elaborating them. We use \(\mathbb R\) since we're proving a statement about real-valued tensors (the decimals above are only there to help us work through the calculation).

import KimiK3.GraphSpec.Expert
import TorchLean.Tensor.Literal

open TorchLean

namespace ExpertExample

-- Two input coordinates, two hidden coordinates, and one output coordinate.
noncomputable def expert : KimiK3.Expert ℝ 2 2 1 :=
  { gateWeight := [[1, 0], [0, 1]]
    upWeight := [[2, 0], [0, 3]]
    downWeight := [[1], [-1]] }

noncomputable def input : Tensor ℝ [2] := [1, 2]

-- Instantiate the existing theorem with these weights and the paper's caps.
example :
    (KimiK3.GraphSpec.Expert.model 2 2 1).specFwd
        (KimiK3.GraphSpec.Expert.parameters expert)
        (KimiK3.GraphSpec.Expert.inputs input 4 25) =
      expert.forward 4 25 input := by
  exact KimiK3.GraphSpec.Expert.specFwd_eq_forward expert input 4 25

end ExpertExample

We reuse the existing expert and its proof, so we don't need a new model wrapper for these dimensions. The theorem below leaves the weights and widths general.

Graph equivalence for arbitrary weights

/-- The expert graph computes `Expert.forward`. -/
theorem specFwd_eq_forward {inputDim hiddenDim outputDim : Nat}
    (expert : KimiK3.Expert ℝ inputDim hiddenDim outputDim)
    (input : Tensor ℝ [inputDim]) (gateCap upCap : ℝ) :
    (model inputDim hiddenDim outputDim).specFwd
        (parameters expert) (inputs input gateCap upCap) =
      expert.forward gateCap upCap input := by
  simp [model, parameters, inputs, Model.specFwd,
    TorchLean.Pack.append, Args.vars, Args.weakenLeft, Args.rename,
    Term.rename, Term.eval_var, Env.tget,
    KimiK3.Expert.forward, Params, Inputs]
  rfl
Full source

The source proof expands the model's parameter and input packaging, then uses the evaluation rules for the graph operations, and what those rules leave is the three matrix products and SiTU expression from Expert.forward. That's why the result works for every choice of weights and dimensions, not only our tiny example.

A bound on the expert's output

For the hidden activation, we can get a bound without inspecting any learned weights. Since \(|\tanh(t)|\le1\) and \(0<\sigma(t)<1\), the paper's caps \(c_g=4\) and \(c_u=25\) give:

The paper's hidden-coordinate bound.

I want to be careful about where that 100 applies, because the down matrix can amplify the hidden vector. For an output coordinate, the triangle inequality gives:

Bound the absolute value of the output sum.
Use the SiTU bound for each hidden coordinate.

In the toy example the absolute down weights sum to two, so this gives \(|y_0|\le200\). It's a loose bound, but it holds for every real input to those weights. The example above gave us one output, and the inequality tells us what can happen across all inputs. That's a useful first result to have before putting the expert inside a larger routed layer :)

The output bound in Lean

We reuse the SiTU theorem for each hidden coordinate, expand the vector–matrix product, and apply mathlib's bound on the absolute value of a finite sum.

import KimiK3.FeedForward.Expert
import TorchLean.Tensor.Algebra

open TorchLean
open scoped BigOperators

example {d h o : Nat} (expert : KimiK3.Expert ℝ d h o)
    (input : Tensor ℝ [d]) (k : Fin o) :
    |(expert.forward 4 25 input).getScalar k| ≤
      100 * ∑ j : Fin h, |Tensor.get2 expert.downWeight j k| := by
  let z := KimiK3.SiTU.vector 4 25
    (Tensor.vecmat input expert.gateWeight) (Tensor.vecmat input expert.upWeight)
  have hz (j : Fin h) : |z.getScalar j| ≤ 100 := by
    simpa only [z, KimiK3.SiTU.vector, Tensor.getScalar_zipWith] using
      KimiK3.SiTU.paper_caps_bound
        ((Tensor.vecmat input expert.gateWeight).getScalar j)
        ((Tensor.vecmat input expert.upWeight).getScalar j)
  change |(Tensor.vecmat z expert.downWeight).getScalar k| ≤ _
  rw [Tensor.vecmat, Tensor.getScalar_contract_vecMat_eq_sum]
  calc
    |∑ j : Fin h, z.getScalar j * Tensor.get2 expert.downWeight j k| ≤
        ∑ j : Fin h, |z.getScalar j * Tensor.get2 expert.downWeight j k| :=
      Finset.abs_sum_le_sum_abs _ _
    _ ≤ ∑ j : Fin h, 100 * |Tensor.get2 expert.downWeight j k| := by
      apply Finset.sum_le_sum
      intro j _
      rw [abs_mul]
      exact mul_le_mul_of_nonneg_right (hz j) (abs_nonneg _)
    _ = 100 * ∑ j : Fin h, |Tensor.get2 expert.downWeight j k| := by
      rw [Finset.mul_sum]
GraphSpec/Expert.lean, complete worked pattern ↗

Figure 2, p. 3 · Table 1, p. 11

Checking K3's published dimensions

I like that we use the same Lean definitions for tiny examples and for the published 93-layer model. All published dimensions live in one checked configuration, so the 2.78-trillion-parameter architecture is just one value of those general definitions.

7,168language width
93backbone layers
96attention heads
896routed experts
16active experts
1,048,576maximum context

Explore the 93-layer schedule

KDA fills three positions, MLA fills the fourth, and layer 93 is forced to MLA so the backbone ends with global attention.

69 KDA24 MLASelect a layer

§2.1.1, pp. 4–5 · Equation 1

KDA's fixed-size recurrent memory

For one head, KDA carries a matrix \(S_t\) from one token to the next, with rows for key channels and columns for value channels. That matrix is the memory. It has a fixed size even when the sequence keeps growing.

Equation 1 packs three actions into one line. Reading left to right matters: fade the old memory by α, erase the part aligned with the current key, then write the current value back along that same key. Only after the update does the query read the state.

(1)
S_t = (I - beta k k^T) Diag(alpha) S + beta k v^T
o-tilde_t = S_t^T q_t
  1. 01

    Decay. Diag(alpha)S scales each key row. Small retention forgets that row quickly.

  2. 02

    Correct. k^T Diag(alpha)S asks what value the old state already associates with this key.

  3. 03

    Write and read. The delta rule adjusts that association toward v_t, with strength β_t, and then the query q_t reads the updated matrix.

Let's reduce this to one key coordinate and one value coordinate, so the memory is now one number s. Set the key and query to one. Decay first changes the old memory to αs, and then correction and writing give:

The new memory adds a scaled prediction error to the decayed memory.

Suppose the old memory is 6, retention is 0.8, the current value is 10, and write strength is 0.5. After decay the old prediction is 4.8, which is off from the current value by 5.2, so the update adds half that error and leaves memory 7.4. A write strength of one would replace 4.8 with 10, and a strength of zero would leave only the decay. (I picked these numbers so you can do the arithmetic in your head. They're small real-number examples of the equation, not measurements from the released model.)

Does token order still matter? It does. Starting from zero with retention and write strength both 0.5, values 2 then 10 leave memory 5.25, but values 10 then 2 leave memory 2.25. So parallel implementations can regroup compositions of state updates, but they can't permute the tokens and expect the same result. The matrix version stores many key-to-value associations at once, and the same correction principle applies along the current key.

Run a 2 × 2 delta updatesmall dimensions, same equation
incoming S
1.000.20−0.300.70
→
decay
→
correct + write

§2.1.1, pp. 4–5 · Equations 2–6 · Figure 3

Preparing the queries, keys, values, and decay

Before KDA updates memory, the token is turned into query, key, and value vectors. A short convolution mixes each vector with a few earlier tokens, then a smooth activation is applied and the queries and keys receive regularized L2 normalization. A separate, smaller projection chooses how quickly each row of memory decays.

The regularizer is part of the equation, so I kept it in the Lean definition. For a projected vector z, we divide each coordinate by , so over the real numbers the result has norm strictly below one (rather than exactly one), and a zero vector stays zero because the regularizer keeps the denominator positive even in that case. KDA uses 10⁻⁶ here, while its RMSNorm operations use a different stabilizer.

(2)

q, k projections

(5)

bounded decay

(6)

output gate

What the slider is showing

The sigmoid keeps the log-decay between g_min and zero, and exponentiating turns that into a retention strictly between exp(g_min) and one. Move the logit right to forget faster, or left to keep more of the row.

Lower-bounded retention\(g_{\min}=-5\)
log-decay g−2.5000
retention α = exp(g)0.0821
proved intervale−5 < α < 1

Thanks to that lower bound, the accumulated log-decay over a 16-token tile stays above −80 (which is why the report says the tile's rescaling factor stays inside the BF16 range). What I've checked in Lean is the real-number bound, not the rounding behavior of the low-precision GPU kernel.

§2.1.2, pp. 5–6 · Equation 7

MLA compresses the attention cache

DeepSeek-V2 introduced MLA. At an MLA layer a token still gets global attention, and the saving comes from what survives in the cache: instead of storing a separate key and value for all 96 heads, the model keeps one 512-wide key/value latent and one shared 64-wide key.

When a head needs the old token, it reconstructs that head's 128-wide content key and 128-wide value from the shared latent. That reconstruction costs computation, but the cache only grows by 576 scalars per token, where a fully expanded per-head layout would store 30,720! Drag the token count below and watch the difference accumulate linearly.

That smaller number is 512 latent coordinates plus 64 shared-key coordinates, and all heads can read that stored entry through their learned reconstruction maps. For the larger baseline, each of 96 heads stores a content key, shared-key coordinates, and a value: 96 × (128 + 64 + 128) = 30,720. These are counts of stored scalar coordinates (converting them to bytes also requires the representation used for each cache).

I'll admit that this expanded baseline flatters MLA a little. It repeats the shared-key coordinates for every head, and a layout that kept those 64 coordinates only once would use 96 × (128 + 128) + 64 = 24,640 scalars instead. So the 53⅓ ratio below compares the specific fully expanded layout with the 576-coordinate latent cache (it isn't a claim about every possible cache layout, or an inference-speed ratio).

MLA still keeps an entry for every token, so if you double the length of a prompt, this cache doubles too. KDA's recurrent matrix stays the same size, but it no longer provides a separate stored entry that a query can inspect for every old token. K3 keeps both mechanisms so the sequence calculation can use recurrent memory at most layers and global attention at selected layers.

Fully expanded per-head layout96 heads × (128 key + 64 shared + 128 value)30,720 scalars / token
÷ 53⅓
Gated MLA cache512 KV latent + 64 shared key576 scalars / token
Cache growthone compressed entry per token per MLA layer
uncompressed3,932,160scalars
MLA73,728scalars
saved3,858,432scalars

§2.2, p. 6 · Equations 8–10

AttnRes: attention across depth

A normal residual stream gives layer ell one running sum of everything below it. AttnRes keeps several depth sources visible instead, and the current layer scores those sources, normalizes the scores, and retrieves a weighted combination.

K3 doesn't retain all 93 layer outputs separately. Every 12 layers are folded into a completed block sum while the unfinished block stays separate (the embedding is always source zero), which is why the memory grows by blocks rather than by layers.

(9)
depth attention weights
depth retrieval
Try layer 12, then layer 13

Processing the twelfth member commits the completed sum immediately and resets the partial size to zero, so layer thirteen starts the next partial block. At every stored state, the partial size stays strictly below twelve.

Walk through the block stateblock size 12

After all 93 layers, how many depth sources can the final retrieval see? Nine, if we count the original embedding. Seven complete groups of twelve account for 84 layers and leave nine in the partial group, so together with the embedding that gives seven completed sums, one partial sum, and one embedding source. Completing a group changes which tensor is stored, and it must not duplicate the completed layers in both the full and partial lists.

The query chooses how to combine these sources. If all source scores are equal, softmax gives them equal weight, and a different query can favor one source over another. Normalization only goes into the scores, while the weighted sum uses the original source vectors. Normalize those values as well and you'd change the retrieved vector, which is why the distinction appears in both the function and the graph proof.

§2.3, pp. 6–8 · Equations 11–13

Each token selects 16 of 896 routed experts

Shared experts operate at the full 7,168-wide model dimension, while routed experts operate at the 3,584-wide latent dimension. On the routed path, a token is projected down once, processed by its 16 selected experts, normalized, and projected back up.

tokenx ∈ ℝ7168
shared pathrouted path
2 shared expertsfull model width
W↓ → 16 of 896 → RMSNorm → W↑latent width 3,584
sumy ∈ ℝ7168
(11)
routed latent sum
shared and routed output
  1. A

    The shared experts see the original 7,168 coordinates and run for every token.

  2. B

    The routed branch projects once to 3,584 coordinates, then sends the same latent vector to 16 distinct experts.

  3. C

    The selected outputs are weighted, then RMSNorm rescales their combined vector by its root-mean-square size. A final projection restores 7,168 coordinates and adds the shared path.

The router first passes each raw score through sigmoid (a smooth function whose output lies between zero and one), and top-k then means choosing the 16 largest adjusted scores. Its selection bias can change which experts enter that set. After selection, though, the weighted sum uses the original sigmoid scores, so the bias doesn't directly change how strongly a chosen expert contributes.

I find a smaller example easier to hold in my head, so imagine four experts with sigmoid scores 0.8, 0.7, 0.6, and 0.2, and select two. Without a bias, the first two win. Add a selection bias of 0.3 to the third expert and its adjusted score becomes 0.9, so now the selected pair is the third and first experts. Their mixture weights still use 0.6 and 0.8, normalized by their sum to 3/7 and 4/7 (using 0.9 in that mixture would implement a different rule).

Shared experts have no top-k decision: they process every token at model width. Routed experts all receive the same down-projected latent input, and their weighted outputs are combined before normalization and the up-projection. Sparse selection saves those unselected expert computations, but their weights are still in the checkpoint.

§2.3.2, p. 7 · Appendix B, p. 43 · Equations 18–19

SiTU caps both linear branches

SwiGLU is the gated activation inside a feed-forward expert: one transformed branch decides how much of another transformed branch passes through. Two of its factors can grow with the input, so its output has no fixed ceiling. SiTU smoothly caps both factors while keeping the sigmoid gate. Near zero it still behaves like SwiGLU, but at large magnitude it stays bounded. Its two squashing functions are what make the bound possible (sigmoid stays between zero and one, while tanh stays between minus one and one).

(19)
SiTU definition
SiTU bound

Drag past 25. The purple SwiGLU curve keeps climbing while the blue SiTU curve bends toward its ceiling, and the formal theorem below proves that ceiling for every real pair (g,u), including points away from the plotted diagonal.

Scalar responsedrag the preactivation
SiTU-GLUSwiGLU

Both branches use the same input, g = u = x. SwiGLU continues above the plotted range, while SiTU approaches 100.

§2.3.3, pp. 8–9 · Appendices C–D, pp. 43–45

Balancing expert loads with score quantiles

K3 chooses the 16 experts with the highest adjusted scores for each token. For one expert, subtract each token’s cutoff (its 17th-highest biased score) from the expert’s raw score. That difference is the expert’s margin, and adding a bias can move it above or below the selection threshold. A quantile is a cutoff in an ordered set of scores, eg the point above which a chosen number of margins lie, and quantile balancing chooses the bias to aim for a target load. We can check the resulting count when the cutoff is exact, characterize thresholds that minimize the coordinate objective, and bound histogram interpolation error within a known bin, but I haven't yet covered the production histogram configuration or proved an exact-cutoff guarantee.

routing margin
selection rule
quantile bias
target count

Each expert gets two bars, and they answer different questions. The raw-score bar shows the sigmoid score used in the mixture, while the biased-score bar adds the balancing bias and decides whether the expert crosses the top-k cutoff.

Bias changes selection, not mixture weightfour experts, top-2

§2.4, pp. 9–10

MoonViT turns images and video into visual embeddings

MoonViT-V2 attends over every patch of an image, or of a video chunk of at most four frames, with 2-D rotary positions on the queries and keys. Each of its 27 blocks normalizes, projects once with wqkv, attends, and adds the result back, then does the same with a GELU MLP. Temporal pooling collapses the frame axis. A 2 × 2 spatial merge trades four neighboring tokens for four times as many channels before the projector maps into the language width. The paper describes factorized spatial and temporal passes, but the released modeling_kimi_k3.py has one attention over all t × h × w tokens, so I follow the code.

spatial merge preserves the number of scalars
four neighboring tokens become four channel groups

Switch from image to video and follow the third stage. An image attends over its H × W patches, while a video chunk of up to four frames attends over all F × H × W patches at once. Every frame gets the same row and column rotations, so only the added frame rows tell attention which frame a patch came from.

The merge preserves the number of scalars by grouping four spatial tokens into one wider row, so the language model sees fewer visual positions, each carrying more channels before projection.

Figure 2, p. 3 · §§2.1–2.4

How the K3 language model fits together

A backbone layer follows the same order every time. It makes two depth queries: the first retrieves input for KDA or MLA, whose output joins the partial depth block, and the second retrieves input for the dense or sparse channel mixer. Only after both submodules run does the block counter advance.

  1. 1

    Retrieve a sequence-mixer input from the current depth sources.

  2. 2

    Normalize and mix sequence with KDA or Gated MLA.

  3. 3

    Retrieve again with the sequence output included.

  4. 4

    Mix channels with the dense FFN or routed LatentMoE.

  5. 5

    Commit once to the AttnRes block state.

Text and visual positions remain distinct until embedding. A visual slot indexes MoonViT's projected sequence and a text slot indexes the vocabulary table. Both become 7,168-wide tensors.

Proof Language backbone · §§2.1–2.3

A token step through the decoder

In my development the state has two representations. The public causal calculation in Model.lean uses list caches and an AttnRes block state, while the graph in GraphSpec/LanguageModel.lean takes an ordered pack of tensors whose shapes are known when the graph is built. Its component theorems compare graph operations with reference functions using that same pack, so I still need to show that packing the public state preserves its transitions.

Fix a valid K3 configuration, a text token, and fixed-shape caches. If each supplied expert route agrees with the reference router, the composition returns exactly the same updated caches and vocabulary logits as runSpecAuto over the reals. Both calculations use the same packed state.

“Packed” means that differently shaped KDA, MLA, and depth states sit in one ordered bundle whose shapes are recorded in its type. The operations describe one incremental step. The old caches enter as inputs, and the updated caches and logits leave as outputs.

route-staged token graph
parameters and causal state
one-token packed denotation

Those brackets mean “evaluate the typed graph as a real-valued function.” The equality is exact. It includes the scheduled KDA/MLA choice, dense or sparse channel path, causal state packing, final depth retrieval, and vocabulary projection. A route trace lists the experts chosen at every sparse layer. The graph builder receives that trace, and hRoutes proves each staged choice agrees with the top-k scores computed by the packed reference run. (Vocabulary scores, also called logits, are the raw numbers softmax later turns into next-token probabilities.)

primitive operationsRMSNorm · matmul · broadcast · reshape · activationTorchLean tensor operations
↓
component graphsKDA · MLA · AttnRes · Expert · MoEcomponent denotation theorems
↓
four backbone casesKDA/dense · KDA/sparse · MLA/dense · MLA/sparseBackbone.model_specFwd_eq_specStep
↓
route-staged token graphgraph_specFwd_eq_runSpecAutoupdated causal states and current vocabulary logits

Shape mistakes fail while the graph is elaborated. A semantic mismatch in cache order, layer case, reshape, parameter packing, or output packing breaks the proof, and a wrong route trace means the caller can't supply hRoutes. So this comparison catches disagreements between the two formal paths, but if I got an equation or assumption wrong in both, my mistake would get through.

Next we turn to updating the parameters and running training. There the proofs cover particular formulas and contracts, such as per-head matrix layout and bounded rewards, while the training curves and systems measurements require evidence from the runs.

§2.5, p. 10

Per-Head Muon and matrix layout

For the query, key, and value projections, Kimi K3 runs Muon (an optimizer that applies an approximate matrix orthogonalization to its updates) separately on each attention head. So the first thing I check is the head split itself: a matrix with \(\text{heads}\times\text{columns}\) outputs must split into head blocks and reassemble without moving an entry.

split one head block
the layout round trip

Hover one color. Those adjacent columns form a single head matrix, orthogonalization runs inside that block, and then merge puts every entry back in its original global column.

Projection layouthover a head block

Each colored group is orthogonalized independently.

In full, the optimizer also has momentum updates, Newton–Schulz-style orthogonalization, and a distributed gather strategy. For my formalization I pulled out just two pieces of it, the per-head layout and the contract an orthogonalizer must satisfy.

Pre-training · Report §3, pp. 10–12

How K3 was pre-trained

K3's reported 2.5× scaling gain compares whole training recipes, and those recipes change the model shape, attention pattern, data mixture, optimizer, and context curriculum all at once. I follow those choices here to see what the comparison actually includes: the capacity available to each token, the examples the model learns from, and the work spent on longer contexts.

More layers and experts, the same hidden width

Kimi K2 already had more than a trillion parameters, but K3 doesn't get its extra capacity by widening the residual stream (both models keep a hidden dimension of 7,168). It grows from 61 to 93 language-model layers, expands the routed pool from 384 to 896 experts, doubles the active routed experts from eight to sixteen, and adds a second shared expert. Each expert's hidden dimension also rises, from 2,048 to 3,072. Add it all up and you get 2.78 trillion stored parameters and 104.2 billion active parameters per token, compared with 1.04 trillion stored and 32.6 billion active in K2.

A mixture-of-experts checkpoint stores all its experts, even though any one token only uses the ones it selects. So total parameters count that stored capacity, while active parameters are the better proxy for the matrix work a token costs. K3 stores about 2.7 times as many parameters as K2 and activates about 3.2 times as many, which means storage and computation both grow. Neither number gives you the time per token, though. For that you'd also need the routing, communication, memory format, batch size, and kernels.

Kimi K2 and Kimi K3 as reported in Table 1
QuantityKimi K2Kimi K3Change
Language-model layers6193+52%
Total parameters1.04T2.78T+167%
Active parameters per token32.6B104.2B+220%
Hidden dimension7,1687,168unchanged
Routed experts384896+133%
Active routed experts816+100%
Shared experts12+100%
Attention heads6496+50%
Attention stack61 MLA69 KDA + 24 MLAhybrid
Training context128K1M8×

The K3 column also lists a 3,584-dimensional latent MoE space and a 401-million-parameter MoonViT-V2 (27 layers, patch size 14, and 12 heads). Sixty-nine of the 93 language layers use KDA, and the remaining 24 provide global MLA attention. Table 1, p. 11 ↗

The reported 2.5× scaling gain

Figure 7 fits validation loss against training compute, using data that wasn't used for training and was deliberately chosen to differ from it. At the same fitted loss, a K3-family run used about 40 percent as much compute as a K2-family run, and that's the reported 2.5× gain. So it's a comparison of fitted model-family curves (serving speed and the total cost of the final checkpoint are separate questions). So which change earned the gain? I can't tell from the report. Architecture, data, optimization, and dimensions all changed together, so I read this as a gain for the combined recipe, and to pin it on KDA, the data mixture, or any other component, you'd need runs that change those choices separately. §3.2 and Figure 7, pp. 10–11 ↗

The data mixture starts multimodal

The text corpus is organized around web text, code, mathematics, and knowledge, and the pipeline that builds it combines rules, learned quality classifiers, and deduplication. Sampling rates for the domains come from ablations on smaller models. So you get the process that picked the rates, but not the rates themselves.

Before base-model pre-training, the team rewrites knowledge and mathematics sources, with prompts that ask for different styles and viewpoints and long sources rewritten chunk by chunk. A later fidelity check tries to keep the facts intact. So the model learns from transformed versions of some of its source material, as part of its base corpus. I think that fidelity check matters, because a rewrite can change a formula or a factual detail even when the new prose sounds convincing.

On the vision side, the corpus covers captions, documents with interleaved images and text, OCR, perception, video, and visual coding. Localization examples give coordinates two ways (absolute, and normalized to the unit square). Programmatic examples pair code with rendered outputs such as SVG images, webpages, games, 3D assets, and CAD drawings, which lets the model learn from code alongside the image or application it produces. You'll see related tasks again in the web-development and visual-agent evaluations. §3.1, p. 10 ↗

Joint vision-language training

MoonViT-V2 and the language model train together from the very first step, under the same next-token objective. Visual features are resized to the language embedding width and interleaved with text tokens, so the language loss also changes the vision encoder (the report calls this native multimodal training). A wrong answer to an image question, for example, can change both the features extracted from the image and the language model that uses them, and the two parts learn to work together under that one objective.

textweb · code · math · knowledge
visionimages · documents · video · rendered code
→
one token streamjoint next-token prediction
→
one backboneMoonViT-V2 + K3 language model
Text and visual examples go into the same pre-training objective, and media-control tokens can stay in the input while selected positions are masked out of the loss.

The optimizer and context schedule

Per-Head Muon updates the query, key, and value projection matrices in separate head blocks. K3 also keeps K2’s weight clipping, and it sets the expert selection biases with Quantile Balancing, in place of the fixed-step bias update of earlier auxiliary-loss-free routing. Learning rate rises during a one-percent linear warmup and then follows cosine decay, with weight decay at 0.1. That's enough to describe the update schedule, but you couldn't replay the run from it, since the peak learning rate, batch size, clipping threshold, and total token budget aren't specified.

Why does context length grow so late? Because attention and activation costs make long sequences expensive. Ordinary pre-training begins at 8K and later reaches 64K, and only during cooldown does the model advance to 256K and then one million tokens. According to the authors, these long-context stages are a small fraction of training. For those stages, the team upsamples scarce coherent long documents and videos, cleans them with exact and fuzzy deduplication (and perceptual hashes for frames), and adds synthetic examples that scatter the evidence needed for one answer across several concatenated documents and subtasks.

KDA uses no explicit positional encoding. Its recurrent decay and gating make the order of tokens affect the state, so the team can extend the sequence without rescaling rotary positional embeddings (RoPE, a common way to rotate query and key coordinates according to token position) or interpolating position indices. Dropping RoPE removes one engineering obstacle, but I still want to know whether the state keeps the information a long-context task requires. We'll see retrieval benchmarks address that question later, under their own evaluation setups. §§3.3–3.4, pp. 11–12 ↗

I find it useful to think about the shared training objective and the late context expansion together. K3 first learns from many kinds of input, then spends part of its final training on much longer examples. The report is enough to understand that order of choices, but you'd need the underlying runs to reproduce what it cost.

§§3.3–3.4, pp. 11–12

Loss masks and longer training contexts

The report describes a joint next-token objective for language and vision, and here I'll write a masked version of it, where we choose which target positions contribute to the loss. As reported, the context schedule grows from 8K to 64K, then to 256K and one million tokens during cooldown.

declared masked-gradient formula

At each trained position, softmax turns the vocabulary scores into probabilities. The stated gradient for one vocabulary item is its predicted probability (minus one when that item is the correct token), averaged over all trained positions. A masked position contributes zero, but its token can still appear in the input context, because the mask only drops its loss. I've recorded this formula in Lean but haven't (yet) derived it from the loss.

pre-training8K
extension64K
cooldown256K
cooldown1M

Example shifted sequence

Themodel<media>seestokens
In the declared formula, supervised rows receive the scaled cross-entropy term and the masked row contributes zero.

The masked loss and gradient formula are my own mathematical specification of the next-token objective, since the report gives neither this formula nor a complete loss mask. The four context lengths do come from §§3.3–3.4, though the report doesn't disclose the total token count or duration of each stage.

Post-training · Report §4.1, pp. 12–14

Training nine specialists, then combining them

Post-training proceeds in three stages. Supervised trajectories first establish a usable agent, then reinforcement learning separates domains and reasoning budgets into nine specialist policies, and finally Multi-Teacher On-Policy Distillation brings their behavior back into one student.

Starting with supervised examples

Supervised fine-tuning (SFT) gives the base model a common interaction format and enough worked examples to begin agent training. Earlier domain-specialized Kimi models generate the complex trajectories, which pass through several verification stages and human annotation before anything trains on them. Every conversation uses XTML (the text format that serializes messages, tool calls, and tool results for the configurable agent wrappers and inference system).

These demonstrations are meant to teach the model to adjust reasoning effort, call tools precisely, and keep working through long tasks, all before reinforcement learning begins. (The report doesn't measure how much each part of this cold start contributes.) They also give RL a better starting point, because the model can already attempt the interaction that the reward will judge. §4.1.1, p. 12 ↗

Three domains crossed with three effort levels

The RL stage separates capability from computation. Its first axis is the domain, and there are three. General-task training covers ordinary experience, vision, reasoning, faithfulness, search, and knowledge work. General-agent training covers long-horizon assistants, deep research, and paragraph-level writing, while coding-agent training covers software engineering, coding experience, kernel work, and web development.

The second axis is reasoning effort (low, high, and max), and crossing the two axes produces nine teachers. So a low-effort coding policy learns under a tighter budget than a max-effort coding policy, and both are distinct from a max-effort general agent.

low
high
max
general tasks
reasoning under a short budget
more search and thought
largest allowed budget
general agents
compact tool use
longer agent work
long-horizon execution
coding agents
fast coding tasks
repository work
extended coding and kernels

As RL computation increases in Figure 8, the plotted coding, tool-use, web-development, search, office, chart, and visual-puzzle capabilities all rise, and so does the average number of assistant or tool-call steps. So more training also goes with longer attempts at the tasks. I can read the direction of those trends, but without numerical axis labels, effect sizes, or variance there's no way to estimate improvement per unit of computation. §4.1.2 and Figure 8, pp. 12–13 ↗

Pausing and resuming unfinished rollouts

Agent trajectories vary in length, so what should a batch do about the slow ones? If it waits for its slowest trajectory, finished workers sit idle, and if it discards unfinished work, it wastes the most expensive examples. K3's answer is partial rollouts. For \(N\) prompts and \(K\) completions per prompt, the system keeps \(N \times K\) trajectories active. It pauses an iteration once a fraction λ has finished, queues the unfinished states, and gives them priority in the next iteration, and a prompt enters policy optimization only after all of its \(K\) responses complete.

  1. 1

    Launch several responses for every prompt and retain their model, tool, cache, and environment state.

  2. 2

    When λ of all responses finish, stop waiting for the longest tail and start the next policy iteration.

  3. 3

    Resume the paused responses first. Their exact sandboxes and cache prefixes survive the boundary between iterations.

  4. 4

    Once every response for one prompt is ready, compute the group reward and make that prompt eligible for optimization.

A paused trajectory can resume after several parameter updates, and by then its earlier actions were sampled by an older policy, so learning from them is off-policy. The team says a per-token regularization penalty limits large policy changes enough to keep this stable. So there's a trade-off between finishing expensive work and learning from a recent policy. I'd like to know the age of the resumed trajectories and the throughput gained over synchronous rollouts, but the report only gives the mechanism.

Training with problem-specific token budgets

Effort levels are enforced through length-relative penalties. First a cold-start model estimates a baseline budget \(b_0(x)\) for each problem, and a trajectory receives reward −1 when its length exceeds τ times that baseline. Length means thinking tokens on general tasks and cumulative output on agent tasks (reasoning and tool-call arguments included). Training begins with a large τ for the max-effort teacher, still under an absolute cap, and anneals τ to produce high- and low-effort teachers, with settings that vary by domain under human guidance.

This penalty pulls against another trend, since the capability curves improve as the agents take more steps. What K3 is trained to do is spend extra computation when it earns reward and stop when the trajectory becomes wasteful. To compare the effort modes, I'd want task success plotted against tokens spent for each one. Figure 8 only shows the broader training trends.

Many agent tasks have deterministic or programmatic verifiers. For writing and other non-verifiable work, K3 uses an Agentic Generative Reward Model, a grader that reads the output, writes a rubric, scores each candidate against it, and records the scores in a scratch area. Candidates then compete through tournament-style binary comparisons, and a response longer than σ times the cold-start verbosity loses automatically. That gives verbosity its own control, instead of treating every extra token as evidence of better work. For these tasks I'd worry about the grader as much as the policy, because a model can learn to satisfy a judge without making its answer more useful. §4.1.2, p. 13 ↗

Combining the specialists through distillation

Nine separate deployment models would be costly and awkward, so how do you fold them back into one? For a given domain, MOPD samples an effort level, rolls out the unified student, and scores each sampled token with the matching teacher, using the teacher-to-student log-probability ratio as the reward. That reward is treated as a fixed score (differentiation doesn't flow back through its calculation), and it's clipped to a symmetric interval. I'll write it out in the next section, along with its Lean bound.

Because the student generates the trajectories, teachers score the states it actually reaches during its own attempts. The team also tried a denser top-\(k\) objective that transferred several token probabilities at each position, and found no clear improvement in convergence or final performance. What you get in practice is one student that can switch domains and effort levels without loading a different model. There's no separate retention score for each teacher, though, so the final evaluation measures the student as a whole, and I can't read off a teacher-by-teacher transfer rate. §4.1.3, pp. 13–14 ↗

§4.1.3, pp. 13–14 · Equation 15

MOPD compares teacher and student token probabilities

MOPD picks one of nine domain-and-effort teachers, asks it for its probability of the token the student sampled, and clips the log probability ratio. That keeps the dense reward bounded even when teacher and student probabilities differ sharply.

(15)
MOPD reward

Set the teacher probability high and the student probability close to zero. You'll see the raw log ratio keep climbing while the value passed to the objective stops at five in this illustration, and if you reverse them the same clamp applies at minus five.

Inspect the clipped reward\(R_{\max}=5\)
log ratio2.169
clipped reward2.169

Start with the displayed probabilities, 0.70 and 0.08. Their ratio is 8.75, so its natural logarithm is about 2.169, and the score is positive because the teacher gives this sampled token more probability than the student does. Swap the probabilities and the sign flips. Equal probabilities give zero. Clipping limits how strongly a very large disagreement can affect the reward. (I picked the slider's cap of five as an illustration, so don't read it as a cap value from the report.)

And why does the stop-gradient operation matter? We use the student probability to calculate the reward, but that reward is held fixed while we differentiate the policy update, and differentiating through both its log ratio and the policy objective would produce a different update. So the scalar bound below describes the reward, and on its own it doesn't pin down either update rule.

§4.1.4, p. 14

What four-bit expert weights mean

Quantization replaces a high-precision number with one of a small set of coded values. MXFP4 gives each expert weight a four-bit code and MXFP8 gives each expert activation an eight-bit code, where “MX” means microscaling (32 neighboring values share a separate scale). Both formats are defined in the OCP Microscaling specification. In the diagram, E8M0 is that shared exponent-like scale and E2M1 is the four-bit element format, with one sign bit, two exponent bits, and one fraction bit. In my formal model I spell out both parts, so its error theorems state exactly what they assume.

shared-scale block decoding
E2M1 reference error

The purple chip belongs to all 32 cells. If you change that scale, the range of the whole block moves, but changing one E2M1 code changes only one cell. This slider isolates the element quantizer, before the later theorems accumulate its error.

E8M0
20
Quantize one E2M1 valuereference semantics
nearest decoded value3.00
absolute error0.30
proved ceiling≤ 1

§4.1.4, p. 14 · Equation 16

A smaller model drafts tokens for K3 to check

EAGLE-3 is a smaller draft model that proposes several future tokens, which full K3 then checks together. That's speculative decoding: cheap proposals can speed up generation, while an acceptance-and-correction rule preserves the full model's final distribution. The draft starts from K3 features taken at low, middle, and high depths and from the pretrained multi-token prediction (MTP) layer, a small head trained to predict beyond the immediate next token. Its fusion matrix begins as [0 0 I], so the first fused feature is exactly the high-level feature the MTP layer already saw, and after that each draft step feeds its own hidden output forward. The training unroll has seven positions.

target featureslow · mid · high
[0 0 I]

Lossless speculative sampling accepts the overlap between the target distribution \(p\) and the draft distribution \(q\), and Kimi K3 minimizes the negative log of that overlap. Total variation (TV below) is half the sum of the absolute probability differences, so it's zero for identical distributions and one when they don't overlap at all.

(16)
acceptance loss
overlap and total variation

Each group of three bars is one possible next token. Blue is the target probability, purple is the draft, and gold is the overlap that can be accepted. Move the draft sliders toward the target and watch the gold area grow while the loss falls.

Acceptance is distribution overlapthree-token vocabulary
Σ min(p,q)
total variation
−log acceptance

Why is acceptance the same thing as overlap? For a proposed token y with positive draft probability, the acceptance probability is . Multiply by the probability of proposing it and you get , and summing those accepted contributions over the vocabulary gives the overlap shown above.

I start the sliders with the target at (0.55, 0.30, 0.15) and the draft at (0.25, 0.45, 0.30), so their accepted contributions are (0.25, 0.30, 0.15), with total mass 0.70. What's left of the target is (0.30, 0, 0), which means that on rejection the correction distribution chooses the first token. Add the accepted mass to that 0.30 rejection mass and you recover exactly (0.55, 0.30, 0.15)! Simply retrying the draft wouldn't implement this correction.

That explains both the training loss and its limit. More overlap means more draft proposals survive verification. But does that make generation faster? Not by itself, because drafting, checking a block, and restoring rejected state all still take time. So the equation trains the draft toward a useful acceptance rate, and the serving section describes the rest of the work it takes to turn that into a faster generator.

RL environments · Report §4.2, pp. 14–17

Tools, tasks, and rewards

Each training task specifies what tools the agent can use and how its work is checked. To build them, the team creates tools, websites, repositories, office applications, machines, hidden tests, and reward rules that let a trajectory run for hours and still produce a checkable result.

Training across agent interfaces

Agent policies can overfit to the wrapper around a task, where tool names, message templates, available memories, context-management rules, subagent APIs, and even error formats become shortcuts. K3's white-box environment makes those pieces configurable. It can reproduce the interaction style of Kimi Code, Claude Code, Codex, OpenClaw, and Hermes, or assemble a new setup from the same parts.

The aim is to teach file inspection, search, and code execution across several tool schemas, so the agent still recognizes those operations when their names or message formats change. A wrapper defines what the policy observes and which actions it can take, which is why varying it changes the learning problem even when the underlying task stays the same. Whether this training improves transfer to a new interface is something I'd need a cross-wrapper ablation to measure, and the report gives the design argument without one. §4.2.1, pp. 14–15 ↗

A knowledge graph becomes a task generator

Broad seed topics are recursively expanded into a directed acyclic graph. For each node an agent runs several web searches, splits coarse ideas into finer ones, reuses an existing node when two branches reach the same concept, and stops when it judges a node atomic. Edges point from coarse to fine. Nodes at several levels can then supply retrieval queries, source bundles, and task prompts.

That's how you get related problems without copying one template at a time. A broad banking node can lead to financial statements, ratios, sector rules, and source-specific questions, while a visual-science node can lead to plots, diagrams, measurements, and small computation tasks. And reusing equivalent nodes connects areas that would otherwise grow as isolated trees.

seedprofessional analysis
bankingfilingsriskvaluation
data worktableschartssources
legalrulesevidencecitations
retrieval + sources + verifiernew agent tasks
A small example task graph, where related topics supply different source bundles and questions. The report describes this construction in Figure 9, but don't read these labels as a dump of its training graph.

§4.2.2 and Figure 9, p. 15 ↗

Search, professional work, and visual tools

Search tasks ask for an answer and supporting sources. Professional tasks cover banking, data analysis, and legal work, with trajectories lasting dozens or hundreds of steps, and the verifier can inspect the final artifact, citations, calculations, or state of the simulated workspace. I like that, because it rewards completion over fluent narration about what the agent intended to do.

Visual tasks put Python inside the observation loop: the agent may crop an image, zoom, transform it, measure a diagram, run a calculation, and feed the generated image back as the next observation. That design makes image tools part of the reasoning instead of a one-time preprocessing stage. The authors say scores rise with more operations and observations (though §4.2.3 supplies no curve or effect size).

Grading kernel correctness and speed

Kernel optimization problems range from one operator to large fused kernels and cover several GPU programming systems (including CUDA, Triton, CuTe DSL, Gluon, ThunderKittens, and TileLang), with tasks in 16-bit, 8-bit, and 4-bit number formats. A candidate whose numerical error crosses the private threshold gets zero, matching an expert implementation earns 0.5, and approaching the hardware roofline moves the reward toward one. Separate detectors penalize replaying a captured CUDA graph, caching the input, or silently lowering precision.

Why does the numerical check have to come before the speed reward? Because caching an input or lowering precision could improve a timing result while changing the computation the task asked for. There are detectors for those shortcuts. What the report doesn't publish is the numerical threshold and timing protocol you'd need to reproduce the grading. §4.2.4, p. 16 ↗

Multi-day assistant tasks

The personal-assistant environment supplies mock versions of Gmail, Notion, Slack, and Canvas, with events that unfold over several simulated days and cross application boundaries. An email may create a calendar obligation, a Slack message may change a document, and a later event may test whether the agent remembered the earlier instruction. Each event gets either a deterministic check or a model-based judge.

A single rollout can reach thousands of tool calls and millions of accumulated context tokens (the report presents that as a possible upper range, not the typical trajectory). Workloads like that explain several of the systems choices I'll describe later. Paused generation must preserve the application state, repeated prefixes must stay cached, and an idle sandbox can't reserve full memory while it waits for the next model response.

day 1read mailrecord a request
→
day 2edit Notionuse prior context
→
day 3answer Slackreconcile changes
→
laterhidden checkinspect final state

§4.2.5, p. 16 ↗

Grading tasks with no reference solution

Autonomous Execution Tasks give the agent a goal, constraints, an action space, a resource budget, and a verification interface, but no procedure or reference trajectory. Reward depends on the final state of the environment. Example domains include reproducing a system, discovering quantitative factors, and auditing taxes.

Public verifiers give the agent diagnostic feedback, while hidden verifiers evaluate held-out scenarios. Submission limits and penalties discourage blind probing. To me this resembles ordinary engineering work more closely than a benchmark with a known sequence of steps: several valid plans may exist, intermediate work can fail, and only the finished state settles whether the task was completed.

Figure 10 shows one camera-repair-system replication task, and its legend reports K3 at 1.000, Opus 4.8 at 0.918, GPT-5.5 at 0.893, and Kimi K2.6 at 0.560. Its caption describes verifier-assessed progress without fully defining what each displayed scalar aggregates. And one demonstration can't establish a distribution of task performance. I read it as a picture of the sort of work the environment permits. §4.2.6 and Figure 10, pp. 16–17 ↗

Web development joins code and visible output

Web tasks start from briefs ranging from one line to several paragraphs. Expected outputs include ordinary sites, games, 3D and WebGL scenes, data visualizations, SVG work, and full-stack applications. Deterministic checks inspect structure, behavior, and pixels, while an internal model judge assesses whatever is hard to encode as a fixed test, and a build failure, a runtime error, or a faked artifact gets zero reward.

In this environment the model builds against an explicit visual and functional target. Later, the report's blind web-development comparison finds judges preferring K3's output to Opus 4.8 in 58.6 percent of pairings, with the largest advantage in 3D and WebGL tasks. I'll get to the judging conditions and limits in the evaluation section. §4.2.7, p. 16 ↗

Infrastructure · Report §5, pp. 17–25

Training and serving infrastructure

K3 creates three different engineering problems at once: KDA has a recurrent state, sparse experts must move across a multi-trillion-parameter training cluster, and agent trajectories can hold on to a million tokens plus a live computer for hours. This part of the report is about how the team allocates memory, distributes expert computation, and stores unfinished rollouts.

KDA trades a growing cache for a serial state update

Full attention offers parallel work across a prompt, but it stores keys and values that grow with the prompt's length. KDA stores a fixed-size state for each head, which cuts cache growth and transfer volume. But its recurrence brings a different problem: token \(t\) depends on the state from token \(t-1\), so a literal implementation would process the prompt serially and leave much of the GPU idle.

So how do you keep the GPU busy? FlashKDA breaks the prompt into chunks. Tokens inside one chunk can be processed in parallel, and only the small summary passed from one chunk to the next stays sequential. It's built on CUTLASS (NVIDIA's building blocks for GPU matrix operations) and serves training and prefill, while long prefills and decoding each get a kernel designed for their regime. You get an explanation of how the kernels overlap their work, but no throughput numbers. §5.1.1, pp. 17–18 ↗

Splitting KDA across devices with transition summaries

If you split a sequence across devices, the second segment needs the state left by the first, and the third needs the state after both. So each device summarizes its segment with a small state update, and those updates can be combined in order. A prefix scan computes the summary after A, then after A+B, then after A+B+C, so every device recovers the state entering its own segment without exchanging all of the tokens.

segment Asegment Bsegment Csegment D
(transition, zero-state)(transition, zero-state)(transition, zero-state)(transition, zero-state)
fixed-size all-gather + associative prefix scan
state 0state after Astate after A+Bstate after A+B+C

What gets communicated is the state summary, whose size doesn't depend on the number of tokens in a segment. That's why the authors describe communication as independent of sequence length and compute scaling as linear in the number of context-parallel devices. That claim follows from the algorithm's message shape (the report doesn't include an end-to-end scaling chart). §5.1.2, p. 18 ↗

In my Lean version, each segment summary is an affine map, which applies a linear transition to the incoming state and adds the segment’s zero-state output. Composing these maps gives the same state as applying them one after another, and identity, associativity, and the append law let us regroup the work for a prefix scan. I haven't connected the summaries to actual KDA updates yet, and the network collectives and measured scaling are open too. Parallel/Context.lean ↗

I picked two scalar summaries to make the ordering easy to see. Let and . Applying A and then B gives , while reversing them gives . Composition is associative, so a parallel scan can change the parentheses as long as A stays before B, but it isn't commutative, so the scan can't exchange the segments. (These are toy summaries for the scan law, and their coefficients aren't measured K3 states.)

Dividing a 2.78T model across devices

The model is too large for one GPU. So training divides layers, experts, optimizer memory, gradients, and long sequences across many devices. Each division addresses a different limit: how much a GPU can store, how much work it can perform, or how much data workers must exchange.

The distribution names used in the report

Pipeline parallelism gives consecutive groups of layers to different workers. Expert parallelism spreads the 896 experts across workers. Context parallelism divides a long token sequence. ZeRO-1 shards optimizer memory, while Pipeline ZeRO-2 also limits which gradient pieces stay resident. Virtual pipeline stages interleave smaller layer groups to reduce waiting time.

These partitions interact. Routing may send many tokens to an expert located on another rank, pipeline stages create bubbles (idle time while one stage waits for another), sharded states have to arrive before their operation runs, and vision adds a separate encoder whose patch tokens and activations occupy memory. So the paper concentrates on three solutions: balance expert work, manage saved activations through one policy, and schedule vision into otherwise idle pipeline time. §5.2, pp. 18–19 ↗

MoonEP and balanced expert assignments

Ordinary expert parallelism can be balanced in expectation and still stall on one rank that receives too many routed tokens. MoonEP migrates redundant copies of popular experts so every rank processes exactly \(S \times K\) token-expert assignments (\(S\) is the sequence length and \(K\) is the number of active routed experts), and the placement changes dynamically with the measured load.

The report proves that no rank needs more than \(E/R\) redundant expert slots for \(E\) experts across \(R\) ranks. MoonEP's fixed receive buffer holds \(S \times K\) assignments, while the existing DeepEP expert-communication layout can require \(S \times K \times R\) (any sending rank may contribute the full amount). Static shapes also remove a CPU synchronization step for discovering the next receive size. In Lean I've now proved the report's key lemma by its own filling construction, then the \(E/R\) upper bound for every router output, plus the capacity pigeonhole lower bound. I haven't verified the online planner or the distributed migration runtime.

conventional worst caseS × K × R

space for every possible sender contribution

MoonEP fixed bufferS × K

exact work assigned to each receiving rank

§5.2.1, pp. 19–20; Appendix E, pp. 45–46 ↗

Parallel/Experts.lean, counting bounds ↗

Saving, recomputing, and offloading activations

Activations are intermediate tensors that later computations may need again, and keeping all of them on the GPU consumes memory, while recomputing or moving them costs work. So a unified manager plans their lifetimes and chooses which to keep, recompute, quantize, move to host memory, or send to remote memory. Most saved activations use a blockwise 8-bit format before offload, and a common buffer plan lets the system overlap transfers with forward and backward computation across modules.

Pipeline ZeRO-2 further limits resident gradients, and reference weights for RL stream through two reusable gradient slots: one slot serves the current virtual pipeline chunk while the other prefetches the next. MoonViT-V2's image patches are sharded, and its encoder work is placed inside language-model pipeline bubbles. Both schedules try to make room for the next operation before it needs to run, rather than keeping every saved tensor resident for the whole update. §§5.2.2–5.2.3 and 5.3.1, pp. 20–22 ↗

Million-token RL preserves unfinished work

The RL cluster is co-located so one experiment fits within a few hundred GPUs, with policy training, rollout generation, reference-model work, and cache storage all sharing that footprint. Because partial rollouts cross iteration boundaries, the system retains their prefix state in an external KV pool backed by CPU DRAM, and adaptive throttling slows generation before cache pressure starts preempting requests.

At one million tokens, rebuilding the prefix on every resume would repeat a large amount of attention work. Keeping that work in the pool while a trajectory is paused lets the next iteration continue from its cached state. How much time does that save? It depends on reuse and transfer costs, since keeping a prefix in CPU memory still costs storage and a transfer back to the GPU, and the design trades that cost against recomputing the prefix. That trade-off isn't measured end to end in the report. §5.3.1, pp. 21–22 ↗

Pausing and restoring agent sandboxes

Early container-based experiments caused kernel panics and deadlocks when agents explored aggressive system operations. So AgentENV runs Firecracker microVMs instead (small virtual machines with their own guest operating-system kernel), and the stronger isolation lets tasks mount disks, start containers, or even launch nested virtual machines without giving the agent control of the host kernel.

Incremental checkpointing saves only the pages dirtied since the previous checkpoint, and the report measures checkpoint latency as low as 133 milliseconds and resume latency as low as 49 milliseconds. Pausing releases the running sandbox's CPU and RAM while keeping its saved snapshot. That matters, because a sandbox can spend up to 98 percent of its lifetime waiting for model inference! Forking creates a side-effect-free copy for reward judging, and snapshots provide recovery points.

On top of that, the team changed image storage, virtual-disk input and output, memory sharing, and direct transfer between machines, and together those changes produce subsecond launches at scale and up to 6.5× memory overcommit in the reported workloads. Across K3 training and evaluation, the system created 51,219,741 sandboxes from 1,505,678 images. These are my favorite operational numbers in the report, since they're among its most concrete. (They describe the environment fleet, though, which isn't the same as the number of unique RL tasks or successful trajectories.) §5.3.2, p. 22 ↗

The storage mechanisms behind those numbers

OverlayBD shares read-only layers between virtual-disk images, and the custom ublk driver handles block storage in user space. Copy-on-write memory lets sandboxes share pages until one modifies a page, page-cache changes improve reuse of recently read file data, and peer-to-peer transport moves state directly between machines.

133 mscheckpoint, as low as
49 msresume, as low as
98%lifetime possibly waiting
6.5×memory overcommit, up to
51.2Msandboxes created

Restoring the recurrent state and attention cache together

A K3 block has three KDA layers and one MLA layer. MLA keeps a per-token cache that grows with the prompt, while KDA keeps one large fixed state per request, and a reusable prefix needs both caches at the same token boundary. So the serving engine packs them into one paged pool, which lets allocation, reference counting, transfer, and eviction use a shared implementation even though the page contents have different types.

KDA checkpoints are too large to store at every token, so physical cache blocks span 1,024 to 6,144 tokens. But if prefix matching used only those coarse blocks, a shorter shared prefix could never hit. How does a shorter prefix ever hit, then? The engine separates allocation granularity from hash granularity: MLA prefixes are hashed at 512-token boundaries inside a physical page, and sparse KDA state checkpoints are retained at eligible hash endpoints (often conversation turns).

one 6,144-token physical block
5121,0241,5362,0482,5603,0723,5844,0964,6085,1205,6326,144
2,800 matching tokensrestore at 2,560 and recompute only the suffix
In the report's Figure 12 example, lookup finds five matching 512-token hash blocks and a KDA checkpoint at token 2,560, even though that point lies inside one physical page.

Lookup first finds the longest MLA hash match, then requires a compatible checkpoint in every KDA cache group. Shared blocks are pinned before private allocation, freshly copied pages cannot be matched before their GPU copy completes, and eviction of one KDA group invalidates sibling checkpoints atomically. Those rules keep the two cache families at the same declared token boundary under concurrent scheduling. §5.4.1 and Figure 12, pp. 22–24 ↗

Speculative decoding retains the projections it needs

KDA decoding updates its recurrent state in place. So if speculative verification rejects a drafted suffix, the state has already advanced beyond the accepted prefix, and saving one full state per draft position would multiply the dominant memory traffic. K3's kernel caches the much smaller projected inputs for each draft token, replays the accepted ones on chip, and writes back only the verified and bonus-token states. I like this trick a lot.

Serving kernels combine several small operations so intermediate values don't need separate trips through memory. During prefill (the first pass over the existing prompt), AttnRes spreads activations across sequence workers, and during token-by-token decoding it performs some depth work on a second GPU stream. LatentMoE overlaps worker communication with expert computation and begins its all-gather in the final stage of a matrix multiplication. Each of these changes tries to keep a useful operation running while another waits for data (the report describes the schedules without an end-to-end speedup table). §5.4.2, pp. 24–25 ↗

Placing requests near their cached prefixes

A typical million-token coding request is described as carrying a 400K cached prefix and only 4K new tokens, so the scheduler sends it to the cluster holding that prefix. Consistent hashing (a deterministic rule that moves only part of the traffic when machines change) assigns a primary and a secondary cluster. After a failure the secondary accepts the session and recomputes its cache, which spreads failover work across the fleet.

Requests under 2K tokens share the fleet with requests near one million, which puts them roughly three orders of magnitude apart in per-request cost! Admission control (which limits how much work each request class can admit) gives the classes separate resource budgets, so a burst of long prompts has a budget of its own while short requests keep theirs. To evaluate this scheduler I'd want to measure how long each class waits under mixed traffic, including bursts and failures. The report describes the policy without those latency distributions. §5.4.3, p. 25 ↗

What I think ties these systems choices together is the amount of work a long-lived request leaves behind: recurrent states, attention caches, tool processes, and a filesystem. Reusing that work takes more than keeping a tensor in memory, because the caches have to agree on a token boundary and the sandbox has to resume at the corresponding point in the task. That's why so much of this section is about state lifetimes and recovery.

Evaluation · Report §6, pp. 25–32

Reading K3's evaluation results

K3 leads several coding, search, office, document, and web-development tests. It's still behind the best proprietary models on parts of research reasoning, difficult computer use, and some long-form knowledge work, and the setup details are why I'd read close scores carefully.

How the benchmark runs were configured

Every K3 result in the main table uses max reasoning effort and temperature 1. Single-step tasks (such as GPQA Diamond and vision benchmarks without tools) use top-p 0.95, meaning sampling keeps the smallest set of likely tokens whose probabilities add to at least 95 percent. Agent and coding tasks use top-p 1, which leaves the full vocabulary available. Proprietary baselines also run at their highest listed effort, except GPT-5.5 at xhigh. Claude Fable 5 may fall back to another model and GPT-5.6 Sol may apply cyberguards, and those policies change both capability and cost.

Coding scores may use Kimi Code, Claude Code, or Codex, and Terminal-Bench reports the best score obtained across the available execution setups for each model. DeepSWE lists 67.5 in the comparison table, while the official mini-SWE-agent result is 67.3. SWE-Marathon uses an H20-calibrated pre-release branch dated July 9, 2026, and Fable falls back on 35 percent of those tasks. All of these choices are disclosed, which I like. They still make small gaps poor evidence of an intrinsic model ordering.

BrowseComp uses context compaction at 300K tokens and reaches 91.2, and with the raw one-million-token window and no context management K3 scores 90.4. MCP-Atlas and AutomationBench use public subsets. WorldVQA required prompt changes to force answers after several models refused. Most vision scores average three runs (ZeroBench uses five), but the table gives no confidence intervals. Several entries also come directly from third-party leaderboards rather than a single common runner. §§6.1.1–6.1.3, pp. 25–27 ↗

Reasoning scores and harder research questions

K3 scores 93.5 on GPQA Diamond, tied with GPT-5.5 and 0.6 points behind GPT-5.6 Sol, and it leads AA-LCR at 74.7. Harder research tests are less favorable. CritPt is 23.4, below Fable 5 at 28.6, Sol at 32.3, and GPT-5.5 at 27.1. On Humanity's Last Exam K3 gets 43.5 without tools and 56.0 with tools, against 53.3 and 63.0 for Fable and 44.5 and 58.0 for Sol.

GPQA DiamondK3 93.5leader: Sol 94.1
AA-LCRK3 74.7best reported
CritPtK3 23.4leader: Sol 32.3
HLE with toolsK3 56.0leader: Fable 63.0

So K3 handles graduate-level questions very well and leads one long-context reasoning test, while frontier research questions still expose a gap (the report reads it the same way, and so do I). Table 2 and §6.1.4, pp. 26–28 ↗

Coding is one of the clearest strengths

K3 leads ProgramBench at 77.8, two tenths above Sol, and reaches 88.3 on Terminal-Bench 2.1, half a point below Sol. SWE-Marathon is 42.0, ahead of Opus at 40.0, Sol at 39.0, and Fable at 35.0 (under the paper's branch and hardware conditions). FrontierSWE is 81.2, second to Fable's 86.6 and well above the other reported models.

DeepSWE is weaker relative to the leaders, with K3's 67.5 trailing Sol at 73.0 and Fable at 70.0, and Fable also leads PostTrainBench and MLS-Bench-Lite. On SciCode, K3 reaches 58.7, behind Fable's 60.2 but ahead of the rest. Where I'd say it's especially strong is terminal work, long-horizon repository tasks, GPU-oriented work, and program synthesis.

BenchmarkK3Best other scoreRead
ProgramBench77.8Sol 77.6leader
Terminal-Bench 2.188.3Sol 88.8near tie
FrontierSWE81.2Fable 86.6second
SWE-Marathon42.0Opus 40.0leader
DeepSWE67.5Sol 73.0third

Search, tools, and office work

BrowseComp is 91.2, DeepSearchQA is 95.0 F1, ResearchRubrics is 76.2, MCPMark-Verified is 94.5, and AutomationBench is 30.8, every one of them the best number in Table 2. K3 also leads SpreadsheetBench 2 at 34.8, τ³-Banking at 33.4, and Harvey Lab-AA at 94.6. All of these tasks ask the model to retrieve, use tools, operate applications, or produce a professional result, which closely matches the post-training environments from §4.2 that I described earlier.

K3 ranks third on GDPval-AA v2 at 1,686 Elo and second on AA-Briefcase at 1,548 (Fable leads both). OfficeQA Pro is 63.3, below Fable at 69.9 and narrowly below Opus at 63.9. OSWorld 2.0 is 58.3, behind Fable at 66.1 and Sol at 62.6, and SaaS-Bench is 60.1 versus Sol at 61.4. So narrower tool suites favor K3, but the harder desktop and long-form professional tests still leave room above it.

OSWorld-Verified shows how close some comparisons are, with K3 at 84.8 and Fable at 85.0, and CorpFin v2 has the same two-tenths gap (71.6 to 71.8). Differences like these are smaller than many plausible sources of run-to-run and setup variation. Repeated runs are only given for selected tests, with no error bars, so for those cases “competitive” seems a better reading to me than a stable rank. Table 2 and §6.1.4, pp. 26–28 ↗

Vision improves when the model can use Python

K3 leads OmniDocBench at 91.1. It reports 90.0 on Video-MME and 82.1 on MMVU, above the other models the table supplies scores for (Fable is absent from both rows). BabyVision with Python is 85.7, below Fable at 90.5 and Sol at 88.9, and WorldVQA is 51.0, second to Fable's 56.7 under the forced-answer prompt.

The paired rows show what the Python observation loop adds. Math-Vision rises from 94.3 to 97.8, CharXiv from 84.8 to 91.3, and MMMU-Pro from 81.6 to 83.4. ZeroBench pass@5 climbs all the way from 23.0 to 41.0! Python doesn't always give K3 the best score, since Fable stays higher on tool-assisted CharXiv and ZeroBench and reaches 98.6 on Math-Vision. But the gains within the model are consistent, and I read them as support for the training choice to let visual agents crop, transform, calculate, and look again.

Math-Vision94.3→97.8+3.5
CharXiv RQ84.8→91.3+6.5
MMMU-Pro81.6→83.4+1.8
ZeroBench pass@523.0→41.0+18.0
Each pair compares K3 without and with the Python tool under the report's evaluation protocol.

The team's internal evaluations

Kimi's team maintains private tests for coding experience, always-on assistants, multi-agent coordination, autonomous execution, instruction learning, agentic vision, online deliverables, deep research, and conversation. K3 leads the reported Swarm Bench at 76.3 and Deep Research Bench at 90.0. On Kimi Code Bench 2.0 it reaches 73.7 under Claude Code, below Fable at 76.9, and 72.9 under Kimi Code. Coding Experience is 59.9, one tenth above Fable at 59.8.

To rerun these comparisons, I'd need the tasks, graders, refresh rules, and contamination checks, and those aren't released (the table gives no uncertainty either). Competitor fallbacks and refusals affect some rows, and agent wrappers differ across models. So I read the scores as measurements of these particular setups. Establishing a public ranking would mean reproducing the setups and seeing how much the scores vary. §6.2.1 and Table 3, pp. 28–29 ↗

K3 wins 58.6% of the blind web-development comparisons

Experts blindly compare K3 and Opus 4.8 outputs on the internal web-development suite. K3 wins 58.6 percent of pairings, ties 13.8 percent, and loses 27.6 percent, a net win rate of 31 points, and its largest category advantage is 59.1 net points on 3D and WebGL work. Because the report also notes weaker or closer categories, I find the breakdown more useful than a single averaged judge score.

K3 preferred 58.6%tie 13.8%Opus preferred 27.6%

Blind judging reduces brand bias, but the suite and the internal judge procedure remain private. Still, the result lines up with the public WebDev Arena (discussed below) and with the pre-training and RL emphasis on rendered code. Table 4, pp. 29–30 ↗

K3 finds real vulnerabilities, but the end-to-end result is 0 of 41

In the defensive tier, K3 has to discover and reproduce vulnerabilities. Human review confirms roughly 70 percent of the findings submitted for review, including 16 previously unknown vulnerabilities across six projects. We don't get the total number of raw findings, though, so that confirmation rate has no published denominator for all generated candidates.

In the offensive tier there are 36 human-solvable tasks (16 user-space targets and 20 Linux kernel targets). K3 completes 14, compared with GLM-5.2's eight, but ten of those successes are in user space, which leaves only four kernel completions. The team names the recurring failures: finishing an exploit chain after obtaining primitives, choosing a poor strategy under mitigations, entering long debugging loops, and failing to verify the final deliverable.

An independent UK AISI and NIST CAISI assessment reports 32 percent versus GLM's 24 percent on ExploitBench, and 17 versus 11 completed steps in a simulated enterprise network. Yet in that same assessment K3 achieves arbitrary code execution on zero of 41 end-to-end tasks. I think the combination is what matters here: K3 can find real vulnerabilities and finish some live exploits, while hardened end-to-end exploitation remains far from expert completion. (OpenAI and Anthropic models are excluded from the paper's internal exploit comparison because their policies refuse parts of the test.) §6.2.2, pp. 30–31 ↗

Independent evaluations at the time of the report

As of July 23, 2026, Artificial Analysis places K3 fourth among 580 entries with an Intelligence Index of 57.1. Count Sol's effort variants as one model and K3 moves to third. Vals AI places it second among 39 models at 74.7, behind Fable at 75.1 and ahead of Sol at 73.1. Each of these aggregates uses its organization's own test mix and setup.

Human-preference arenas tell a more specialized story. K3 is first of 99 on WebDev Arena at 1,678 Elo, ahead of Fable at 1,634. It's eighth of 200 on Text Arena at 1,486 and fourth of 37 on Agent Arena at 9.1. Arena scores move as votes accumulate (the Agent Arena was only a few days old at the report's cutoff). Still, I'd count the public web-development lead as an important independent match for the internal web result. §6.3 and Table 5, pp. 31–32 ↗

#4of 580

Artificial Analysis

#2of 39

Vals Index

#1of 99

WebDev Arena

#8of 200

Text Arena

#4of 37

Agent Arena

Cost changes the practical comparison

On Kimi Code Bench 2.0, K3 is four points behind Fable at 38 percent of its cost. Its BrowseComp score is 91.2 at $2.03 per task, about half the reported cost of Sol and an order of magnitude below the max-effort Claude runs. On GDPval-AA v2, K3 sits within 50 Elo of Sol at 13 percent lower cost and costs 2.6 times less than Fable, while on AA-Briefcase it places second at roughly half Fable's cost.

These comparisons mix sources. Kimi Code costs come from internal runs with different agent wrappers, BrowseComp combines Kimi measurements with published competitor charts, and GDPval and Briefcase use pay-per-token API prices from Artificial Analysis. So I'd read them as deployment examples at a dated price point (they aren't a controlled systems benchmark). Even with that caution, the numbers explain why K3 can be a strong model without topping every row. It often approaches the highest score at much lower reported inference cost. §6.4 and Figure 13, pp. 31–32 ↗

Case studies · Report §7, pp. 33–34

Long-running coding, research, and design tasks

The report's final section leaves standardized benchmarks behind and shows completed work. These cases are self-reported demonstrations (not controlled estimates of average user performance), but they do show the duration and technical range the team is targeting.

Up to twenty-four hours of kernel optimization

Each model receives an identically configured sandbox and up to 24 hours per task to profile, rewrite, and benchmark one of four kernels: AttnRes, DeepSeek Sparse Attention, KDA, and MLA with head dimension 512. The machines include an NVIDIA Hopper GPU and a second vendor's general-purpose GPU, so the agent can iterate against real timing results instead of submitting one code sample for static inspection.

K3 cuts AttnRes latency from 283.6 milliseconds to 114.4 milliseconds. It reduces DSA runtime by 55.1 percent and KDA runtime by 73.6 percent, and its MLA implementation reaches more than half of the measured peak TFLOPS. Across the four tasks, the report says K3 matches Fable 5 with fallback and exceeds Opus 4.8, Sol, and GPT-5.5. Figure 14 plots the AttnRes improvement across active hours, which I find useful, because you can see the gains continue after the first working kernel rather than only the final point.

AttnRes latency283.6 ms→114.4 ms
DSA runtime−55.1%
KDA runtime−73.6%
MLA throughput> ½ peak TFLOPS

The Kimi team also says an early K3 checkpoint handled most of its kernel optimization during late-stage model development. That's operational testimony from the model's maker (there's no separately audited usage log), so for me the measured kernel changes are the stronger part of the case. Figure 14 and §7, p. 33 ↗

MiniTriton: building a GPU compiler

K3 built MiniTriton, a compact compiler for GPU tensor programs. You describe calculations on rectangular tiles of data in a small Python language, and the compiler turns that language into an intermediate representation, applies rewriting passes, generates GPU instructions, and runs them through a CUDA runtime. On top of it sits a tensor library that can execute operations immediately or compile them first, and it also supplies differentiation, neural-network modules, distributed training, sparse operations, and visualization. So the project spans the whole route from user code to a training loop, well beyond one isolated kernel.

On an NVIDIA L20, the report says MiniTriton's geometric mean beats ordinary immediate PyTorch execution and torch.compile across its core suite. Its largest from-scratch matrix multiplication reaches about 90 percent of the fastest rate measured on that machine and approaches NVIDIA's tuned matrix library, and its KDA prefill kernel beats the matched Triton reference. A small GPT trains end to end with a loss curve close to PyTorch, and when both are compared with an FP64 reference, full-model gradient differences stay within 10−4 of Torch autograd.

I like that this case has public code, which already makes it more inspectable than a screenshot of an agent conversation. But the paper doesn't provide a blinded comparison of generated compiler quality or isolate which parts humans repaired. What it does supply is roofline plots, convergence curves, and numerical checks for the finished artifact. Figure 15 and §7, pp. 33–34 ↗

A 48-hour chip-design run

In another autonomous run, K3 builds an inference-chip prototype for a small version of its own architecture. Its design includes hybrid KDA and MLA, Block AttnRes with a block size of two, sigmoid MoE routing with one shared expert, and four-bit integer weights that share quantization settings in groups of 128. Kimi Code runs for 48 hours using open electronic-design-automation tools and Nangate45 (a library of reusable logic cells).

The resulting design meets a 4 mm² analytical area budget, closes timing at 100 MHz, and reports more than 8,700 tokens per second in RTL simulation. It contains 1.46 million standard cells, 0.277 MiB of on-chip static memory, and a four-bit multiply-and-add array that converts values back to a wider format as part of the operation. These are pre-silicon numbers from an RTL flow and not measured performance from fabricated hardware, but the source release makes the artifact available for a deeper engineering audit.

Implementing an astrophysics calculation

For an astrophysics task about I–Love–Q universal relations, K3 reviews more than twenty papers, cross-checks their results, implements a numerical pipeline, evaluates over 300 equations of state, finds inconsistencies in published formulas, writes more than 3,000 lines of Python, and produces an interactive HTML dashboard. By the report's count that took about two hours, against an estimated one to two weeks for an experienced researcher.

I'd treat that time comparison as anecdotal, since no matched human study is described. Still, a successful trajectory has to keep citations, formulas, numerical code, data products, and a user-facing explanation consistent, and that combination resembles the search, professional-work, coding, and web environments used during RL.

Research with parallel agents

One Kimi Work case produces an interactive history of 42 years of the AI-ASIC industry. It goes through more than 120 revisions, reads 87 quarterly reports and 99 original PDFs totaling over 11,000 pages, runs more than 2,800 web searches, and issues more than 1,100 terminal queries. Another case analyzes 391 gravitational-wave events from GWTC-5 with more than twenty concurrent subagents, then produces seven scientific visualizations, two summary tables, and a synthesis of more than ten papers.

Each trajectory has to keep its sources and calculations consistent through many tool calls and revisions, and subagents add another coordination problem, because their outputs must agree on the data and definitions they share. If you wanted to check the finished research, you'd have to follow the cited reports into the tables and calculations, then inspect the revision history for unresolved discrepancies.

Video editing and motion design

K3 creates a motion-graphics explanation of its own architecture in the style of a popular mathematics video channel, and edits a teaser from 56 source clips. That work includes clip selection, motion-matched cuts, beat-level synchronization, audio processing, and several revisions, and the team estimates one to two days for an experienced editor to make a comparable short video.

There's no numerical quality test for the video. What the report does show is the scale of task the team wants K3 to handle: hours of tool use ending in a finished artifact.

What the current proofs cover

The sequence result is one I especially wanted. LanguageModel.run_eq_logits proves that processing embeddings token by token gives exactly the public model's full-sequence logits. run_append comes from the same causal-scan structure: split the input at any position and every logit and the final decoder state are preserved, provided the second chunk resumes from the first chunk's state. These are equalities over the real-valued model (deterministic expert routing included) for every sequence length and parameter value, and each one covers every input its statement admits.

The packed graph has its own composed theorem, from token lookup through the decoder to vocabulary logits, under the stated dimension and route-agreement conditions. At a smaller scale, the quantile proof gives a complete condition for minimizing the balancing objective, ties and interval endpoints included. It shows that the strict-count clause in Appendix C misses the upper endpoint (the interval stated just after it is correct). Finding that endpoint case was useful to me, because the theorem tells us precisely which thresholds minimize the objective, so we aren't left holding a counterexample alone.

01 · checkedPaper equation → reference function

KDA, MLA, AttnRes, experts, routing, quantization, selected training equations, and EAGLE have explicit tensor or probability semantics.

02 · checked by componentReference function → tensor composition

The Kimi development has typed tensor compositions for all four sequence/channel layer combinations and the MoonViT embedding, encoder, and merge/project stages.

03 · checked for one packed tokenTyped graph → packed semantics

Denotation theorems identify graph evaluation with the packed reference calculation through vocabulary logits.

04 · openPacked state → public causal model

List caches and packed tensors still need representation relations for KDA, MLA, AttnRes, the backbone, and the complete language model.

05 · openGraph → executable K3 checkpoint

Runtime top-k, released parameter loading, checkpoint-backed assembly and generation, execution refinement, and finite-precision kernel bounds remain to be connected to the K3 theorem.

The public full-sequence API now agrees with repeated causal token steps by LanguageModel.run_eq_logits. The next connection is between those public states and the packed graph: packing KDA histories, MLA caches, and AttnRes sources must preserve each step.

Report claimCurrent evidenceNeeded for a stronger claim
Pre-training data and scaling law (§§3.1–3.2)empirical

Dataset manifests, sampling code, fitted curves, and reproducible measurements.

Optimizer and context curriculum (§§3.3–3.4)reported design

Stage durations, optimizer execution, checkpoints, loss traces, and evidence that a run followed the described curriculum.

RL synthesis and agent environments (§4.2)not modeled

Environment semantics, graders, reward aggregation, sandbox behavior, and rollout traces.

KDA kernels and context parallelism (§5.1)scan algebra checked

The bridge from actual KDA updates to affine summaries, then refinement to finite-precision kernels and distributed collectives, remains open.

MoonEP and memory system (§5.2)counting checked

The online placement algorithm, communication semantics, memory accounting, and machine-checked cost assumptions.

1M-context RL infrastructure (§5.3)not modeled

Sequence packing, sandbox scheduling, failure recovery, and measured throughput.

Inference and serving (§5.4)not modeled

Prefix-cache policy, kernel implementation, fleet scheduler, latency traces, and end-to-end refinement.

Benchmarks and case studies (§§6–7)reported results

Exact prompts, judge implementations, model artifacts, seeds, and independent reruns.

Source files

The definitions and proofs used above, grouped by component. You can filter by a model name or theorem.

reference

Common.lean

tensor helpers

Shared tensor notation, vector–matrix multiplication, outer products, normalization helpers.

reference

Config.lean

checked constants

Paper dimensions, released-checkpoint validation, layer schedule, compression and block counts.

reference

FeedForward/

activation, experts, routing, MoE

Four modules for SiTU bounds, expert computations, deterministic top-k, and Stable LatentMoE composition.

reference

Microscaling.lean

formats and bounds

FloatLib OCP decoders, finite-code adapters, 32-value blocks, and conditional quantization error bounds.

reference

Model.lean

public semantics

Dependent mixer states, backbone order, multimodal slots, final depth retrieval, and logits.

reference

Sequence/

causal semantics

Separate KDA, MLA, AttnRes, and scan modules. The existing Sequence import brings them together.

proof

Model/Streaming.lean

sequence = token steps

Tensor input and output sequences, retained per-layer state, and a theorem covering the public logits API.

reference

Training/

selected equations

Separate Muon, pretraining, distillation, and draft-model modules, with their existing proofs.

reference

Vision.lean

vision semantics

Released encoder blocks with 2-D RoPE attention, pooling, pixel-shuffle merge, projector, and full vision path.

proof

FeedForward/Quantile.lean

coordinate minimum with ties

A threshold minimizes the objective exactly when strict and weak counts bracket the real-valued target. This covers ties, the upper endpoint the strict count misses, and fractional targets. The endpoint and tie examples are checked there too. The exact-count routing theorem is separate; a threshold is not constructed automatically.

proof

FeedForward/Histogram.lean

distributed counts and error

Shard-independent pooling and interpolation error within one bin width, assuming the true quantile lies in that bin.

proof

Parallel/Context.lean

associative scan

Supplied affine summaries compose associatively and agree with sequential application. Their connection to actual KDA updates remains open.

proof

Parallel/Experts.lean

counting bounds

Appendix E key lemma by its filling construction, the redundant-expert upper bound for every router output, and the capacity lower bound.

protocol

Training/Controls.lean

deterministic controls

Nine teacher indices, selected MOPD reward, token-budget override, and verbosity enforcement.

protocol

ChatTemplate.lean

typed message grammar

Context zones, generation channels, and index-safe parallel tool call/result association.

graph

GraphSpec/Primitives.lean

term builders

General SiTU cap composition and small semantic adapters to canonical TorchLean primitives.

graph

GraphSpec/Expert.lean

graph = forward

Dense expert graph equals the reference SiTU expert forward pass.

graph

GraphSpec/KDA.lean

graph = fixed step

Preparation, recurrent update, readout, window rolling, and complete KDA layer equivalence.

graph

GraphSpec/MLA.lean

graph = stepFixed

Fixed-cache Gated MLA graph and its packed denotation theorem.

graph

GraphSpec/AttnRes.lean

term = packed retrieval

Depth-attention term evaluation over a fixed leading source axis.

graph

GraphSpec/MoE.lean

route-staged graph

A fixed-route graph equals forward; specialization at one input equals forwardReal.

graph

GraphSpec/Backbone.lean

four packed cases

KDA/MLA crossed with dense/sparse channel mixing, each with a denotation theorem.

graph

GraphSpec/Decoder/

layers, depth, backbone

Separate layer graphs, AttnRes depth scheduling, and backbone composition. LanguageModel.lean adds embeddings, final retrieval, logits, and the one-token theorem.

graph

GraphSpec/Vision.lean

component denotations

Primitive graphs for embedding, one encoder block, and merge/project, cut at the exact GELU, equal the reference equations.

graph

GraphSpec.lean

public surface

Imports the typed language-graph modules and states their packed/list boundary.

Conclusion

The next proof I want for K3 connects the public causal state to the packed graph, which means showing that packing each KDA history, MLA cache, and AttnRes source preserves its transition. That would join the sequence theorems to the graph theorem, and we'd have one account of the model instead of two separate ones. Loaded weights and finite-precision execution would come next.

I'd also like to discuss the Appendix C endpoint case with people working on expert balancing. That count condition handles ties and interval endpoints, but the router still needs to choose a threshold and resolve ties. Connecting the theorem to the histogram implementation is what would make it useful for the update itself.

My hope is that we eventually release models with their equations and proofs right alongside the code and weights. For this one, we have concrete connections left to prove, and if you're interested in taking those on, I'd be very happy to work with you :)

References

Cite this article

Robert Joseph George. Kimi K3: the paper and proofs side by side. TorchLean Verified Examples, 2026.

@misc{george2026kimi,
  author = {Robert Joseph George},
  title = {{Kimi K3: the paper and proofs side by side}},
  year = {2026},
  howpublished = {TorchLean Verified Examples},
  url = {https://robertboy18.github.io/TorchLean-Verified-Examples/week-04-kimi-k3-specification/site/}
}
Download BibTeX