"""Static stream-buffer and explicit software-pipeline examples."""

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

# ---------------------------------------------------------------------------
# Stream buffers
# ---------------------------------------------------------------------------


# NKI_EXAMPLE_TILED_GRID_SCALE_CHUNKS_BEGIN
@nki.jit
def scale_chunks(src):
    """Scale rank-three tensor slices through two reusable SBUF slots."""
    # src.shape == (128, 8, 128)
    out = nl.ndarray(src.shape, dtype=src.dtype, buffer=nl.shared_hbm)
    src_sbufs = nl.alloc_stream_buffers(src, buffer=nl.sbuf, dim=1, num_slots=2)

    for m in range(src.shape[1]):
        src_chunk = src[:, m, :]
        chunk_sbuf = src_sbufs[m]
        nisa.dma_copy(dst=chunk_sbuf, src=src_chunk)
        nisa.tensor_scalar(
            dst=chunk_sbuf,
            data=chunk_sbuf,
            op0=nl.multiply,
            operand0=2.0,
        )
        nisa.dma_copy(dst=out[:, m, :], src=chunk_sbuf)
    return out


# NKI_EXAMPLE_TILED_GRID_SCALE_CHUNKS_END


@nki.jit
def stream_input_output_scale(src):
    """Scale tiles through independent double-buffered input and output pools."""
    # src is a 2D tensor, for example (512, 1024).
    tile_shape = (128, 128)
    src_tiles = nl.tiles(src, tile_shape=tile_shape)
    out = nl.ndarray(src.shape, dtype=src.dtype, buffer=nl.shared_hbm)
    out_tiles = nl.tiles(out, tile_shape=tile_shape)

    for i in range(src_tiles.shape[0]):
        src_row_view = src_tiles[i, :]
        out_row_view = out_tiles[i, :]
        src_sbufs = nl.alloc_stream_buffers(
            src_row_view, buffer=nl.sbuf, dim=0, num_slots=2
        )
        out_sbufs = nl.alloc_stream_buffers(
            out_row_view, buffer=nl.sbuf, dim=0, num_slots=2
        )
        for j in range(src_row_view.shape[0]):
            nisa.dma_copy(
                dst=src_sbufs[j].data,
                src=src_row_view[j].data,
            )
            nisa.tensor_scalar(
                dst=out_sbufs[j].data,
                data=src_sbufs[j].data,
                op0=nl.multiply,
                operand0=2.0,
            )
            nisa.dma_copy(
                dst=out_row_view[j].data,
                src=out_sbufs[j].data,
            )
    return out


@nki.jit
def stream_with_dtype_conversion(src):
    """Sum each tile column after converting stream slots to BF16."""
    # src is a 2D tensor, for example (512, 1024).
    tile_shape = (128, 128)
    src_tiles = nl.tiles(src, tile_shape=tile_shape)
    out = nl.ndarray(
        (tile_shape[0], src.shape[1]),
        dtype=src.dtype,
        buffer=nl.shared_hbm,
    )
    out_tiles = nl.tiles(out, tile_shape=tile_shape)

    for j in range(src_tiles.shape[1]):
        src_col_view = src_tiles[:, j]
        src_sbufs = nl.alloc_stream_buffers(
            src_col_view,
            buffer=nl.sbuf,
            dim=0,
            num_slots=2,
            dtype=nl.bfloat16,
        )
        out_sbuf = nl.ndarray(tile_shape, dtype=nl.float32, buffer=nl.sbuf)
        nisa.memset(dst=out_sbuf, value=0.0)

        for i in range(src_col_view.shape[0]):
            nisa.dma_copy(
                dst=src_sbufs[i].data,
                src=src_col_view[i].data,
            )
            nisa.tensor_tensor(
                dst=out_sbuf,
                data1=out_sbuf,
                data2=src_sbufs[i].data,
                op=nl.add,
            )
        nisa.dma_copy(dst=out_tiles[0, j].data, src=out_sbuf)
    return out


