"""Tiled tensor addition with single-core and multicore sharding."""

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


# NKI_EXAMPLE_TILED_GRID_TENSOR_ADD_OWNED_REGION_BEGIN
def _tensor_add_owned_region(lhs, rhs, row_indices, column_indices):
    """Add the tile region selected by one pair of ownership slices."""
    tile_shape = (128, 512)
    out = nl.ndarray(lhs.shape, dtype=lhs.dtype, buffer=nl.shared_hbm)
    lhs_tiles = nl.tiles(lhs, tile_shape=tile_shape)[row_indices, column_indices]
    rhs_tiles = nl.tiles(rhs, tile_shape=tile_shape)[row_indices, column_indices]
    out_tiles = nl.tiles(out, tile_shape=tile_shape)[row_indices, column_indices]

    for i in range(lhs_tiles.shape[0]):
        for j in range(lhs_tiles.shape[1]):
            lhs_view = lhs_tiles[i, j]
            rhs_view = rhs_tiles[i, j]
            lhs_sbuf = nl.empty_like(lhs_view, buffer=nl.sbuf)
            rhs_sbuf = nl.empty_like(rhs_view, buffer=nl.sbuf)
            nisa.dma_copy(dst=lhs_sbuf.data, src=lhs_view.data)
            nisa.dma_copy(dst=rhs_sbuf.data, src=rhs_view.data)
            nisa.tensor_tensor(lhs_sbuf.data, lhs_sbuf.data, rhs_sbuf.data, op=nl.add)
            nisa.dma_copy(
                dst=out_tiles[i, j].data,
                src=lhs_sbuf.data,
            )
    return out


# NKI_EXAMPLE_TILED_GRID_TENSOR_ADD_OWNED_REGION_END


@nki.jit
def tensor_add_single_core(lhs, rhs):
    """Add two tensors one tile at a time."""
    tile_shape = (128, 512)
    out = nl.ndarray(lhs.shape, dtype=lhs.dtype, buffer=nl.shared_hbm)
    lhs_tiles = nl.tiles(lhs, tile_shape=tile_shape)
    rhs_tiles = nl.tiles(rhs, tile_shape=tile_shape)
    out_tiles = nl.tiles(out, tile_shape=tile_shape)

    for i in range(lhs_tiles.shape[0]):
        for j in range(lhs_tiles.shape[1]):
            lhs_sbuf = nl.empty_like(lhs_tiles[i, j], buffer=nl.sbuf)
            rhs_sbuf = nl.empty_like(rhs_tiles[i, j], buffer=nl.sbuf)
            nisa.dma_copy(dst=lhs_sbuf.data, src=lhs_tiles[i, j].data)
            nisa.dma_copy(dst=rhs_sbuf.data, src=rhs_tiles[i, j].data)
            nisa.tensor_tensor(lhs_sbuf.data, lhs_sbuf.data, rhs_sbuf.data, op=nl.add)
            nisa.dma_copy(dst=out_tiles[i, j].data, src=lhs_sbuf.data)
    return out


@nki.jit
def tensor_add_contiguous(lhs, rhs):
    """Assign each logical NeuronCore contiguous tile columns."""
    # lhs and rhs are 2D tensors, for example (256, 4096).
    tile_shape = (128, 512)
    column_count = (lhs.shape[1] + tile_shape[1] - 1) // tile_shape[1]
    column_indices = nl.contiguous_indices(
        column_count,
        shard_id=nl.program_id(0),
        num_shards=nl.num_programs(0),
    )
    return _tensor_add_owned_region(
        lhs,
        rhs,
        row_indices=slice(None),
        column_indices=column_indices,
    )


@nki.jit
def tensor_add_interleaved(lhs, rhs):
    """Assign tile columns to logical NeuronCores in round-robin order."""
    # lhs and rhs are 2D tensors, for example (256, 4096).
    tile_shape = (128, 512)
    column_count = (lhs.shape[1] + tile_shape[1] - 1) // tile_shape[1]
    column_indices = nl.interleaved_indices(
        column_count,
        shard_id=nl.program_id(0),
        num_shards=nl.num_programs(0),
    )
    return _tensor_add_owned_region(
        lhs,
        rhs,
        row_indices=slice(None),
        column_indices=column_indices,
    )


@nki.jit
def tensor_add_custom_columns(lhs, rhs):
    """Assign tile columns using an application-defined LNC=2 60/40 split."""
    tile_shape = (128, 512)
    column_count = (lhs.shape[1] + tile_shape[1] - 1) // tile_shape[1]
    core_id = nl.program_id(0)
    split_column = (3 * column_count) // 5
    column_boundaries = (0, split_column, column_count)
    column_indices = slice(
        column_boundaries[core_id],
        column_boundaries[core_id + 1],
    )
    return _tensor_add_owned_region(
        lhs,
        rhs,
        row_indices=slice(None),
        column_indices=column_indices,
    )


@nki.jit
def tensor_add_contiguous_rows(lhs, rhs):
    """Assign each logical NeuronCore one contiguous set of tile rows."""
    tile_shape = (128, 512)
    row_count = (lhs.shape[0] + tile_shape[0] - 1) // tile_shape[0]
    row_indices = nl.contiguous_indices(
        row_count,
        shard_id=nl.program_id(0),
        num_shards=nl.num_programs(0),
    )
    return _tensor_add_owned_region(
        lhs,
        rhs,
        row_indices=row_indices,
        column_indices=slice(None),
    )


@nki.jit
def tensor_add_interleaved_rows(lhs, rhs):
    """Assign tile rows to logical NeuronCores in round-robin order."""
    tile_shape = (128, 512)
    row_count = (lhs.shape[0] + tile_shape[0] - 1) // tile_shape[0]
    row_indices = nl.interleaved_indices(
        row_count,
        shard_id=nl.program_id(0),
        num_shards=nl.num_programs(0),
    )
    return _tensor_add_owned_region(
        lhs,
        rhs,
        row_indices=row_indices,
        column_indices=slice(None),
    )


# NKI_EXAMPLE_TILED_GRID_COPY_INTERLEAVED_TILE_BLOCKS_BEGIN
@nki.jit
def copy_interleaved_tile_blocks(src):
    """Promote interleaved tile rows to aggregate DMA blocks."""
    out = nl.ndarray(src.shape, dtype=src.dtype, buffer=nl.shared_hbm)
    src_tiles = nl.tiles(src, tile_shape=(128, 128))
    out_tiles = nl.tiles(out, tile_shape=(128, 128))
    owned_rows = nl.interleaved_indices(
        src_tiles.shape[0],
        shard_id=nl.program_id(0),
        num_shards=nl.num_programs(0),
    )
    src_blocks = nl.blocks(
        src_tiles[owned_rows, :],
        block_shape=(2, 1),
    )
    out_blocks = nl.blocks(
        out_tiles[owned_rows, :],
        block_shape=(2, 1),
    )

    for i in range(src_blocks.shape[0]):
        for j in range(src_blocks.shape[1]):
            block_sbuf = nl.empty_like(src_blocks[i, j], buffer=nl.sbuf)
            nisa.dma_copy(dst=block_sbuf.data, src=src_blocks[i, j].data)
            nisa.dma_copy(dst=out_blocks[i, j].data, src=block_sbuf.data)
    return out


# NKI_EXAMPLE_TILED_GRID_COPY_INTERLEAVED_TILE_BLOCKS_END
