Skip to content

[FEAT] Interpret NKI ISA instructions and more nl operations in the NKI interpreter - #540

Open
mark14wu wants to merge 1 commit into
fix/nki-official-kernelsfrom
fix/nki-isa-ops
Open

mark14wu wants to merge 1 commit into
fix/nki-official-kernelsfrom
fix/nki-isa-ops

Conversation

@mark14wu

@mark14wu mark14wu commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator

Stacked on #539 (base branch fix/nki-official-kernels); retarget to main after #539 merges.

Summary

#539 lets the legacy NKI interpreter (frontend="nki") run kernels written in the style of AWS's NKI samples, but the samples' larger kernels use NKI ISA instructions (nisa.*) that the interpreter does not implement. Without them, the kernel calls NKI's real implementation and fails with RuntimeError: calling NKI API outside of NKI kernels is not supported. This PR implements them, plus the nl operations those kernels use, with NKI's semantics:

  • nisa: nc_matmul (stationary.T @ moving, fp32), nc_transpose, activation / activation_reduce (op(data * scale + bias), optional reduction into reduce_res), tensor_tensor, tensor_scalar / tensor_scalar_reduce, scalar_tensor_tensor, tensor_reduce, tensor_tensor_scan, tensor_copy, memset, affine_select, reciprocal, iota, dma_copy, dma_transpose, get_nc_version (gen2, a Trn1 NeuronCore).
  • nl: ds, num_programs, program_ndim, full, ones, shared_constant, shared_identity_matrix, transpose, floor, mod.
  • Operators given as numpy ufuncs or as nl functions (nl.add, nl.max, nl.sum, ...) map to numpy ufuncs by name.
  • nisa.dma_copy and nisa.dma_transpose read and write through load / store, so analysis clients see their HBM accesses as loads and stores. NKITransformer rewrites nisa.dma_copy(dst=o[...], src=x[...]) and nisa.dma_transpose(x[...]) to pass the subscripts as dst_keys / src_keys.

The samples' kernels also needed these fixes:

  • 1-D tiles. A 1-D tile has only the partition dimension; NKI broadcasts it along the free axes. numpy aligned it with the last axis, so nisa.activation(op=nl.exp, data=t, scale=A[c0:c1, j]) failed with operands could not be broadcast together with shapes (128,512) (128,). Binary operations, scale / bias, and scalar operands now align a 1-D tile with axis 0.
  • par_dim. Kernels import it directly (from neuronxcc.nki.language import par_dim), so nl.ndarray((par_dim(128), n), ...) received NKI's ParDim objects; shapes now take their value.
  • nl.mgrid. Its result has .p and .x (and .y, .z) for its axes, as in NKI.
  • Assignment. Assigning a [P, 1] result to a [P] slot reshapes it, as store already does.
  • Slices past the tensor. NKI keeps the tile's size, but numpy truncated the slice and changed the tile's shape. A key of ints and slices with an out-of-range slice is now indexed with arrays, so the tile keeps its shape and the out-of-bounds lanes reach masked_load. An unmasked out-of-bounds load now raises IndexError there, as NKI's simulator does, instead of failing on mask.shape.
  • Shared HBM aliasing. Builder.ndarray named a shared-HBM tensor after its caller's frame so that every program of the grid gets the same array. That caller was the op-patching wrapper, so every shared-HBM tensor of a kernel shared one name, and one array. It now uses the kernel's allocation site.
  • Tracer. It accepts a boolean mask (a condition on Python ints) and slices whose bounds are computed (nl.ds(start, size)).

Tests

Not modeled: kernels that allocate SBUF by address (ncc.sbuf.mod_alloc) and rely on two tiles sharing the same memory. Such tiles are separate arrays here.

🤖 Generated with Claude Code

https://claude.ai/code/session_0169QRxKtsivkLDCS5f7rrsm

…KI interpreter

Implements, with NKI's semantics, the nisa instructions that AWS's NKI
samples use: nc_matmul, nc_transpose, activation, activation_reduce,
tensor_tensor, tensor_scalar, tensor_scalar_reduce, scalar_tensor_tensor,
tensor_reduce, tensor_tensor_scan, tensor_copy, memset, affine_select,
reciprocal, iota, dma_copy, dma_transpose, get_nc_version; and nl.ds,
num_programs, program_ndim, full, ones, shared_constant,
shared_identity_matrix, transpose, floor, mod. nisa.dma_copy and
nisa.dma_transpose read and write through load/store, so clients see their
HBM accesses; NKITransformer passes their subscripted operands as keys.