@nki.jit
def stream_dim_walks_columns(src):
    """Stream each complete tile column through one coalesced DMA operand."""
    # src is a 2D tensor, for example (512, 1024).
    tile_shape = (128, 128)
    src_tiles = nl.tiles(src, tile_shape=tile_shape)
    out = nl.ndarray(src.shape, dtype=src.dtype, buffer=nl.shared_hbm)
    out_tiles = nl.tiles(out, tile_shape=tile_shape)
    src_sbufs = nl.alloc_stream_buffers(src_tiles, buffer=nl.sbuf, dim=1, num_slots=2)

    for j in range(src_tiles.shape[1]):
        src_col_view = src_tiles[:, j]
        out_col_view = out_tiles[:, j]
        src_sbuf = src_sbufs[j]
        nisa.dma_copy(dst=src_sbuf.data, src=src_col_view.data)
        for i in range(src_sbuf.shape[0]):
            tile_sbuf = src_sbuf[i].data
            nisa.tensor_scalar(
                dst=tile_sbuf, data=tile_sbuf, op0=nl.multiply, operand0=2.0
            )
        nisa.dma_copy(dst=out_col_view.data, src=src_sbuf.data)
    return out


# NKI_EXAMPLE_TILED_GRID_STREAM_PARTIAL_BLOCKS_BEGIN
def _move_block(dst_view, src_view):
    """Move one block, splitting it when its tiles have mixed partition extents."""
    if src_view.is_data_representable and dst_view.is_data_representable:
        nisa.dma_copy(dst=dst_view.data, src=src_view.data)
        return

    # A block that spans a partition remainder needs one transfer per extent.
    dst_tiles = nl.tiles(dst_view)
    src_tiles = nl.tiles(src_view)
    nisa.dma_copy(dst=dst_tiles[:-1].data, src=src_tiles[:-1].data)
    nisa.dma_copy(dst=dst_tiles[-1:].data, src=src_tiles[-1:].data)


@nki.jit
def stream_2d_blocks(src):
    """Stream one block at a time and process its interior tile grid."""
    # src is a 2D tensor, for example (500, 500).
    tile_shape = (128, 128)
    block_shape = (2, 2)
    src_blocks = nl.blocks(src, tile_shape=tile_shape, block_shape=block_shape)
    out = nl.ndarray(src.shape, dtype=src.dtype, buffer=nl.shared_hbm)
    out_blocks = nl.blocks(out, tile_shape=tile_shape, block_shape=block_shape)

    for i in range(src_blocks.shape[0]):
        src_row_view = src_blocks[i, :]
        src_sbufs = nl.alloc_stream_buffers(
            src_row_view, buffer=nl.sbuf, dim=0, num_slots=2
        )
        for j in range(src_row_view.shape[0]):
            # The final step of a row returns a view clamped to its valid extent.
            block_sbuf = src_sbufs[j]
            _move_block(block_sbuf, src_row_view[j])
            tiles_sbuf = nl.tiles(block_sbuf)
            for k in range(tiles_sbuf.shape[0]):
                for p in range(tiles_sbuf.shape[1]):
                    tile_sbuf = tiles_sbuf[k, p].data
                    nisa.tensor_scalar(
                        dst=tile_sbuf, data=tile_sbuf, op0=nl.multiply, operand0=2.0
                    )
            _move_block(out_blocks[i, j], block_sbuf)
    return out


# NKI_EXAMPLE_TILED_GRID_STREAM_PARTIAL_BLOCKS_END


# ---------------------------------------------------------------------------
# Software pipelines
# ---------------------------------------------------------------------------


