This document is relevant for: Trn2, Trn3
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.
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 Simulation Limitations.
Choose how to run your kernel:
Use case |
How to run |
|---|---|
Simulate kernel calls in an existing PyTorch program |
Set |
Simulate a specific kernel call |
Use |
Simulate multiple ranks in one Python process |
Use |
Note
When torch.distributed is initialized, calls through NKI_SIMULATOR=1
or nki.simulate() use its process group for collective communication.
Each process supplies only its own rank’s inputs. See
Simulating Collectives.
Quick Start#
With NKI installed (see How to set up your environment for NKI development), run this addition kernel on CPU arrays:
import nki
import nki.language as nl
import numpy as np
@nki.jit
def add_kernel(a_ptr, b_ptr):
# Load tiles from HBM into SBUF
a = nl.load(a_ptr)
b = nl.load(b_ptr)
# Element-wise add
result = nl.add(a, b)
# Store result back to HBM
out = nl.ndarray(a_ptr.shape, dtype=a_ptr.dtype, buffer=nl.shared_hbm)
nl.store(out, value=result)
return out
# Create example inputs
a = np.random.rand(128, 512).astype(np.float32)
b = np.random.rand(128, 512).astype(np.float32)
# Run on the CPU simulator
result = nki.simulate(add_kernel)(a, b)
# Verify correctness
np.testing.assert_allclose(result, a + b, rtol=1e-5)
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 nki_simulate_example.py and run it:
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:
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:
# 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 Simulating Collectives.
Target Platform#
The simulator models different NeuronCore generations. Set the target using the
NEURON_PLATFORM_TARGET_OVERRIDE environment variable:
Environment variable value |
Hardware |
|---|---|
|
Trn1 (NeuronCore-v2) |
|
Trn2 (NeuronCore-v3) |
|
Trn3 (NeuronCore-v4) |
(unset) |
Auto-detect (uses the Neuron chip detected on the running machine, otherwise defaults to |
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:
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.
Run your kernel with
NKI_PRECISE_FP=0.Compare the output with your reference result.
Repeat with
NKI_PRECISE_FP=1to 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():
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:
@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.
Simulating Collectives#
The simulator runs 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 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:
import nki
import nki.collectives as nccl
import nki.isa as nisa
import nki.language as nl
import numpy as np
@nki.jit
def all_reduce_kernel(x, replica_group):
src = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.private_hbm)
out = nl.ndarray(x.shape, dtype=x.dtype, buffer=nl.shared_hbm)
nisa.dma_copy(dst=src, src=x)
nccl.all_reduce(srcs=[src], dsts=[out], replica_group=replica_group, op=nl.add)
return out
Each rank’s input is filled with its rank ID, and the caller checks every rank’s result:
# Rank r's input is filled with r.
inputs = [np.full((128, 512), rank, dtype=np.float32) for rank in range(2)]
replica_group = nccl.ReplicaGroup([[0, 1]])
results = nki.multi_rank_simulate(
all_reduce_kernel,
world_size=2,
per_rank_inputs=[((x,), {"replica_group": replica_group}) for x in inputs],
)
# Every rank returns the sum of all ranks' inputs.
for out in results:
np.testing.assert_allclose(out, inputs[0] + inputs[1])
Download all_reduce.py and
run it:
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 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:
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:
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:
NEURON_LOGICAL_NC_CONFIG=1 torchrun --nproc-per-node 2 simulate_distributed.py
How It Works#
Execution#
When you call nki.simulate(kernel)(a, b):
Each NumPy array argument is wrapped into a
NkiTensorwithbuffer=nl.hbm(orshared_hbmfor LNC2). Non-array arguments pass through unchanged.The simulator backend is activated, routing all
nki.isaandnki.languageoperations to NumPy-based implementations.The kernel function runs as regular Python — each NKI API call executes eagerly and sequentially. There is no instruction scheduling or engine parallelism.
On return,
NkiTensorresults 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
Using Logical NeuronCores (LNC) with NKI).
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:
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.ndarraybut not writing to all elements before readingOff-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:
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#
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 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 (
all_to_all_v(),all_gather_v()and their prepare/trigger forms) withshared_hbmoperands at LNC degree 1: the simulator runs them, but the Trainium runtime does not yet accept them.
This document is relevant for: Trn2, Trn3