The NKI Library provides pre-built reference kernels you can use directly in your model development with the AWS Neuron SDK and NKI. These kernel APIs provide the default classes, functions, and parameters you can use to integrate the NKL kernels into your models. More details can be found in the NKI Library Documentation
| Kernel API | Description |
|---|---|
| Attention Backward Kernel | The kernel computes the Flash Attention backward pass, producing dQ, dK and dV by recomputing attention scores instead of materializing the full attention matrix. |
| Attention CTE Kernel | The kernel implements attention with support for multiple variants and optimizations. |
| Attention KV Parallel Segmented CTE Kernel | The kernel implements KV-parallel segmented prefill attention with online softmax merging for context parallelism. |
| Attention TKG Kernel | The kernel implements attention specifically optimized for token generation use cases. |
| Attention TKG Mask Generation Kernel | The kernel generates the token-generation attention mask from position IDs, for flat and block KV caches, from HBM tensors. |
| Cascaded Max Kernel | The kernel finds the global maximum value and its index across a tensor using a multi-stage cascaded reduction. |
| Find Nonzero Indices Kernel | The kernel finds the indices of nonzero elements along the T dimension of a [T, C] tensor, for each column. |
| Indexed Flatten Kernel | The kernel writes each row of an [E, T] tensor into an output tensor at per-row block offsets, for MoE blockwise matrix multiplication. |
| MLP Kernel | The kernel implements a Multi-Layer Perceptron with optional normalization fusion, multi-LoRA (per-token adapters on gate/up/down) and various optimizations. |
| MoE Block TKG Kernel | The kernel implements a fused MoE block for token generation, with RMSNorm, router top-K, an optional shared expert and the expert MLPs, in selective-expert and all-expert modes. |
| MoE CTE Kernel | The kernel implements Mixture of Experts optimized for Context Encoding use cases. |
| MoE TKG Kernel | The kernel implements Mixture of Experts optimized for Token Generation use cases. |
| Output Projection CTE Kernel | The kernel computes the output projection operation optimized for Context Encoding use cases. |
| Output Projection TKG Kernel | The kernel computes the output projection operation optimized for Token Generation use cases, with optional multi-LoRA (per-token adapters). |
| QKV Kernel | The kernel performs Query-Key-Value projection with optional normalization fusion and multi-LoRA (per-token adapters on Q/K/V). |
| RMSNorm-Quant Kernel | The kernel performs optional RMS normalization followed by quantization to fp8. |
| RMSNorm MX Prefill Kernel | The kernel fuses RMSNorm with MX quantization and optional router top-K in token-major [T, H] layout for prefill. |
| RMSNorm MX Quantize TKG Kernel | The kernel fuses an optional residual add, RMSNorm and optional MX, static or row quantization for token generation. |
| RoPE Kernel | The kernel applies Rotary Position Embedding to input embeddings with optional LNC sharding. |
| RoPE HF Kernel | The kernel applies Rotary Position Embedding to query and key tensors in the HuggingFace [batch, heads, seq, head_dim] layout. |
| Rotational Top-K Kernel | The kernel finds the k largest elements along the last dimension using a multi-stage rotational reduction, with LNC sharding support. |
| Router Top-K Kernel | The kernel computes router logits and top-K selection for Mixture of Experts models. |
| Cumsum Kernel | The kernel computes cumulative sum along the last dimension. |
| Kernel API | Description |
|---|---|
| AdaLN Quantization Kernel | The kernel implements fused gated residual add, LayerNorm/RMSNorm, per-hidden (adaptive) modulation and optional FP8 row quantization. |
| Attention Block TKG Kernel | The kernel implements fused attention block for TKG with RMSNorm, QKV, RoPE, and output projection, with optional multi-LoRA on QKV and output projection. |
| Attention Const Max Kernel | The kernel implements constant-max attention, eliminating the online softmax reduction when a pre-known max is available. |
| BatchNorm Backward Kernel | The kernel implements batch normalization backward with optional fused ReLU, pre-ReLU residual addition, and residual-gradient output. |
| Bitonic Sort Kernel | The kernel sorts every row of a 2-D fp32, bf16, fp16 or int32 tensor and returns values and indices like torch.sort, using stable bitonic networks on the Vector Engine; long rows span up to 128 partitions, float rows with indices can take one key + payload network, with optional per-row lengths and a values-only mode. bitonic_argsort is its argsort subkernel for data and indices in SBUF. |
| Cross Entropy Kernel | The kernel implements memory-efficient cross entropy loss forward and backward passes for large vocabularies. |
| Depthwise Conv1D Kernel | The kernel implements depthwise 1D convolution using implicit GEMM. On trn2, calls with at least 128 channels and filters of at most 512 taps run on the one-row diagonal path of the grouped Conv2D kernel. |
| Blockwise MM Backward Kernel | The kernel implements blockwise matrix multiplication backward pass for dropless Mixture of Experts. |
| Conv1D Kernel | The kernel implements 1D convolution using a filter replication strategy. |
| Conv3D Kernel | The kernel implements 3D convolution using a filter replication strategy. On trn2, thin 2D layers with wide rows run on a row-banded path that stacks image rows with their channels on the tensor engine. |
| Grouped Conv2D Kernel | The kernel implements grouped and depthwise 2D convolution (torch.nn.functional.conv2d with groups) with block-diagonal banded filter matrices built on chip; small depthwise planes with many channels run as whole planes with diagonal filter matrices. |
| Conv3D Transpose Kernel | The kernel implements 3D transposed convolution by performing a 3D convolution with input dilation. On trn2, thin stride-2 2D layers run on the same row-banded path, without dilating the input. |
| Conv3D Backward Kernel | The kernel computes the 3D convolution backward pass (dx, dw, db) for a 3D convolution forward pass. |
| Conv3D Temporal Unroll Kernel | The kernel implements 3D convolution with temporal unrolling and column tiling for small C_out configurations. |
| Dynamic Shape Kernels | The kernels dynamic input shapes with dynamic loop tiling on dynamic dimension. |
| Grid Sample 3D Kernel | The kernel implements torch.nn.functional.grid_sample for 5-D inputs (aten.grid_sampler_3d: trilinear and nearest; zeros, border and reflection padding; both corner conventions), gathering each trilinear sample's 2 x 2 x 2 neighbourhood as one row of an oct scratch copy of the input, or its eight taps from a zero-padded channels-last copy. |
| Grid Sample Bicubic Kernel | The kernel implements torch.nn.functional.grid_sample with mode="bicubic" for 4-D inputs (zeros and border padding; both corner conventions), gathering each sample's 4 x 4 neighbourhood as one row of a scratch copy of the input padded by 4 pixels. |
| RoI Align Kernel | The kernel implements torchvision.ops.roi_align for sampling ratios 1, 2 and 4 (both box conventions), gathering each bin's bilinear samples from a channels-last scratch copy of the input whose entries hold a pixel and its right neighbour. |
| Deformable Convolution Kernel | The kernel implements torchvision.ops.deform_conv2d (DCNv1, and DCNv2 with a mask; one offset group and one weight group), gathering each kernel tap's 2 x 2 neighbourhood with batched indirect DMA from a channels-last scratch copy of the zero-padded input and multiplying the sampled columns by the weights on the Tensor Engine. |
| Grid Sample Backward Kernel | The kernel computes the input and grid gradients of grid_sample for 4-D inputs (aten.grid_sampler_2d_backward): the input gradient by deduplicated DMA read-modify-writes into the forward's scratch layout, the grid gradient from the forward's gathered taps. The same file has bilinear_splat, the summation splat of softmax splatting. |
| Grouped MM Kernels | The kernels multiply each expert's contiguous token rows by its matrix (grouped_mm_2d_3d, forward and token gradient) and sum each expert's outer products (grouped_mm_2d_2d, weight gradient) for mixture-of-experts layers, with the expert offsets on device so a new routing does not recompile. grouped_mm_2d_3d_supported and grouped_mm_2d_2d_supported tell a framework, without tracing, whether the kernels accept a call. |
| Grid Sample Kernel | The kernel implements torch.nn.functional.grid_sample for 4-D inputs (bilinear and nearest; zeros, border and reflection padding; both corner conventions) for any grid, gathering each sample's 2 x 2 neighbourhood with batched indirect DMA from a channels-last scratch copy of the input. |
| Interpolate Kernel | The kernel implements torch.nn.functional.interpolate (nearest, nearest-exact, linear, bilinear, bicubic, trilinear, lanczos and area, and antialias for bilinear, bicubic and lanczos; 3-D to 5-D input) without gathers: a host planner finds each axis's period of PyTorch's float32 taps, and the kernel blends statically shifted rows and columns on the Scalar and Vector Engines, or, for resizes without a short period, multiplies by banded operator blocks on the Tensor Engine. An optional fused epilogue (scale, per-channel bias, activation) and channel-slice output save the HBM round trips of the ops that usually follow. interpolate_backward computes the input gradient, 3-D to 5-D, with the transposed operators on the same paths (no scatter). interpolate_supported and interpolate_backward_supported tell a framework, without tracing, whether the kernels accept a call. |
| Fine-Grained AllGather Kernel | The kernel implements fine-grained ring-based all-gather. |
| FGCC Kernel | The kernel implements fused all-gather and matrix multiplication (Fine-Grained Gather Collective Compute). |
| FlashAttention-2 Forward (trn3) Kernel | The kernel implements FlashAttention-2 forward for Trainium 3 with a software-pipelined online softmax and support for arbitrary sequence lengths. |
| KNN Points Kernel | The kernel finds the exact k nearest neighbours (squared Euclidean distance) of query points among point clouds or feature sets, with distance tiles on the tensor engine and a two-stage top-k over bin maxima; point sets above 16384 points (up to 2^24) stream through SBUF in blocks. |
| Pixel Shuffle Kernel | The kernels implement torch.nn.functional.pixel_shuffle and pixel_unshuffle bit for bit with whole-row DMAs and strided on-chip copies on the Vector and Scalar Engines (no gathers, no descriptors built on GpSimd). pixel_shuffle_neuron and pixel_unshuffle_neuron dispatch to them from torch-neuronx, each as the other's backward, and pixel_shuffle_supported and pixel_unshuffle_supported tell a framework, without tracing, whether the kernels accept a call. |
| Upsample Conv2D Kernel | The kernel implements a nearest 2x upsample followed by a 3 x 3 convolution (F.conv2d(F.interpolate(x, scale_factor=2, mode="nearest"), weight, bias, padding=1), the upsampler of U-Net and VAE decoders) without building the upsampled input: each of the four output phases is a 2 x 2 convolution of the low-resolution input with weights folded on chip (2.25x fewer multiply-adds), run as flat-shift matmuls on the Tensor Engine. upsample_conv2d_neuron dispatches to it from torch-neuronx, and upsample_conv2d_supported tells a framework, without tracing, whether the kernel accepts a call. |
| Ring Attention Backward Kernel | The kernel implements the backward pass for ring attention using collective permute operations. |
| RNG Kernels | The kernels provide GPSIMD engine RNG state management and random number generation. |
| JAX Random Normal Kernel | The kernel generates jax.random.normal for threefry keys in JAX's partitionable layout, bit-exact on JAX's random bit stream, with an on-device loop over row blocks; offset and row_stride arguments generate a block of a sharded tensor, and normal_generation_2d plans the call for an output of any rank. |
| Transformer TKG Kernel | The kernel implements a transformer forward pass megakernel optimized for token generation (TKG). |
| Ring Attention Forward Kernel | The kernel implements ring attention forward using attention_cte with HBM I/O and online softmax reduction for context parallelism. |
| Fused Adam Kernel | The kernel implements a fused Adam/AdamW/AMSGrad optimizer step with SPMD tiling and Scalar Engine fusion. |
| Fused SGD Kernel | The kernel implements a fused SGD optimizer step (momentum, dampening, Nesterov momentum, weight decay, maximize). |
| Fused Adagrad Kernel | The kernel implements a fused Adagrad optimizer step (weight decay, learning-rate decay, maximize). |
| Gated DeltaNet Kernels | The kernels implement Gated DeltaNet linear attention: chunked prefill (gdn_cte, with a choice of Schur-complement or Neumann-series intra-chunk inverse), its backward pass (gdn_cte_bwd, the reverse-mode VJP of the Schur forward), single-token decode, the fused decode megakernel, and the depthwise conv1d. |
| KDA Spec Verify Kernel | The kernel implements the Kimi Delta Attention verify step of speculative decoding for a batch of sequences: per (sequence, head) it folds the previous step's accepted tokens into the recurrent state, returns that committed state, and computes the outputs of the new draft tokens from it without writing their state, in the chunked (WY) form of the gated delta rule with every pair of a core in one block-diagonal matrix. |
| KDA Short Convolution Prefill Kernel | The kernel prepares the inputs of Kimi Delta Attention prefill: the causal depthwise short convolution and SiLU of the token-major q, k and v projection output, continued from the input rows before the chunk, then the per-head L2 norm of q and k, written head-major as [H, S, D] float32 for the chunked delta rule. |
| MXFP8 Matmul Kernel | The kernel implements MXFP8 matrix multiplication with configurable tiling and quantization. |
| MXFP8 MLP Kernels | The kernels implement MXFP8 MLP forward and backward passes with recompute support. |
| MXFP8 MoE Forward Kernel | The kernel implements blockwise matrix multiplication forward pass for dropless Mixture of Experts using MXFP8 quantized matmuls, and emits the activation checkpoints the MXFP8 MoE backward consumes. |
| MXFP8 MoE Backward Kernel | The kernel implements blockwise matrix multiplication backward pass for dropless Mixture of Experts using MXFP8 quantized matmuls. |
| MXFP8 Quantize Kernel | The kernel implements block-wise MXFP8 quantization with scale packing. |
| Foreach Norm Kernels | The kernels implement L1, L2, and Linf norm computation with SPMD tiling and fused activation-reduce. |
| Foreach Elementwise Kernels | The kernels implement elementwise add, sub, mul, div, addcdiv, addcmul and sqrt operations with SPMD tiling for scalar and tensor operands. |
| Linear Scan Kernel | The kernel computes first-order linear recurrence along the last dimension using tensor_tensor_scan. |
| Selective Scan Kernel | The kernel implements fused Mamba-style discretization, recurrence, and output projection. |
| SSD Kernel | The kernel implements Mamba-2 chunk-wise parallel SSD computation with TensorE matmuls and VectorE scans, with optional LNC sharding across heads. |
| Gather Kernel | The kernel gathers rows from a 2D input tensor based on a 1D index tensor using indirect DMA load. |
| Scatter-Add Kernel | The kernel scatter-adds values from a source tensor into a destination tensor using a gather-accumulate-scatter pattern. |
| Scatter-Add Dedup Kernel | The kernel scatter-adds values for any indices into a new tensor: per 128-index tile a TensorE equality-matrix matmul sums the rows that share an index, and one DMA read-modify-write adds the tile into one or two accumulation buffers, as a cost model picks. Small tables accumulate with one-hot matmuls on TensorE instead, and few tiles over a large table accumulate in the output itself. With unique_indices=True (distinct indices within every tile) it skips the deduplication. Its index and source loads use static DMA descriptors, so the speed of a standalone call, where index and src are NEFF inputs, depends on NEURON_RT_IO_RING_CACHE_SIZE (the design spec measures with 64; the runtime default is 1). |
| NeuroTile | Tile-iterator library that abstracts HBM/SBUF/PSUM tiling, sharding, and access-pattern construction for kernel authors; tutorials and example kernels live under src/nkilib_src/nkilib/experimental/neurotile/examples/. |
| MSDeformableAttention Kernel | Multi-scale deformable attention: routes each call on trn2 and trn3 to the kernel measured fastest for it (the quad, indirect or, on trn3, SBUF-gather kernel). |
| MSDeformableAttention Indirect Kernel | The kernel implements multi-scale deformable attention with an indirect DMA transpose strategy. |
| MSDeformableAttentionBwd Kernel | The kernel implements multi-scale deformable attention backward with an indirect DMA transpose and combined bilinear corner scatter-add strategy. |
| MSDeformableAttention Quad Kernel | The kernel implements multi-scale deformable attention forward through a quad scratch: one gathered row per bilinear sample, blended in a multiply and a reduction per level. |
| MSDeformableAttention SBUF Gather Kernel | The kernel implements multi-scale deformable attention forward on trn3 with every level of a batch in SBUF, its bilinear corners gathered by tensor indirection. |
| GpSIMD Top-K Kernel | The kernel computes top-k over the last dimension using the GpSIMD nisa.topk instruction (bfloat16, gen3+). |
| Max Pooling 3D | The kernel implements max pooling 3D using tensor_reduce on the Vector Engine. |
| Average Pooling 3D | The kernel implements 3D average pooling using tensor_reduce on the Vector Engine. |
| Max Pooling 3D Backward | The kernel implements 3D max pooling backward by using the input and output of max pooling 3D with a contribution mask strategy. |
| Average Pooling 3D Backward | The kernel implements 3D average pooling backward using a separable spread of the gradient. |
| Chunked Top-K Kernel | The kernel computes top-k with GLOBAL indices over vocabularies wider than a single nisa.topk call by chunking the row and reducing the per-chunk candidates. |
| GPT-OSS Sampling Tail Megakernel | The kernel implements the GPT-OSS decode sampling tail (final RMSNorm, lm_head GEMM, one all-to-all exchange, chunked top-k, and top-k/top-p sampler) in a single NEFF. |
| MXFP8 Attention TKG Kernel | The kernel implements MXFP8 flash decode attention for token generation. |
| Sparse Attention Indexer Kernel | The kernel implements the DeepSeek sparse attention indexer: MX-quantized Q/K/W projections, a BF16 score matmul, and hardware top-K selection of the most relevant KV positions per query. |
| DeepSeek V3.2 MX MLP Kernel | The kernel implements the DeepSeek V3.2 MLP for shared-experts and first dense layers with MX-prequantized packed block-scale input, auto-selecting hoisted or tiled weights with token or intermediate LNC sharding. |
The Neuron compiler includes a bundled version of this package within neuronx-cc, accessible under the nkilib Python namespace (for example, import nkilib). This bundled version is referred to as "bundled nkilib" throughout this guide. Bundled nkilib has been validated to work with that particular compiler version and can be used out of the box.
If you want to contribute a kernel change or use the latest kernels, you can integrate with this package directly.
Note: Unlike bundled nkilib, kernels from this package are not guaranteed to be compatible with the latest release of the Neuron compiler. To start from a known good commit compatible with your compiler version, find the branch corresponding to your compiler version in this repository.
- Install
neuronx-ccas usual (most likely already done). For more information, see the Neuron Quick Start Guide. - Install this package into the same virtual environment as the rest of your project:
pip install nki-library
- Import and use kernels as usual. This package automatically replaces bundled nkilib kernels with the content of this package. No code changes are required.
To uninstall, run the following command:
pip uninstall nki-libraryAfter uninstalling, the compiler falls back to the bundled nkilib.
To temporarily revert to the bundled version of nkilib, set the NKILIB_FORCE_BUNDLED_LIBRARY environment variable to a truthy value:
export NKILIB_FORCE_BUNDLED_LIBRARY=trueOn the next execution of neuronx-cc, it will use the bundled version of nkilib. To go back to the kernels from this package, unset NKILIB_FORCE_BUNDLED_LIBRARY
unset NKILIB_FORCE_BUNDLED_LIBRARY