.. meta::
    :description: Documentation for the nki.simulate API in the Neuron SDK
    :keywords: nki, simulate, nki.simulate, nki.multi_rank_simulate, test, kernels, aws neuron sdk
    :date-modified: 10/12/2026

.. _nki-simulator:

NKI CPU Simulator
=================

.. warning::

   The simulator APIs are experimental and may change in future releases.

Run and debug NKI kernels on the CPU without Trainium hardware or a compilation
step. The simulator executes kernel code as Python and uses NumPy to model
supported NKI operations.

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

Overview
--------

Use the simulator to check kernel outputs and inspect intermediate values before
running on Trainium. Simulation does not predict performance or guarantee
hardware correctness; see :ref:`simulation-limitations`.

Choose how to run your kernel:

.. list-table::
   :header-rows: 1
   :widths: 45 55

   * - Use case
     - How to run
   * - Simulate kernel calls in an existing PyTorch program
     - Set ``NKI_SIMULATOR=1``.
   * - Simulate a specific kernel call
     - Use :func:`nki.simulate`.
   * - Simulate multiple ranks in one Python process
     - Use :func:`nki.multi_rank_simulate` with per-rank NumPy inputs.

.. note::

   When ``torch.distributed`` is initialized, calls through ``NKI_SIMULATOR=1``
   or :func:`nki.simulate` use its process group for collective communication.
   Each process supplies only its own rank's inputs. See
   :ref:`nki-simulator-collectives`.

Quick Start
-----------

With NKI installed (see :doc:`../get-started/setup-env`), run this addition
kernel on CPU arrays:

.. nki_example:: /nki/examples/simulate/nki_simulate_example.py
   :language: python
   :marker: NKI_EXAMPLE_SIMULATE

.. nki_example:: /nki/examples/simulate/nki_simulate_example.py
   :language: python
   :marker: NKI_EXAMPLE_SIMULATE_RUN

Set ``NEURON_LOGICAL_NC_CONFIG=1`` before starting Python to select one
physical NeuronCore per rank (LNC degree 1) for the examples on this page.
Download :download:`nki_simulate_example.py
</nki/examples/simulate/nki_simulate_example.py>` and run it:

.. code-block:: bash

   NEURON_LOGICAL_NC_CONFIG=1 python nki_simulate_example.py

The script exits successfully after verifying the element-wise sum.


Usage
-----

Running the Simulator
^^^^^^^^^^^^^^^^^^^^^

**NKI_SIMULATOR=1 — Simulate calls in a PyTorch script**

Set this environment variable to route ``@nki.jit`` kernel calls through the
simulator without changing the call sites:

.. code-block:: bash

   NKI_SIMULATOR=1 python my_script.py

The rest of the script still runs normally, so its framework and environment
requirements continue to apply.

.. note::

   ``NKI_SIMULATOR=1`` does not currently support JAX. For JAX workflows, use the
   ``nki.simulate()`` explicit API instead.

**nki.simulate() — Simulate a specific call**

Use the explicit API to run a kernel on the simulator. This is also useful when you want
to run a kernel on *both* the simulator and hardware in the same script — for example,
to compare results:


.. code-block:: python

   # Run on simulator with NumPy
   sim_result_np = nki.simulate(my_kernel)(a_np, b_np)

   # Run on simulator with PyTorch
   sim_result = nki.simulate(my_kernel)(a_torch, b_torch)

   # Run on hardware (requires Trainium and neuronx-cc)
   hw_result = my_kernel(a_torch, b_torch)

   # Compare
   torch.testing.assert_close(sim_result, hw_result, rtol=1e-2, atol=1e-5)


For multi-rank kernels, see :ref:`nki-simulator-collectives`.


Target Platform
^^^^^^^^^^^^^^^

The simulator models different NeuronCore generations. Set the target using the
``NEURON_PLATFORM_TARGET_OVERRIDE`` environment variable:

.. list-table::
   :header-rows: 1
   :widths: 40 60

   * - Environment variable value
     - Hardware
   * - ``trn1`` or ``gen2``
     - Trn1 (NeuronCore-v2)
   * - ``trn2`` or ``gen3``
     - Trn2 (NeuronCore-v3)
   * - ``trn3`` or ``gen4``
     - Trn3 (NeuronCore-v4)
   * - *(unset)*
     - Auto-detect (uses the Neuron chip detected on the running machine, otherwise defaults to ``trn3``)

Precise Floating-Point Mode
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

