Repository navigation
Conversation
…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) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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)), |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 hereCatching 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" |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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__ methodSo 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) |
There was a problem hiding this comment.
Minor: Arguments that affect the result fall into **kwargs and are dropped without a warning:
activation'sreduce_cmd:_reduce_intoalways overwritesreduce_res, so a kernel that passesreduce_cmdto accumulate a row sum across loop iterations gets only the last iteration's sum.nc_matmul'sis_transpose:stationary.T @ movingis 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( |
There was a problem hiding this comment.
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 = ( |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
Minor: Two new per-access costs:
_expand_oob_slicesbuilds annp.arangeper slice dimension on every load / store before checking whether any is out of range.__setitem__evaluatesself.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.
Stacked on #539 (base branch
fix/nki-official-kernels); retarget tomainafter #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 withRuntimeError: calling NKI API outside of NKI kernels is not supported. This PR implements them, plus thenloperations 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 intoreduce_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.nlfunctions (nl.add,nl.max,nl.sum, ...) map to numpy ufuncs by name.nisa.dma_copyandnisa.dma_transposeread and write throughload/store, so analysis clients see their HBM accesses as loads and stores.NKITransformerrewritesnisa.dma_copy(dst=o[...], src=x[...])andnisa.dma_transpose(x[...])to pass the subscripts asdst_keys/src_keys.The samples' kernels also needed these fixes:
nisa.activation(op=nl.exp, data=t, scale=A[c0:c1, j])failed withoperands 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), sonl.ndarray((par_dim(128), n), ...)received NKI'sParDimobjects; shapes now take their value.nl.mgrid. Its result has.pand.x(and.y,.z) for its axes, as in NKI.[P, 1]result to a[P]slot reshapes it, asstorealready does.masked_load. An unmasked out-of-bounds load now raisesIndexErrorthere, as NKI's simulator does, instead of failing onmask.shape.Builder.ndarraynamed 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.nl.ds(start, size)).Tests
tests/nki/test_nki_isa.py: six kernels run under TileLens and undernki.simulate_kernel, and their outputs must match. They cover matmul with DMA, the vector-engine instructions, a grid withnl.ds, DMA with subscripts, miscellaneous operations, and partition vectors withmgridand the scan. Two more tests check that a DMA is traced as a load and a store, and that an unmasked slice past the tensor raisesIndexError, as it does in NKI. All eight fail on [FIX] Run NKI kernels written like the official samples in the NKI interpreter #539's head.nki.simulate_kernelfor the eleven attention tutorial kernels (attn_fwd_v1...v11), the three fused Mamba kernels, and the Stable Diffusion attention tutorial, besides [FIX] Run NKI kernels written like the official samples in the NKI interpreter #539's kernels.pytest tests/ -m ""(NKI tests included): 626 passed, 2 skipped on [FIX] Run NKI kernels written like the official samples in the NKI interpreter #539; 634 passed, 2 skipped with this PR. Environment: Python 3.12, Triton 3.8.0, neuronx-cc 2.22.12471, nki 0.2.0.ruff checkandruff format --check(v0.1.9) pass on the changed files.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