This document is relevant for: Trn2, Trn3

nki.language.interleaved_indices#

nki.language.interleaved_indices(extent: int, *, shard_id: int, num_shards: int) → slice[source]#

Return the round-robin coordinate slice owned by one shard.

Shard shard_id receives that coordinate followed by every num_shards-th coordinate below extent. Divisibility is not required, and shard counts differ by at most one.

For extent=10 and num_shards=3, the returned slices are:

shard 0: slice(0, 10, 3)  # coordinates 0, 3, 6, 9
shard 1: slice(1, 10, 3)  # coordinates 1, 4, 7
shard 2: slice(2, 10, 3)  # coordinates 2, 5, 8

The result is a built-in slice and can index an NkiTensor, NkiTileGrid, or NkiBlockGrid. Applied to a grid, it creates a gapped tile or block view. NkiGrid.shape reports the number of owned cells, while NkiGrid.index_step_elements includes the round-robin stride. Access through NkiGrid.data preserves those gaps in the native access pattern.

All arguments must be exact compile-time Python integers; booleans and integer subclasses are rejected. Native-tracer nki.language.program_id() and nki.language.num_programs() values satisfy this requirement.

Parameters:
  • extent – Positive number of coordinates to partition.

  • shard_id – Zero-based shard identifier in [0, num_shards).

  • num_shards – Positive round-robin stride. It cannot exceed extent because this helper never returns an empty shard.

Returns:

A positive-step built-in slice selecting this shard’s interleaved coordinates.

Raises:
  • TypeError – if any argument is not an exact compile-time Python integer.

  • ValueError – if extent or num_shards is nonpositive, num_shards exceeds extent, or shard_id is outside its valid range.

Examples:

import nki
import nki.isa as nisa
import nki.language as nl

@nki.jit
def copy_interleaved_tile_rows(src):
    tile_shape = (128, 512)
    dst = nl.ndarray(
        src.shape, dtype=src.dtype, buffer=nl.shared_hbm
    )
    src_tiles = nl.tiles(src, tile_shape=tile_shape)
    dst_tiles = nl.tiles(dst, tile_shape=tile_shape)
    rows = nl.interleaved_indices(
        src_tiles.shape[0],
        shard_id=nl.program_id(0),
        num_shards=nl.num_programs(0),
    )
    local_src = src_tiles[rows, :]
    local_dst = dst_tiles[rows, :]

    for i in range(local_src.shape[0]):
        for j in range(local_src.shape[1]):
            src_tile = local_src[i, j]
            tile = nl.empty_like(src_tile, buffer=nl.sbuf)
            nisa.dma_copy(dst=tile.data, src=src_tile.data)
            nisa.dma_copy(
                dst=local_dst[i, j].data,
                src=tile.data,
            )
    return dst

See also

nki.language.contiguous_indices(): Select one adjacent coordinate

range per shard.

This document is relevant for: Trn2, Trn3