By default, the simulator uses **precise floating-point mode** (``NKI_PRECISE_FP=1``). In this mode,
low-precision dtypes (``bfloat16``, ``float8_e4m3``, ``float8_e5m2``) are stored using ``ml_dtypes``
(``bfloat16``, ``float8``, etc.), producing numerical behavior similar to hardware.


**Disabling precise mode (high-precision mode):**

You can disable precise mode by setting ``NKI_PRECISE_FP=0``:

.. code-block:: bash

   NKI_PRECISE_FP=0 python my_script.py

When disabled, ``bfloat16``, ``float8_e4m3``, ``float8_e4m3fn``, and
``float8_e5m2`` tensor storage uses ``float32`` instead of the low-precision
dtype. This can help isolate accuracy loss from rounding to those formats.
It does not make every operation full-FP32: ``float16`` remains ``float16``,
and packed formats retain their packed representation.

1. Run your kernel with ``NKI_PRECISE_FP=0``.
2. Compare the output with your reference result.
3. Repeat with ``NKI_PRECISE_FP=1`` to assess the effect of low-precision storage.

Debugging
^^^^^^^^^

Because the simulator runs kernels as regular Python, you have full access to Python's
debugging ecosystem.

**Using breakpoint():**

.. code-block:: python

   import nki.isa as nisa

   @nki.jit
   def my_kernel(a_ptr):
       tile = nl.ndarray(a_ptr.shape, dtype=a_ptr.dtype, buffer=nl.sbuf)
       nisa.dma_copy(dst=tile, src=a_ptr)
       breakpoint()  # Debugger stops here — inspect `tile`
       result = nl.add(tile, tile)
       out = nl.ndarray(a_ptr.shape, dtype=a_ptr.dtype, buffer=nl.shared_hbm)
       nisa.dma_copy(dst=out, src=result)
       return out

   data = np.ones((128, 512), dtype=np.float32)
   result = nki.simulate(my_kernel)(data)

**Using device_print:**

``nl.device_print`` works in the simulator and prints tensor values to stdout:

.. code-block:: python

   @nki.jit
   def my_kernel(a_ptr):
       tile = nl.load(a_ptr)
       nl.device_print("my tile", tile)
       ...

**Using Python print:**

Since the simulator executes kernels as standard Python, you can use ``print()`` to inspect any
intermediate tensor or register object during execution. This is especially useful for both interactive
debugging and AI-assisted development workflows where agents iterate on kernels locally.

**IDE Debugging (VSCode / PyCharm):**

Set breakpoints in your kernel code and run your script normally. The simulator executes
kernel code in-process, so IDE debuggers work without any special configuration.


.. _nki-simulator-collectives:

Simulating Collectives
----------------------

The simulator runs :ref:`nki.collectives <nki-collectives>`
operations across multiple ranks on the CPU. It supports LNC degrees of 1 and 2.
A rank is a logical participant in a collective; the LNC degree is
the number of physical NeuronCores within each rank, not the world size.

For operations that take a ``ReplicaGroup``, each rank list executes independently.
The caller must belong to one of those rank lists; otherwise, the simulator raises
an error.

The simulator models the semantics of collective communication APIs, but not
the underlying communication algorithms, hardware topology, latency, bandwidth,
or communication and compute overlap.

Running a Collective Kernel
^^^^^^^^^^^^^^^^^^^^^^^^^^^

Use :func:`nki.multi_rank_simulate` to run one copy of a kernel per rank in a
single Python process. Pass the number of ranks and each rank's arguments in
one call.

This kernel all-reduces its input across ranks, so every rank returns the sum of
all ranks' inputs:

.. nki_example:: /nki/examples/multi_rank/all_reduce.py
   :language: python
   :marker: NKI_EXAMPLE_MULTI_RANK_ALL_REDUCE

Each rank's input is filled with its rank ID, and the caller checks every rank's
result:

.. nki_example:: /nki/examples/multi_rank/all_reduce.py
   :language: python
   :marker: NKI_EXAMPLE_MULTI_RANK_SIMULATE

Download :download:`all_reduce.py </nki/examples/multi_rank/all_reduce.py>` and
run it:

.. code-block:: bash

   NEURON_LOGICAL_NC_CONFIG=1 python all_reduce.py

The script runs as an ordinary Python program: it simulates two ranks in one
process and exits successfully after checking their results. To run the same
kernel on Trainium, call :func:`nki.multi_rank_execute` with the same arguments.

Per-Rank Arguments and Results
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Pass ``world_size`` and ``per_rank_inputs`` by keyword. ``per_rank_inputs``
gives each rank an ``(args, kwargs)`` pair, where ``args`` is a tuple and
``kwargs`` is a dict. It is either 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. In this example, a function builds
each rank's pair:

