Porting Kimi Delta Attention to AWS Trainium with NKI
Kimi K3's attention layer uses Kimi Delta Attention, a gated delta-rule linear attention that shipped only for NVIDIA GPUs. This build log walks through porting its forward pass to AWS Trainium2 in NKI: why decode issues zero matmuls, how prefill's chunked scan handles a triangular solve with no partition-index primitive, the 0 × inf = nan numerics trap, three bugs that appear only on real silicon, and a roofline that matches the theory to the percent.
What it takes to bring a modern linear-attention kernel to a non-CUDA accelerator: what the hardware changes, where the numerics are easy to get wrong, and how to verify correctness on real silicon.
What we built and why
On July 27, 2026, Moonshot AI released Kimi K3, a 2.8-trillion-parameter mixture-of-experts model with open weights. Its attention layer is not softmax attention. It is Kimi Delta Attention (KDA), a gated delta-rule linear attention.
KDA had two production implementations, and both assumed NVIDIA silicon: FLA (
fla-org/flash-linear-attention ), a Triton kernel, and FlashKDA ( MoonshotAI/FlashKDA ), CUDA/CUTLASS for SM90 and later. To run Kimi K3 efficiently on AWS Trainium, you had nothing. No NKI kernel existed in aws-neuron/nki-library or aws-neuron/nki-samples . This project fills that gap with a correct, then fast, KDA forward-inference kernel in NKI, the Neuron Kernel Interface, for Trainium2.The scope is deliberately narrow, and staying clear about scope is the first lesson. In scope: the forward pass of the KDA attention kernel, both prefill (process a whole prompt) and decode (generate one token at a time). Out of scope: the backward pass, training, the MoE feed-forward layers, the full-attention layers, and end-to-end serving. When we say we ran KDA on Trainium, we mean the attention kernel, verified against the reference on real hardware. That distinction is the difference between a claim you can defend and one you cannot.
A short theory of KDA
Softmax attention costs you an
O(T²) score matrix. Linear attention replaces it with a running state S that you update token by token, which turns attention into a recurrence that is O(T) in time and O(1) in memory per step. The delta rule makes the state learn: each step writes a correction, the difference between the value you want and the value the current state predicts. KDA adds a per-channel forget gate so old information decays, and L2-normalized queries and keys for stability.Here is the entire decode step. Every line becomes a hardware decision later:
decay = exp( lower_bound * sigmoid( exp(A_log) * (g_raw + dt_bias) ) ) # per-K-channel forget gateq, k = l2norm(q), l2norm(k) # eps = 1e-6b = sigmoid(beta_raw) # write strength
S = S * decay[..., None] # (1) forget: decay BEFORE the correctionerr = v - (k[..., None] * S).sum(-2) # (2) delta: what we want minus what the state predictsS = S + outer(b * k, err) # (3) write the correctiono = (q * scale) @ S # (4) read the answer outTwo properties drive everything that follows. First, the recurrence is memory-light and matmul-poor: the large object is
S , shaped [K, V] = [128, 128] , and there is no large matrix multiply in the decode step. This is why the decode kernel, on a chip known for its matrix engine, does not use the matrix engine at all. Second, prefill is the same recurrence refactored for parallelism: it splits the sequence into chunks, does the expensive cross-token work inside a chunk with real matmuls, and carries S from one chunk to the next. One algorithm, two kernels.The machine you are programming
You cannot port a kernel to Trainium by translating CUDA idioms. A NeuronCore is not a pool of interchangeable threads. It is a small number of specialized engines attached to an on-chip scratchpad (SBUF):
Engine | What it does | KDA uses it for |
|---|---|---|
TensorEngine (PE) | A systolic array that does matmul , contracting over the partition axis. | Prefill's chunked matmuls. Decode: never. |
VectorEngine | Elementwise and reductions across the free axis. | The entire decode recurrence. |
ScalarEngine | Activations: exp , sigmoid , rsqrt , square . | Gates, L2 norm, decay. |
DMA | Moves data between HBM and SBUF. | Loading inputs, writing outputs. |
| | |
One geometric fact governs the whole port: SBUF is a 2D tile store with 128 partitions. Every on-chip tile is
[partitions ≤ 128, free] . The partition axis is what the TensorEngine contracts over, and it is where your parallelism must live to keep the machine full. A tile that uses 8 of 128 partitions leaves 120 lanes idle. That fact becomes the center of the performance story later.NKI is a Python-embedded kernel language. You write
@nki.jit functions, and ISA ops map to engine instructions. Ops write into a pre-allocated destination tile rather than returning values, so idiomatic NKI reads as a sequence of nisa.op(dst=..., data=...) calls. We wrapped the common ones in thin helpers to keep the kernel body a line-by-line mirror of the numpy reference, which is how you keep a port auditable.One economic fact shaped the workflow: you can develop for free. NKI ships
nki.simulate , a CPU interpreter of your kernel. Trainium instances cost tens of dollars per hour, and capacity is not always available. So the discipline is: do all correctness work in simulation, then buy one focused hardware session for compile, on-device numerics, and profiling. Simulation is necessary but not sufficient.Reference-first discipline
Before writing a line of NKI, we vendored the FLA torch implementation of KDA and pinned it to a commit hash. This is the golden reference, and we check every kernel output against it. One rule, written down before any code, settles every later argument: when the FLA source contradicts the design doc, the FLA source wins.
A concrete example this rule caught: in the recurrence, does the state decay happen before or after the delta correction? The math reads either way. The FLA source does
S = S*decay first, then computes the error against the already-decayed state. Reverse this and your kernel is subtly, plausibly wrong. It passes smell tests and fails at the third decimal place, which is the worst kind of wrong. We fixed tolerance up front too: max abs error ≤ 2e-2, mean abs error ≤ 2e-3 against the fp32 reference. A number you commit to before you see results is a specification. A number you pick afterward is an excuse.Decode: a recurrence that never touches the matmul unit
The decode kernel processes one token for a batch of
(batch, head) pairs. The design question is where the parallelism goes, and the answer follows from the engine model: pack the flattened (B, H) axis onto the 128 SBUF partitions. Each pair gets its own partition, its recurrent state lives in that partition's free dimension, and every lane runs its own delta rule in parallel with no cross-partition communication.The one subtle decision is state layout. The reduction contracts over the
K axis, and NKI's free-axis reduction wants the contracted axis to be trailing, so we store the state v-first as [BH, V, K] . That single transpose choice makes the recurrence a clean sequence of broadcast-multiply-then-reduce over the last axis. The broadcasts use stride-0 access patterns, which are views rather than copies, the NKI way to repeat a vector across an axis without spending DMA on it.The headline result violates the instinct trained on GPUs: the decode kernel issues zero matmuls. On a chip whose marquee feature is a systolic matrix array, the entire token-generation path runs on the Vector and Scalar engines. A per-channel recurrence over a
[128,128] state has no large contraction to feed a matmul unit. If you port this kernel by looking for matmuls to accelerate, you optimize a code path that does not exist. The algorithm tells you which engine you live on.Prefill: the chunked scan and a triangular solve
Prefill processes a whole prompt, up to
T = 4096 tokens. A strict token-by-token recurrence would leave the machine almost idle, so prefill uses a chunked scan: split the sequence into chunks of BT = 64 , do the dense intra-chunk work with matmuls, and carry the state between chunks. Here K sits on the partition axis, so nc_matmul is the natural primitive for every score-build and the state update.One piece deserves a warning, because it is where the algorithm stops looking like a recurrence and starts looking like numerical linear algebra: the UT/WY transform, which inverts a lower-triangular matrix per chunk. You do not compute a generic inverse. You do forward substitution, a strictly serial
BT -step row solve. Here the accelerator model bites: NKI has no "read partition i " primitive, so you cannot index a single partition of an on-chip tile directly. You build the operation you want out of the operations you have:- To extract partition row
i: multiply the matrix by a one-hot column of a compile-time identity, as thestationaryoperand of annc_matmul. Contracting a one-hot against the matrix over the partition axis yields that row.
- To write back into only partition
i: use the same one-hot, broadcast across the free axis, as a write mask, then multiply-then-add so the update touches only lanei.
This is the deep lesson of prefill, and it generalizes: on a specialized accelerator, "how do I read or write element
i ?" is often the wrong question. The right question is "what bulk operation has the effect I want?" A one-hot matmul is a gather. A masked add is a scatter.We validated prefill against the reference across single chunk, two chunks,
T = 4096 , with and without an initial state, multi-batch and multi-head, and non-chunk-aligned lengths. The strongest test compares prefill against T sequential decode-kernel calls, which cross-checks the two kernels against each other so a shared misunderstanding of the algorithm has nowhere to hide.The numerics chapter: 0 × inf = nan
Every kernel port has one bug that costs a full day. Ours was
0 × inf = nan , and the fix is subtle and the failure is silent.Inside a chunk, prefill computes a decay term
exp(g_c − g_i) between pairs of positions. For the entries the algorithm uses, the causal ones, the exponent is ≤ 0 and its exp is well-behaved. But the algorithm computes the full score matrix and applies causality by multiplying with a triangular mask. The entries it discards have exponents that can be arbitrarily positive, so exp(...) overflows to +inf , and the mask then multiplies those infinities by 0 . In IEEE floating point, 0 × inf = nan . The nan passes straight through the mask that was supposed to erase it and corrupts the output, with no error and no warning.The fix is one line, and it looks deletable to anyone who did not live through the bug:
diff = nl.minimum(diff, 0.0) # clamp the decay exponent to <= 0 BEFORE exp()Clamping at zero is a no-op on every entry the algorithm keeps and turns every entry it discards into a harmless
exp(0) = 1 , which the mask multiplies to 0 . No infinities are created, so no nan can be born. The general principle: on hardware, mask * value is not a safe way to select. If the masked-out value can be non-finite, mask-by-multiply manufactures nan . Make the discarded values finite before you multiply.The compile wall: three bugs that live only on hardware
Here is the most important workflow lesson: a kernel that passes
nki.simulate perfectly can still fail to compile, or fail to run, on real hardware. We had 43 green simulation tests, then hit three independent walls on a NeuronCore, none of which the simulator models.Wall 1: the compiler was invisible. The first on-device run failed with a driver error that amounted to running
python None compile ... . The NKI runtime resolves the compiler with shutil.which("neuronx-cc") , and in a bare venv invocation the compiler was not on PATH , so which returned None . The fix was one line, export PATH=$V/bin:$PATH , but it cost real time because the error pointed nowhere near the cause. On a new accelerator, budget time for toolchain plumbing, not just the kernel.Wall 2: the simulator was too forgiving about outputs. Our kernels took the output tensors as pre-allocated arguments and wrote into them with DMA.
nki.simulate accepts this; the real neuronx-cc rejects it with NCC_INKI003: Insufficient number of outputs . The backend requires that a kernel's outputs be values it allocates itself (in nl.shared_hbm ) and returns:out = nl.ndarray((BH, V_DIM), dtype=nl.float32, buffer=nl.shared_hbm)state_out = nl.ndarray((BH, V_DIM, K_DIM), dtype=nl.float32, buffer=nl.shared_hbm)...return out, state_outnki.simulate accepts the return-style form identically, so this became the single code path for both simulation and hardware. When you find a discrepancy, prefer the fix that collapses the two paths into one rather than forking them.Wall 3: the target auto-detected wrong. With the compiler found and outputs fixed, the NEFF compiled, then failed to load with
NRT_INVALID(2): Failed to load model . NKI's target auto-detection resolved the box as trn3 , and a trn3 -targeted NEFF compiles fine but does not load on this runtime. Forcing NEURON_PLATFORM_TARGET_OVERRIDE=trn2 made it load and run cleanly. "Compiles," "loads," and "runs correctly" are three different milestones on new hardware, and each can fail for reasons the previous one gave no hint of.Proving it on silicon
The word "done" is cheap, so here is the standard we held it to. We ran both kernels on a real NeuronCore, not the simulator, against the pinned torch reference at the committed tolerance:
tests/test_decode_hardware.py::test_decode_matches_reference_on_hardware PASSEDtests/test_prefill_hardware.py::test_prefill_matches_reference_on_hardware PASSED2 passed in 19.49sBoth within
atol/rtol = 2e-2 . The prefill test uses two chunks so it exercises the inter-chunk state carry and the TensorEngine matmul path, the parts decode never touches. The two passes are independent evidence, not the same code path run twice.The roofline: reading the profile
Correctness is table stakes. The interesting question is where the time goes, and whether that matches what the algorithm predicts. We profiled the decode kernel on-device:
Engine | Utilization | Notes |
|---|---|---|
VectorEngine | 89.1% (121.7 µs of 136.5 µs) | The delta-rule recurrence lives here. |
DMA | 15.2% | Loading inputs, writing state. |
ScalarEngine | 7.6% | Gates, L2 norm, decay. |
TensorEngine | 0% | Zero matmuls, as designed. |
On a chip sold on its matrix engine, the decode kernel uses that engine 0% of the time, and this is correct, a predicted consequence of the decode design. When your measurement matches your theory this cleanly, you have understood the workload.
Why is Vector at 89% and the kernel not faster? The profiler localized it to seven full-
[p, V, K] operations at about 17 µs each. The root cause is partition under-utilization: the test ran with BH = 8 , so only 8 of the 128 SBUF partitions were live. Each hot op streams the full free dimension per lane, but with 120 of 128 lanes empty, the Vector engine is roughly 16× under-occupied. This points to three levers, in rough order of payoff:- Fill the partitions. In real serving, batch × heads is far larger than 8, so occupancy improves at production batch sizes. The profiling number is close to a worst case.
- Repack the parallel axis. For genuinely small
BH, fold part of theVaxis onto the partition dimension to raise occupancy toward 128 regardless of batch.
- Fuse the multiply pairs. Several hot ops are adjacent multiply-then-multiply or multiply-then-reduce pairs; fusing removes a full-tile pass each.
A profile is a diagnosis, not a scoreboard. "89% Vector-bound" is not the finding. "89% Vector-bound because 120 of 128 lanes are idle" is the finding, and it changes the optimization from "make the vector ops faster" to "make the tile wider."
What we would do next, and the honest caveat
The forward kernel is done and verified on hardware. Next: raise partition occupancy (mostly layout, not new math); profile prefill, whose story will be a TensorEngine one; tune
chunk_size ; integrate with vLLM-Neuron and NxD Inference; and add variable-length batching, then the backward pass.The standing caveat, because it is the difference between an honest claim and an overclaim: what exists today is the KDA attention kernel, prefill and decode forward inference, verified on Trainium. It is not an end-to-end Kimi K3 serving deployment.
The seven lessons
- Scope honestly. "A verified KDA kernel" is not "Kimi K3 on Trainium." Say which one you have.
- The algorithm picks the engine. A per-channel recurrence has no matmul; do not optimize a code path that does not exist.
- Reference-first, pinned, source wins. Decide the tie-breaker before you need it.
-
0 × inf = nan. Mask-by-multiply is not safe selection; make discarded values finite first.
- Simulation passing is not hardware passing. The compiler, the output ABI, and the load target each fail for reasons simulation never shows.
- "How do I index element
i?" is often the wrong question. A one-hot matmul is a gather; a masked add is a scatter.
- "The log says it passed" is not "I watched it pass." For anything you publish, re-run it live.
Built with NKI on AWS Trainium2. The kernel, the reference harness, and the full test suite are in the repository.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article