This document is relevant for: Trn2, Trn3

NKI Standalone#

A NKI kernel is usually invoked inside a model. A PyTorch or JAX program invokes the kernel with framework tensors. The framework records the invocation as a custom operator in the model’s HLO graph. The Neuron Compiler then compiles the kernel and the model together into one executable (see NKI Kernel as a Framework Custom Operator). The framework controls the inputs, the invocation, and the device.

NKI Standalone execution removes the framework. An ordinary Python program invokes a @nki.jit kernel with NumPy arrays. NKI specializes the kernel and compiles it into its own NEFF (Neuron Executable File Format). NKI then executes the NEFF directly on NeuronDevices and returns NumPy results. There is no model and no HLO graph. Your program supplies the inputs and controls the invocation.

The kernel itself does not change. Standalone execution only changes how you invoke a kernel. You can develop and test a kernel on its own, then insert the same kernel into a model without changes.

Understanding the Standalone Execution Pipeline#

A standalone invocation moves through three stages. NKI specializes the kernel, compiles the kernel into a NEFF, and executes the NEFF on one or more NeuronCores.

The standalone pipeline. NumPy arguments enter the specialize stage, which traces the kernel. The compile stage lowers NKI IR to a NEFF. The NEFF executes on one or more NeuronCores and the invocation returns NumPy arrays.

Specialize. NKI traces the kernel with Python, using the arguments you passed (see NKI Language Guide). The trace resolves every value that is known during specialization. The shapes and dtypes of the arrays become fixed. The values of the non-tensor arguments become constants. What remains is a kernel specialized to this one invocation, where only the tensor data is unknown until run time.

Compile. The NKI Compiler optimizes the specialized kernel, and the Neuron Compiler back end produces a NEFF. In a framework, the NEFF contains the whole model, and the kernel is one operator inside it. In standalone execution, the NEFF contains only your kernel.

Execute. NKI loads the NEFF onto one or more NeuronCores. It copies the NumPy inputs into device memory, executes the kernel, and copies the outputs back to host memory. The invocation returns the kernel’s return value as NumPy arrays.

NKI APIs for Standalone Execution#

NKI provides two APIs for executing in standalone mode.

Standalone APIs

Behavior

When to Use

nki.execute()

Executes a NKI kernel on hardware using NumPy arrays.

Use when testing a kernel in isolation without collective communication.

nki.multi_rank_execute()

Executes a NKI kernel on hardware across multiple NeuronCores using NumPy arrays.

Use when testing a kernel in isolation with collective communication.

nki.execute#

nki.execute(kernel, *args, **kwargs) invokes a kernel with NumPy arguments, the way a direct call does. nki.execute(matmul_kernel, X, y) and matmul_kernel(X, y) pass the same arguments to the kernel. The call returns the kernel’s return value.

Parameter Constraints#

kernel

A nki.jit() kernel, or a plain Python function.

args / kwargs

The kernel’s own arguments. Tensor arguments are NumPy arrays (numpy.ndarray). Every other argument becomes a constant of the specialized kernel.

nki.multi_rank_execute#

nki.multi_rank_execute(kernel, world_size=N, per_rank_inputs=...) invokes one kernel on N ranks. It returns a list with one entry per rank, where entry r is rank r’s return value.

The call compiles once. NKI specializes the kernel from rank 0’s arguments, compiles one NEFF, and loads that same NEFF onto every rank’s NeuronCore. One NEFF means one specialization, which restricts how the per-rank arguments can differ.

Parameter Constraints#

kernel

A nki.jit() kernel, or a plain Python function.

world_size

The number of ranks. Must be a Python int of one or greater.

per_rank_inputs

One (args, kwargs) pair per rank, where args is a tuple of positional arguments and kwargs is a dict of keyword arguments. Pass a sequence in rank order, or a mapping with one key for each rank from 0 to world_size - 1. Rank r runs kernel(*args, **kwargs) with its pair.

Every rank must pass arguments for the same kernel parameters. Tensor arguments can hold different data on every rank, but their shape and dtype must match on every rank. Every other argument must be equal on every rank. A mismatch raises a ValueError before compilation starts, and a malformed (args, kwargs) pair raises a TypeError.

If any rank fails at run time, the call raises nki.MultiRankExecutionError. Its rank_failures attribute maps each failing rank to the exception that rank raised.

Using NKI Standalone APIs#

The next two sections walk through two complete programs. The first runs a kernel on one NeuronCore with nki.execute(). The second runs a collective kernel on four NeuronCores with nki.multi_rank_execute().

Using nki.execute#

This section walks through a complete standalone program using a simple kernel that performs matrix multiplication on two tensors.

The program starts with the kernel. When it runs, its two arguments are sitting in HBM (High Bandwidth Memory), the device’s working memory. The compute engines cannot read HBM directly. They work out of SBUF (State Buffer), the on-chip memory. The kernel begins by copying both inputs there:

import nki
import nki.isa as nisa
import nki.language as nl


@nki.jit
def matmul_kernel(X: nl.NkiTensor, y: nl.NkiTensor) -> nl.NkiTensor:
    X_sbuf = nl.ndarray(shape=X.shape, dtype=X.dtype, buffer=nl.sbuf)
    y_sbuf = nl.ndarray(shape=y.shape, dtype=y.dtype, buffer=nl.sbuf)
    nisa.dma_copy(dst=X_sbuf, src=X)
    nisa.dma_copy(dst=y_sbuf, src=y)

With both inputs in SBUF, the kernel can multiply them. nl.matmul runs on the Tensor Engine and writes its result to PSUM, the Partial Sum Buffer that stores and accumulates matrix multiplication results (see The Trainium Memory Hierarchy). A tensor_copy moves the result back to SBUF:

def matmul_kernel(X: nl.NkiTensor, y: nl.NkiTensor) -> nl.NkiTensor:
    ...
    z_psum = nl.matmul(X_sbuf, y_sbuf)  # X @ y
    z_sbuf = nl.ndarray(shape=z_psum.shape, dtype=X.dtype, buffer=nl.sbuf)
    nisa.tensor_copy(dst=z_sbuf, src=z_psum)

Last, the kernel returns its result. The output lives in nl.shared_hbm, the HBM region whose contents are visible outside the kernel. The kernel allocates the output there, copies the result into it, and returns it:

def matmul_kernel(X: nl.NkiTensor, y: nl.NkiTensor) -> nl.NkiTensor:
    ...
    z = nl.ndarray(shape=z_sbuf.shape, dtype=X.dtype, buffer=nl.shared_hbm)
    nisa.dma_copy(dst=z, src=z_sbuf)
    return z

The full dataflow of the kernel:

Dataflow of matmul_kernel. X and y move from HBM into SBUF with dma_copy, nl.matmul produces z_psum in PSUM, tensor_copy moves it to SBUF, and dma_copy writes z to shared HBM, which is returned as a NumPy array.

So far, this is an ordinary NKI kernel. Nothing in it is specific to standalone execution. The standalone part is the invocation:

import numpy as np

X = np.random.rand(2, 2).astype(np.float32)
y = np.random.rand(2, 1).astype(np.float32)

z = nki.execute(matmul_kernel, X, y)

np.testing.assert_allclose(z, X @ y)

One call runs all three pipeline stages. nki.execute() traces matmul_kernel with X fixed to shape (2, 2) and y fixed to shape (2, 1), both float32. It compiles the kernel into a NEFF, executes the NEFF on one NeuronCore, and returns z as a NumPy array. The whole program is plain Python. There is no framework, no device tensor, and no session.

Note

Standalone execution does not cache compilation. Every invocation specializes and compiles the kernel again, even with the same arguments. Invoke a kernel once and reuse the returned arrays where possible.

Note

The kernel on this page favors clarity over speed. For the recommended workflow to profile and optimize a matrix multiplication kernel, see Introduction to NKI Kernel Optimization.

Using nki.multi_rank_execute#

This section walks through a multi-rank program using a kernel that passes tensors around a ring. The program runs four copies of the kernel at the same time. Each copy runs as one rank, a logical participant in the collective, numbered 0 to 3.

A multi-rank kernel still describes the work of one rank. Ranks exchange data through collective operations, and collectives work on tensors in HBM. The kernel allocates a send buffer and a receive buffer there, in the rank’s own HBM:

import nki
import nki.collectives as nccl
import nki.isa as nisa
import nki.language as nl
import numpy as np

WORLD_SIZE = 4

@nki.jit
def shuffle_kernel(
   x: nl.NkiTensor, source_target_pairs: list[tuple[int, int]]
) -> nl.NkiTensor:
   """
   Shuffles inputs to the next rank in a ring-topology order.

   Before this kernel:

      Rank 0 : [1, 2, 3]
      Rank 1 : [4, 5, 6]
      Rank 2 : [7, 8, 9]
      Rank 3 : [10, 11, 12]

   After this kernel:

      Rank 0 : [10, 11, 12]
      Rank 1 : [1, 2, 3]
      Rank 2 : [4, 5, 6]
      Rank 3 : [7, 8, 9]
   """

   send = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.hbm)
   recv = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.hbm)
   nisa.dma_copy(dst=send, src=x)

Then the ranks trade tensors. The kernel takes the ring as an argument. source_target_pairs is a list of (source, target) pairs, one per transfer. Every rank runs the same collective_permute call. For rank r, the collective sends send to r’s target and fills recv from r’s source:

def shuffle_kernel(
   x: nl.NkiTensor, source_target_pairs: list[tuple[int, int]]
) -> nl.NkiTensor:
   ...
   assert len(source_target_pairs) == WORLD_SIZE, (
      "source_target_pairs must be equal to the world size for shuffle_kernel"
   )
   nccl.collective_permute(
      srcs=[send],
      dsts=[recv],
      source_target_pairs=source_target_pairs,
   )

Note

This page uses collective_permute because its source_target_pairs argument shows how a non-tensor argument reaches the kernel. For a production ring, prefer collective_permute_implicit, which the hardware can optimize for ring topologies.

The ring, with each rank’s tensor before and after the collective:

Four NeuronCores in a ring. Green arrows show each transfer in source_target_pairs. Each rank's box lists its tensor before and after the shuffle, with rank 0 receiving rank 3's values.

Last, the kernel copies the received tensor into nl.shared_hbm and returns it:

def shuffle_kernel(
   x: nl.NkiTensor, source_target_pairs: list[tuple[int, int]]
) -> nl.NkiTensor:
   ...
   out = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.shared_hbm)
   nisa.dma_copy(dst=out, src=recv)
   return out

Now the invocation. Four ranks need four inputs. nki.multi_rank_execute() takes one (args, kwargs) pair per rank, in rank order:

inputs = [
   np.array([1, 2, 3], dtype=np.float32),     # rank 0
   np.array([4, 5, 6], dtype=np.float32),     # rank 1
   np.array([7, 8, 9], dtype=np.float32),     # rank 2
   np.array([10, 11, 12], dtype=np.float32),  # rank 3
]

ring = [(0, 1), (1, 2), (2, 3), (3, 0)]

results = nki.multi_rank_execute(
   shuffle_kernel,
   world_size=WORLD_SIZE,
   per_rank_inputs=[
      ((inputs[0],), {"source_target_pairs": ring}),
      ((inputs[1],), {"source_target_pairs": ring}),
      ((inputs[2],), {"source_target_pairs": ring}),
      ((inputs[3],), {"source_target_pairs": ring}),
   ],
)

# Each rank receives the previous rank's tensor.
np.testing.assert_allclose(results[0], inputs[3])
np.testing.assert_allclose(results[1], inputs[0])
np.testing.assert_allclose(results[2], inputs[1])
np.testing.assert_allclose(results[3], inputs[2])

The tensor argument x differs on every rank, in data only. source_target_pairs is a non-tensor argument. Every rank passes the same ring. NKI compiles the kernel once and executes the same NEFF on four NeuronCores. Rank r runs with per_rank_inputs[r], and its return value is stored in results[r].

Note

A standalone invocation compiles into a temporary directory and deletes it when the invocation finishes. To keep the NEFF and the other compilation artifacts, set the NKI_ARTIFACTS_DIR environment variable to an empty directory. Use a new empty directory for each invocation. Compilation fails on a directory that already holds artifacts.

See Also#

This document is relevant for: Trn2, Trn3