.. code-block:: python

   import nki.collectives as nccl

   replica_group = nccl.ReplicaGroup([[0, 1]])

   def rank_inputs(rank):
       return (inputs[rank],), {"replica_group": replica_group}

   results = nki.multi_rank_simulate(
       all_reduce_kernel,
       world_size=2,
       per_rank_inputs=[rank_inputs(rank) for rank in range(2)],
       # or: per_rank_inputs={rank: rank_inputs(rank) for rank in range(2)},
   )

Every rank runs the same kernel specialization, so each rank must pass
arguments for the same parameters. Tensor arguments are dynamic: they are NumPy
arrays (``numpy.ndarray``) whose contents can differ across ranks, but they must
have the same shape and dtype on every rank. All other arguments, such as
``replica_group`` here, are static and must be equal on every rank. For a kernel
without parameters, pass ``((), {})`` for each rank.

For Torch or other framework tensors, use ``nki.simulate`` in each rank
process.

The call returns a list containing each rank's kernel return value, in rank
order.

With ``NKI_SIMULATOR=1``, an ordinary ``kernel(...)`` call simulates the
calling process's rank. To simulate several ranks in one process, use
``nki.multi_rank_simulate``.

Using an Existing Distributed Process Group
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For a program already launched with ``torchrun``, initialize a
``torch.distributed`` process group before calling ``nki.simulate``. The
simulator uses that group to exchange data between rank processes. Pass the
current rank's arguments as in an ordinary call. Without an initialized group,
``nki.simulate`` runs as a single rank.

For example, save this as ``simulate_distributed.py`` beside the downloaded
example:

.. code-block:: python

   import nki
   import nki.collectives as nccl
   import numpy as np
   import torch.distributed as dist
   from all_reduce import all_reduce_kernel

   dist.init_process_group(backend="gloo")
   rank = dist.get_rank()
   world_size = dist.get_world_size()
   replica_group = nccl.ReplicaGroup([list(range(world_size))])
   x = np.full((128, 512), rank, dtype=np.float32)
   out = nki.simulate(all_reduce_kernel)(x, replica_group)
   np.testing.assert_allclose(out, sum(range(world_size)))
   dist.destroy_process_group()

Run it with two CPU ranks:

.. code-block:: bash

   NEURON_LOGICAL_NC_CONFIG=1 torchrun --nproc-per-node 2 simulate_distributed.py

Shared HBM at LNC Degree 1
^^^^^^^^^^^^^^^^^^^^^^^^^^

At LNC degree 1, the two ranks that share an HBM stack each keep a separate
copy of each ``shared_hbm`` tensor. Writes become visible to the sibling rank
at ``nki.isa.core_barrier`` on that tensor and when a collective writes a
``shared_hbm`` destination. If both ranks write different values to
the same element between synchronization points, the simulator raises an error.
For hardware execution, set ``NKI_LNC1_SHARED_HBM=1`` to enable shared HBM
for LNC degree 1 kernels.

Before synchronization, each rank reads only its own copy. The simulator does
not detect a kernel that reads a sibling's write without synchronizing first.
Such a kernel can give the same result on every simulator run but different
results on hardware.


How It Works
------------

Execution
^^^^^^^^^

When you call ``nki.simulate(kernel)(a, b)``:

1. Each NumPy array argument is wrapped into a ``NkiTensor`` with ``buffer=nl.hbm``
   (or ``shared_hbm`` for LNC2). Non-array arguments pass through unchanged.
2. The simulator backend is activated, routing all ``nki.isa`` and ``nki.language``
   operations to NumPy-based implementations.
3. The kernel function runs as regular Python — each NKI API call executes eagerly
   and sequentially. There is no instruction scheduling or engine parallelism.
4. On return, ``NkiTensor`` results are converted back to NumPy arrays. Input arrays are
   updated in-place if the kernel modified the corresponding HBM tensors.

For **LNC2 kernels** (configured with ``NEURON_LOGICAL_NC_CONFIG=2``), the
simulator spawns two Python threads that execute the kernel concurrently, each
with its own ``program_id``. Input arrays use ``shared_hbm`` buffers, so both
threads can access shared memory. ``nki.lnc.sendrecv`` and
``nki.lnc.core_barrier`` use thread-safe synchronization primitives (see
:ref:`nki-about-lnc`).

Uninitialized Memory Detection
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