Also: a 1-D tile (partition only) broadcasts along the free axes; shapes
accept par_dim objects imported from NKI; nl.mgrid results have .p/.x;
assigning a [P, 1] result to a [P] slot reshapes it; a slice past the
tensor keeps the tile's size instead of being truncated by numpy, and an
unmasked out-of-bounds load raises IndexError as in NKI; shared-HBM
tensors were all named after the op-patching wrapper's frame and so
aliased one array; the tracer accepts boolean masks and slices with
computed bounds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0169QRxKtsivkLDCS5f7rrsm
numpy_keys = self._convert_keys_to_numpy(keys)

# Call the actual masked_load function
numpy_keys = _expand_oob_slices(numpy_keys, ndarray.shape)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Must fix: _expand_oob_slices runs only inside Builder.load / store. The Load / Store callbacks fire before the op runs (core/patch.py), with the raw keys from the adapters in core/frontend/nki.py. So the tracer gets numpy's truncated slice while the simulator uses the full tile:

x: [128, 32], mask = nl.arange(32)[None, :] < 31
nl.load(x[0:128, 1:33], mask=mask)
# simulator:                       tile (128, 32)
# tracer, tile_mask(offsets, ...): ValueError: operands could not be broadcast together
#                                  with remapped shapes [original->remapped]: (1,32) and requested shape (128,31)

Without a mask, the tracer records a truncated Load before the simulator raises IndexError. The new test only covers the unmasked raise.

Suggestion: expand the keys once, where they are made (Builder._convert_keys_to_numpy, or the Load / Store adapters), so clients and the simulator share the same tile.

ranges = []
for dim, k in enumerate(keys):
if isinstance(k, slice) and dim < len(shape):
start = 0 if k.start is None else k.start

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Must fix: _expand_oob_slices treats a negative slice start as out of range and replaces the slice with np.arange(start, stop). Negative fancy indices wrap in numpy, so every index is "valid" and the load returns all of them with no error:

y: [200, 4]
y[-128:, :]                        -> numpy: (128, 4)
nki_builder.load(y, (slice(-128, None), slice(None)))  -> (328, 4)

Before this PR, nl.load(x[-128:, :]) or dma_copy(src=x[-k:]) returned the last 128 rows.

Suggestion: normalize negative start / stop against shape[dim] first (as normalize_slice does), or skip the expansion when start < 0.

