This document is relevant for: Trn2, Trn3

nki.language.contiguous_indices#

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

Return the contiguous coordinate slice owned by one shard.

The half-open coordinate range [0, extent) is partitioned into num_shards adjacent, nonempty slices. Shard sizes differ by at most one. When division has a remainder, lower shard IDs receive one additional coordinate.

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

shard 0: slice(0, 4)
shard 1: slice(4, 7)
shard 2: slice(7, 10)

The result is a built-in slice, so it can index an NkiTensor, NkiTileGrid, or NkiBlockGrid. Applied to a grid, it partitions tile or block coordinates rather than source elements. The operation allocates no storage and emits no instruction.

All arguments must be exact compile-time Python integers; booleans and integer subclasses are rejected. Under the native tracer, nki.language.program_id() and nki.language.num_programs() satisfy this contract because each logical NeuronCore is traced with specialized Python integer values.

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

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

  • num_shards – Positive number of shards. It cannot exceed extent, because this helper never returns an empty shard.

Returns:

A unit-step built-in slice selecting this shard’s contiguous 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_contiguous_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.contiguous_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.interleaved_indices(): Select round-robin

coordinates instead of one adjacent range.

This document is relevant for: Trn2, Trn3