# NKI_EXAMPLE_TILED_GRID_PREFETCH_MATMUL_BEGIN
@nki.jit
def explicit_prefetch_matmul(lhs_t, rhs):
    """Prefetch the next RHS tile while multiplying the current tile."""
    # lhs_t and rhs are 2D tensors, for example (256, 256).
    tile_shape = (128, 128)
    _, out_rows = lhs_t.shape
    _, out_cols = rhs.shape
    assert lhs_t.shape[0] == rhs.shape[0], "Inputs must have the same K dimension"
    assert out_rows % tile_shape[0] == 0, (
        f"This example requires M to be a multiple of {tile_shape[0]}"
    )
    assert out_cols % tile_shape[1] == 0, (
        f"This example requires N to be a multiple of {tile_shape[1]}"
    )
    out = nl.ndarray((out_rows, out_cols), dtype=lhs_t.dtype, buffer=nl.shared_hbm)

    lhs_tiles = nl.tiles(lhs_t, tile_shape=tile_shape)
    rhs_tiles = nl.tiles(rhs, tile_shape=tile_shape)
    out_tiles = nl.tiles(out, tile_shape=tile_shape)
    reduction_tiles = lhs_tiles.shape[0]

    for m in range(out_tiles.shape[0]):
        # Hoist the LHS column.
        lhs_col_view = lhs_tiles[:, m]
        lhs_sbuf = nl.empty_like(lhs_col_view, buffer=nl.sbuf)
        assert lhs_col_view.is_data_representable and lhs_sbuf.is_data_representable, (
            "Split full and partial K tiles before hoisting the LHS column"
        )
        nisa.dma_copy(dst=lhs_sbuf.data, src=lhs_col_view.data)

        for n in range(out_tiles.shape[1]):
            rhs_col_view = rhs_tiles[:, n]
            # Stream the RHS column through two physical slots.
            rhs_sbufs = nl.alloc_stream_buffers(
                rhs_col_view, buffer=nl.sbuf, dim=0, num_slots=2
            )

            out_psum = nl.ndarray(tile_shape, dtype=nl.float32, buffer=nl.psum)

            # Prologue.
            nisa.dma_copy(dst=rhs_sbufs[0].data, src=rhs_col_view[0].data)

            # Steady state.
            for k in range(reduction_tiles - 1):
                nisa.dma_copy(
                    dst=rhs_sbufs[k + 1].data,
                    src=rhs_col_view[k + 1].data,
                )
                nisa.nc_matmul(
                    dst=out_psum,
                    stationary=lhs_sbuf[k].data,
                    moving=rhs_sbufs[k].data,
                    accumulate=k > 0,
                )

            # Epilogue.
            nisa.nc_matmul(
                dst=out_psum,
                stationary=lhs_sbuf[reduction_tiles - 1].data,
                moving=rhs_sbufs[reduction_tiles - 1].data,
                accumulate=reduction_tiles > 1,
            )

            # Copy the result from PSUM through SBUF to HBM.
            out_sbuf = nl.ndarray(tile_shape, dtype=nl.float32, buffer=nl.sbuf)
            nisa.tensor_copy(dst=out_sbuf, src=out_psum)
            nisa.dma_copy(
                dst=out_tiles[m, n].data,
                src=out_sbuf,
            )
    return out


# NKI_EXAMPLE_TILED_GRID_PREFETCH_MATMUL_END


# NKI_EXAMPLE_TILED_GRID_TRIPLE_BUFFER_PIPELINE_BEGIN
@nki.jit
def triple_buffer_pipeline(src):
    """Scale tiles in place through a three-stage pipeline."""
    # src is a 2D tensor, for example (512, 256).
    tile_shape = (128, 512)
    src_tiles = nl.tiles(src, tile_shape=tile_shape)
    out = nl.ndarray(src.shape, dtype=src.dtype, buffer=nl.shared_hbm)
    out_tiles = nl.tiles(out, tile_shape=tile_shape)

    def scale_in_place(slot):
        nisa.tensor_scalar(dst=slot.data, data=slot.data, op0=nl.multiply, operand0=2.0)

    for j in range(src_tiles.shape[1]):
        src_view = src_tiles[:, j]
        out_view = out_tiles[:, j]
        src_sbufs = nl.alloc_stream_buffers(
            src_view, buffer=nl.sbuf, dim=0, num_slots=3
        )
        count = src_view.shape[0]
        assert count >= 2, "This pipeline requires at least two stream steps"

        # Prologue: load two items and compute the first.
        nisa.dma_copy(dst=src_sbufs[0].data, src=src_view[0].data)
        nisa.dma_copy(dst=src_sbufs[1].data, src=src_view[1].data)
        scale_in_place(src_sbufs[0])

        # Steady state: load k, compute k - 1, and store k - 2.
        for k in range(2, count):
            nisa.dma_copy(dst=src_sbufs[k].data, src=src_view[k].data)
            scale_in_place(src_sbufs[k - 1])
            nisa.dma_copy(
                dst=out_view[k - 2].data,
                src=src_sbufs[k - 2].data,
            )

        # Epilogue: finish and store the remaining items.
        scale_in_place(src_sbufs[count - 1])
        nisa.dma_copy(
            dst=out_view[count - 2].data,
            src=src_sbufs[count - 2].data,
        )
        nisa.dma_copy(
            dst=out_view[count - 1].data,
            src=src_sbufs[count - 1].data,
        )
    return out


# NKI_EXAMPLE_TILED_GRID_TRIPLE_BUFFER_PIPELINE_END