New simulator storage is initialized with sentinel values: ``NaN`` for
floating-point storage and ``4`` for integer storage. These values can help
expose reads from memory that the kernel has not written.

Many arithmetic operations propagate ``NaN``, so an uninitialized read can
appear as a ``NaN`` in the output. For a kernel whose valid outputs should all
be finite, this check can help identify the problem:

.. code-block:: python

   result = nki.simulate(my_kernel)(inputs)
   assert not np.any(np.isnan(result)), "Unexpected NaN; check for uninitialized reads"

This is a debugging aid, not a complete uninitialized-read detector. Operations
such as comparisons can hide ``NaN`` values, and integer tensors use a finite
sentinel. An output without ``NaN`` does not prove that every read was initialized;
a ``NaN`` can also have other causes, such as invalid arithmetic.

.. tip::

   If you see unexpected ``NaN`` values in your simulation output, check that all tensors are properly
   initialized before use. Common causes include:

   - Allocating a tensor with ``nl.ndarray`` but not writing to all elements before reading
   - Off-by-one errors in tile loop bounds that leave some elements unwritten
   - Conditional writes that skip certain partitions or indices


Hardware Constraint Validation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

NKI operations check hardware constraints such as shape limits, dtype
compatibility, buffer types, engine restrictions, and architecture requirements.
A violated constraint raises a Python exception; validation coverage is incomplete.

``nl.while_loop`` checks the body's returned condition after each executed
iteration. If the initial condition is zero, the simulator does not call the
body or check its return type. The compiler checks the body during tracing,
even for a zero-iteration loop, so it can reject a body that simulation never
executes.

.. warning::

   Hardware constraint validation is actively being developed. Some constraints may not yet
   be checked by the simulator. If your kernel passes simulation but fails on hardware,
   report it to the Neuron team as an issue.


**Example:**

.. code-block:: python

   import nki.isa as nisa

   @nki.jit
   def bad_kernel():
       tile = nl.ndarray((256, 512), dtype=nl.float32, buffer=nl.sbuf)
       nisa.tensor_tensor(dst=tile, data1=tile, data2=tile, op=nl.add)

   nki.simulate(bad_kernel)()
   # AssertionError: tensor_tensor data1 partition dimension 256 exceeds maximum 128



.. _simulation-limitations:

Simulation Limitations
----------------------

The simulator approximates hardware behavior but is not identical. Understanding these
limitations helps you write kernels that work on both the simulator and real Trainium hardware.

NKI Meta-Programming Support
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The simulator executes kernel code directly as Python — there is no compilation step. As a result,
the simulator accepts any valid Python in the kernel body, including arbitrary classes, closures,
and dynamic control flow. The NKI compiler, however, only supports a restricted subset of Python
for meta-programming, see :ref:`NKI Language Guide<nki-language-guide>`. Kernels that use
unsupported Python constructs will execute successfully on the simulator but fail to compile for hardware.

Numerical Precision
^^^^^^^^^^^^^^^^^^^

The simulator uses precise floating-point mode by default (``NKI_PRECISE_FP=1``), storing
low-precision types using ``ml_dtypes`` for numerical behavior close to hardware. However,
simulation results may still differ slightly from hardware due to differences in how the
simulator computes operations versus the hardware engines, as well as
floating-point non-associativity (different accumulation ordering can produce different
rounding results).
See `Precise Floating-Point Mode`_ for details on how to use ``NKI_PRECISE_FP=0`` to isolate
precision effects from algorithmic correctness.

Performance
^^^^^^^^^^^

The simulator runs on the CPU using Python and NumPy. It does not model instruction latency,
engine parallelism, or hardware scheduling. Since kernels are interpreted rather than compiled
and optimized for Trainium NeuronCores, the simulator is significantly slower than hardware
execution and is not suitable for performance benchmarking.

Memory Model
^^^^^^^^^^^^

The simulator allocates each tensor independently without simulating overlapping memory regions
or validating against SBUF/PSUM capacity limits. Kernels with memory conflicts may run
successfully on the simulator but fail or produce incorrect results on real hardware, where
SBUF and PSUM are shared physical memory with capacity constraints.

Known Gaps
^^^^^^^^^^

- Some hardware constraint checks are missing — see `Hardware Constraint Validation`_ for details.
- Simulation runs ahead of runtime support for variable-sized collectives
  (:func:`~nki.collectives.all_to_all_v`, :func:`~nki.collectives.all_gather_v` and their
  prepare/trigger forms) with ``shared_hbm`` operands at LNC degree 1: the simulator runs them,
  but the Trainium runtime does not yet accept them.