if isinstance(other, NDArray):
return NDArray(
value=op_func(self.data, other.data),
value=op_func(*_aligned_pair(self.data, other.data)),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Must fix: NDArray._binary_op (and _rbinary_op) now applies _aligned_pair to every operand pair, so a 1-D array is treated as [P, 1]. That's right for data tiles, but it also applies to index expressions built from nl.arange, which rely on plain numpy broadcasting:

i_p = nl.arange(128)[:, None]; i_f = nl.arange(128)
i_p * 128 + i_f            -> numpy: (128, 128) | this PR: (128, 1)
nl.arange(64) + i_p        -> numpy: (128, 64)  | this PR: ValueError: operands could not be broadcast together with shapes (64,1) (128,1)

This hits any kernel that mixes a 1-D arange with a 2-D index tile, and any + - * < & between a 1-D and an N-D NDArray.

Suggestion: keep partition alignment in the tile/ISA ops (tensor_scalar, activation, Builder._binary_op) and restore plain numpy broadcasting in the NDArray operators, or apply it only to non-index tiles.

target_shape = self.data[new_keys].shape
value = np.asarray(value.data if isinstance(value, NDArray) else value)
if value.shape != target_shape and value.size == int(np.prod(target_shape)):
value = value.reshape(target_shape) # e.g. a [P, 1] result into a [P] slot

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness: __setitem__ reshapes any value whose size matches the target slot, so a wrongly shaped tile is silently re-laid out instead of raising:

buf = zeros([4, 8]); t = arange(32).reshape(8, 4)   # e.g. a missing transpose
buf[0:4, 0:8] = t
# buf[0] == [0, 1, 2, 3, 4, 5, 6, 7]: t reshaped in memory order, no error
# plain numpy raises ValueError here

Catching layout bugs like this is a large part of what an analysis tool is for. store (from #539, L463) has the same behavior.

Suggestion: reshape only when the shapes differ by size-1 dims (e.g. np.squeeze(value).shape == np.squeeze(target).shape); otherwise let numpy broadcast or raise.

if not (
isinstance(call_node.func, ast.Attribute)
and isinstance(call_node.func.value, ast.Name)
and call_node.func.value.id == "nisa"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness: The dma_copy / dma_transpose rewrite only matches the literal name nisa:

nisa.dma_copy(dst=o[i], src=x[i])     -> nisa.dma_copy(dst=o, dst_keys=i, src=x, src_keys=i)
isa.dma_copy(dst=o[i], src=x[i])      -> unchanged
nki.isa.dma_copy(dst=o[i], src=x[i])  -> unchanged

When it isn't rewritten, dst=o[i] runs NDArray.__getitem__, which returns a new NDArray (a copy for fancy keys), dst_keys is None, and the store fills that throwaway object. The output is unchanged, with no error.

Suggestion: match any attribute chain ending in isa.dma_copy / isa.dma_transpose (or resolve the target from the exec globals). As a backstop, raise in Builder.dma_copy when dst is a sliced NDArray and dst_keys is None.

return tuple(self._convert_keys_to_numpy(k) for k in keys)
elif isinstance(keys, NDArray):
return keys.data
elif isinstance(keys, slice): # e.g. nl.ds(start, size) with a computed start

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correctness: This branch (and the tracer) now turns nl.ds slices with an NDArray start into ints, but NDArray.__getitem__ / __setitem__ (L213, L224) still pass such slices straight to numpy:

start = NDArray(4)
nki_builder.load(tile, (slice(None), nl.ds(start, 4)))   # works: (4, 4)
tile[:, nl.ds(start, 4)]
# TypeError: slice indices must be integers or None or have an __index__ method

So nl.ds with a computed start works for nl.load / nl.store but not for slicing an SBUF tile before a nisa op.

Suggestion: route __getitem__ / __setitem__ keys through the same converter (_int on slice parts), or give NDArray an __index__ for 0-d values.

)
if bias is not None:
value = value + _partition_aligned(bias, nd)
value = self._activate(op, value)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: Arguments that affect the result fall into **kwargs and are dropped without a warning:

  • activation's reduce_cmd: _reduce_into always overwrites reduce_res, so a kernel that passes reduce_cmd to accumulate a row sum across loop iterations gets only the last iteration's sum.
  • nc_matmul's is_transpose: stationary.T @ moving is computed whatever its value.

Suggestion: support these flags, or raise NotImplementedError when they are set to a non-default value instead of swallowing them.

reduced = _ufunc(reduce_op).reduce(
value, axis=_free_axes(value.ndim), keepdims=True
)
reduce_res.data[...] = np.broadcast_to(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: _reduce_into writes reduce_res.data[...] directly. When reduce_res is a copy, such as an indexed slice with fancy keys, the result never reaches the accumulator:

acc = zeros([4, 3]); d = ones([4, 8])
nisa.activation(np.exp, d, reduce_op=np.add, reduce_res=acc[i_p, 1])
# acc[:, 1] == [0, 0, 0, 0]        (the sum went into a temporary copy)
nisa.activation(np.exp, d, reduce_op=np.add, reduce_res=acc[:, 1:2])
# acc[:, 1] == [21.75, ...]        (a basic-slice view works)

The write also bypasses the Store callbacks, so the tracer and visualizer never record it.

Suggestion: keep the base array and keys on sliced NDArrays and write back through them, or at least reject a reduce_res that isn't a view.

if isinstance(keys, (tuple, list)):
return tuple(_convert_keys_to_numpy(k) for k in keys)
if isinstance(keys, slice): # e.g. nl.ds(start, size) with a computed start
part = (

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: This lambda repeats simulation.nki._int and Builder._convert_keys_to_numpy. The copies have already drifted: neither expands out-of-range slices, which is why the tracer and the simulator disagree on out-of-range slices (see the comment on nki.py:437). The # noqa: E731 is also redundant, as pyproject.toml already ignores E731.

Suggestion: one shared convert_nki_keys(keys, shape) helper (int conversion plus out-of-range expansion), in core/masked_load_store.py or core/frontend/nki.py, used by both Builder and the tracer; drop the noqa.

new_keys = [k.data if isinstance(k, NDArray) else k for k in keys]
self.data[tuple(new_keys)] = value.data
new_keys = tuple(k.data if isinstance(k, NDArray) else k for k in keys)
target_shape = self.data[new_keys].shape

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: Two new per-access costs:

  • _expand_oob_slices builds an np.arange per slice dimension on every load / store before checking whether any is out of range.
  • __setitem__ evaluates self.data[new_keys] just to read its shape; for fancy keys that copies the whole tile.

Both run for every program of the grid and every loop iteration.

Suggestion: check bounds arithmetically first (start < 0 or start + (len - 1) * step >= shape[dim]) and build the aranges only when expanding; get the target shape from tile_shape() / np.broadcast_shapes instead of indexing.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants