.. meta::
   :description: Run NKI kernels standalone from plain Python with nki.execute and nki.multi_rank_execute.
   :keywords: NKI, standalone, nki.execute, nki.multi_rank_execute, nki.simulate, nki.multi_rank_simulate, collectives, NeuronCore
   :date-modified: 11/13/2026


.. _nki-standalone:


==============
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
:ref:`nki_framework_custom_op`). 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.

.. contents:: On this page
   :local:
   :depth: 2


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.

.. image:: /nki/img/deep-dives/standalone/execute-pipeline.png
   :alt: 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 :ref:`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.

.. list-table::
   :header-rows: 1
   :widths: 10 20 15

   * - Standalone APIs
     - Behavior
     - When to Use
   * - :func:`nki.execute`
     - Executes a NKI kernel on hardware using NumPy arrays.
     - Use when testing a kernel in isolation without collective communication.
   * - :func:`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 :func:`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 :func:`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 :func:`nki.execute`. The second runs a
collective kernel on four NeuronCores with :func:`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:

.. code-block:: python

   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.
:func:`nl.matmul <nki.language.matmul>` runs on the Tensor Engine and writes
its result to PSUM, the Partial Sum Buffer that stores and accumulates matrix
multiplication results (see
:doc:`/nki/get-started/about/memory-hierarchy-overview`). A ``tensor_copy``
moves the result back to SBUF:

.. code-block:: python

   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:

.. code-block:: python

   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:

.. image:: /nki/img/deep-dives/standalone/matmul-dataflow.png
   :alt: 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:

.. code-block:: python

   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. :func:`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
   :ref:`nki-kernel-optimization-guide`.


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:

.. code-block:: python

   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
:func:`collective_permute <nki.collectives.collective_permute>` call. For
rank ``r``, the collective sends ``send`` to r's target and fills ``recv``
from r's source:

.. code-block:: python

   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
   :func:`collective_permute <nki.collectives.collective_permute>` because
   its ``source_target_pairs`` argument shows how a non-tensor argument
   reaches the kernel. For a production ring, prefer
   :func:`collective_permute_implicit <nki.collectives.collective_permute_implicit>`,
   which the hardware can optimize for ring topologies.

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

.. image:: /nki/img/deep-dives/standalone/shuffle-ring.png
   :alt: 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:

.. code-block:: python

   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.
:func:`nki.multi_rank_execute` takes one ``(args, kwargs)`` pair per rank,
in rank order:

.. code-block:: python

   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
--------

- :doc:`/nki/api/nki.collectives` - the collective operations available to
  multi-rank kernels.
- :ref:`nki-simulator` - run kernels on CPU with ``nki.simulate`` and
  ``nki.multi_rank_simulate``, without Trainium hardware.
- :ref:`nki-compile-config` - per-kernel compile options.
- :ref:`nki_framework_custom_op` - insert a kernel into a PyTorch or JAX
  model.
