# AUTO GENERATED FILE - DO NOT MANUALLY MODIFY.
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from typing import *
if TYPE_CHECKING:
from nki.framework import Kernel
class MultiRankExecutionError(Exception):
r"""Raised when one or more ranks fail during multi-rank execution.
``rank_failures`` maps each failing rank id to the exception it raised."""
rank_failures: dict[int, Exception]
r"""The exception raised by each failing rank, keyed by rank id."""
def __init__(self, rank_failures: dict[int, Exception]):
...
...
[docs]def execute(kernel: Kernel | Callable, *args: Any, **kwargs: Any) -> Any:
r"""Specializes a kernel into a NEFF (Neuron Executable File Format) and executes it
on hardware. ``kernel`` may be a :func:`nki.jit` kernel or a plain Python function.
**Example**
.. code-block:: python
import nki
import nki.isa as nisa
import nki.language as nl
import numpy as np
@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)
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(z_sbuf, z_psum)
z = nl.ndarray(shape=z_sbuf.shape, dtype=X.dtype, buffer=nl.shared_hbm)
nisa.dma_copy(dst=z, src=z_sbuf)
return z
X = np.random.rand(2, 2).astype(np.float32)
y = np.random.rand(2, 1).astype(np.float32)
# Specialization and execution.
results = nki.execute(matmul_kernel, X, y)
:param kernel: The kernel to execute, either a :func:`nki.jit` kernel or a plain
Python function.
:param args: Positional arguments to pass to ``kernel``.
:param kwargs: Keyword arguments to pass to ``kernel``.
:return: The kernel's return value."""
...
[docs]def multi_rank_execute(kernel: Kernel | Callable, *, world_size: int, per_rank_inputs: Mapping[int, tuple[tuple[Any, ...], dict[str, Any]]] | Sequence[tuple[tuple[Any, ...], dict[str, Any]]]) -> list[Any]:
r"""Specializes a kernel into a NEFF (Neuron Executable File Format) and executes it
on hardware across multiple ranks. ``kernel`` may be a :func:`nki.jit` kernel or
a plain Python function.
``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.
Every rank runs the same NEFF, 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 are static and must
be equal on every rank.
**Example**
.. code-block:: python
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
Run it on two ranks:
.. code-block:: python
# 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_execute(
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])
:param kernel: The kernel to execute, either a :func:`nki.jit` kernel or a plain
Python function.
:param world_size: Number of ranks to execute on.
:param per_rank_inputs: Each rank's ``(args, kwargs)`` pair, as a sequence in
rank order or a mapping keyed by rank.
:return: A list with one entry per rank, where entry ``i`` is rank ``i``'s return
value."""
...
[docs]def jit(fn=None, *, compile_config=None, specialization_config=None, **kwargs):
r"""Just-in-time compile a top-level NKI function to run on NeuronDevices.
The returned callable detects the current framework and compiles the function as a
custom operator. It detects the current framework by inspecting its arguments:
- ``torch.Tensor``: uses PyTorch integration.
- ``jax.Array``: uses JAX integration.
- ``np.ndarray``: compiles and executes standalone kernel, without a framework.
You might need to explicitly set the target platform using the
``NEURON_PLATFORM_TARGET_OVERRIDE`` environment variable. Supported values:
- ``trn1|inf2|gen2``
- ``trn2|gen3``
- ``trn3|gen4``
Configure the LNC (Logical NeuronCore) degree by setting the
``NEURON_LOGICAL_NC_CONFIG`` environment variable to 1 or 2 before invoking
the kernel. If the LNC degree is not explicitly set, the default is LNC=1.
Per-kernel config is passed through two typed objects:
- ``compile_config`` -- a :class:`nki.compiler.CompileConfig` of options that
impact downstream compiler behavior (``address_rotation``,
``non_ssa_legalization``, ``dead_code_elim``, ``barrier_check``,
``prefetch_auto``, ``nki_alloc_fallback``, ``dma_copy_elim``,
``element_widening``, ``tensor_copy_elim``,
``remove_unused_instructions``, ``remove_overwritten_writes``,
``split_reused_buffers``, ``experimental_allocation_mode``,
``experimental_sbuf_allocation_mode``, ``experimental_hbm_allocation_mode``,
``experimental_psum_allocation_mode``, ``sbuf_allocation_fallback``,
``engine_balancing``, ``experimental_scheduling_heuristic``,
``register_load_reuse``, ``allocation``, ``scheduling``, ``opt_level``).
Every field is keyword-only.
- ``specialization_config`` -- a :class:`nki.compiler.SpecializationConfig` of
options that tune the specialization phase (``allow_nested_config_override``).
e.g.::
from nki.compiler import CompileConfig, SpecializationConfig
@nki.jit(compile_config=CompileConfig(non_ssa_legalization=True))
def my_kernel(...): ...
``SpecializationConfig.allow_nested_config_override`` -- when this kernel is used
as the top-level compiled kernel:
* default (``False``): a nested sub-kernel whose config disagrees raises an error.
* ``True``: warn instead, and inline the sub-kernel under this kernel's config.
Useful for composing @nki.jit kernels whose config you cannot edit.
Returns a :class:`Kernel` instance wrapping the decorated function."""
...
[docs]def simulate(kernel):
r"""Create a CPU-simulated version of an NKI kernel.
.. warning::
This API is experimental and may change in future releases.
See :ref:`nki-simulator` for full documentation including target platform
selection, precise floating-point mode, debugging, and known limitations.
Example::
import os
@nki.jit
def my_kernel(a, b): ...
# Explicit simulation
result = nki.simulate(my_kernel)(a_np, b_np)
# With LNC2
os.environ["NEURON_LOGICAL_NC_CONFIG"] = "2"
result = nki.simulate(my_kernel)(a_np, b_np)
Args:
kernel: NKI kernel function, typically decorated with ``@nki.jit``.
If a plain function is passed, it is automatically wrapped.
Returns:
A callable that, when invoked with NumPy arrays or torch Tensors,
executes the kernel on CPU and returns results in the same format
(NumPy arrays or torch Tensors respectively)."""
...
[docs]def multi_rank_simulate(kernel: Kernel | Callable, *, world_size: int, per_rank_inputs: Mapping[int, tuple[tuple[Any, ...], dict[str, Any]]] | Sequence[tuple[tuple[Any, ...], dict[str, Any]]]) -> list[Any]:
r"""Run a kernel across multiple ranks in one CPU process.
.. warning::
This API is experimental and may change in future releases.
``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.
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
are static and must be equal on every rank.
**Example**
.. code-block:: python
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
Run it on two ranks:
.. code-block:: python
# 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])
Args:
kernel: NKI kernel decorated with ``@nki.jit``, or a plain Python function.
world_size: Number of ranks to simulate.
per_rank_inputs: Each rank's ``(args, kwargs)`` pair, as a sequence in rank
order or a mapping keyed by rank.
Returns:
A list containing each rank's kernel return value, in rank order."""
...