This document is relevant for: Trn2, Trn3

nki.multi_rank_simulate#

nki.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][source]#

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

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:

# 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])
Parameters:
  • 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.

This document is relevant for: Trn2, Trn3