"""Tiled matmul reuse, streaming, and coalescing examples."""

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

# ---------------------------------------------------------------------------
# Operand reuse
# ---------------------------------------------------------------------------


# NKI_EXAMPLE_TILED_GRID_MATMUL_SIMPLE_BEGIN
@nki.jit
def matmul_simple(lhs_t, rhs):
    """Compute ``lhs_t.T @ rhs`` one output tile at a time."""
    out = nl.ndarray(
        (lhs_t.shape[1], rhs.shape[1]), dtype=lhs_t.dtype, buffer=nl.shared_hbm
    )
    # Define tile-grid views over the HBM inputs and output.
    lhs_tiles = nl.tiles(lhs_t, tile_shape=(128, 128))
    rhs_tiles = nl.tiles(rhs, tile_shape=(128, 512))
    out_tiles = nl.tiles(out, tile_shape=(128, 512))

    for m in range(out_tiles.shape[0]):
        for n in range(out_tiles.shape[1]):
            # Accumulate one output tile across K in PSUM.
            out_psum = nl.ndarray((128, 512), dtype=nl.float32, buffer=nl.psum)
            for k in nl.affine_range(lhs_tiles.shape[0]):
                # Load the current lhsT and rhs tiles from HBM into SBUF.
                lhs_sbuf = nl.empty_like(lhs_tiles[k, m], buffer=nl.sbuf)
                rhs_sbuf = nl.empty_like(rhs_tiles[k, n], buffer=nl.sbuf)
                nisa.dma_copy(dst=lhs_sbuf.data, src=lhs_tiles[k, m].data)
                nisa.dma_copy(dst=rhs_sbuf.data, src=rhs_tiles[k, n].data)
                nisa.nc_matmul(
                    dst=out_psum,
                    stationary=lhs_sbuf.data,
                    moving=rhs_sbuf.data,
                    accumulate=k > 0,
                )
            # Move the completed tile from PSUM through SBUF to HBM.
            out_sbuf = nl.ndarray((128, 512), 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_MATMUL_SIMPLE_END


@nki.jit
def matmul_hoist_lhs(lhs_t, rhs):
    """DMA each LHS tile column once and reuse it across output columns."""
    # lhs_t is a 2D tensor, for example (256, 256).
    # rhs is a 2D tensor, for example (256, 512).
    lhs_tile_shape = (128, 128)
    rhs_tile_shape = (128, 512)
    out_tile_shape = (128, 512)
    _, out_rows = lhs_t.shape
    _, out_cols = rhs.shape
    out = nl.ndarray((out_rows, out_cols), dtype=lhs_t.dtype, buffer=nl.shared_hbm)
    lhs_tiles = nl.tiles(lhs_t, tile_shape=lhs_tile_shape)
    rhs_tiles = nl.tiles(rhs, tile_shape=rhs_tile_shape)
    out_tiles = nl.tiles(out, tile_shape=out_tile_shape)

    for m in range(out_tiles.shape[0]):
        lhs_col_view = lhs_tiles[:, m]
        lhs_sbuf = nl.empty_like(lhs_col_view, buffer=nl.sbuf)
        nisa.dma_copy(dst=lhs_sbuf.data, src=lhs_col_view.data)
        for n in range(out_tiles.shape[1]):
            out_psum = nl.ndarray(out_tile_shape, dtype=nl.float32, buffer=nl.psum)
            for k in range(lhs_tiles.shape[0]):
                rhs_view = rhs_tiles[k, n]
                rhs_sbuf = nl.empty_like(rhs_view, buffer=nl.sbuf)
                nisa.dma_copy(dst=rhs_sbuf.data, src=rhs_view.data)
                nisa.nc_matmul(
                    out_psum,
                    lhs_sbuf[k].data,
                    rhs_sbuf.data,
                    accumulate=k > 0,
                )
            out_sbuf = nl.ndarray(out_tile_shape, dtype=nl.float32, buffer=nl.sbuf)
            nisa.tensor_copy(out_sbuf, out_psum)
            nisa.dma_copy(dst=out_tiles[m, n].data, src=out_sbuf)
    return out


# ---------------------------------------------------------------------------
# Coalesced blocks
# ---------------------------------------------------------------------------


# NKI_EXAMPLE_TILED_GRID_MATMUL_BLOCKED_BEGIN
@nki.jit
def matmul_blocked(lhs_t, rhs, block_m=4, block_n=2, block_k=4):
    """Compute ``lhs_t.T @ rhs`` with block-level DMA."""
    assert block_m * block_n <= 8, "output block exceeds PSUM capacity"
    tile_m = nl.tile_size.gemm_stationary_fmax
    tile_k = nl.tile_size.pmax
    tile_n = nl.tile_size.gemm_moving_fmax
    # Keep M/K tiles full to avoid mixed partition extents in block transfers.
    assert lhs_t.shape[1] % tile_m == 0, (
        f"This example requires M to be a multiple of {tile_m}"
    )
    assert lhs_t.shape[0] % tile_k == 0 and rhs.shape[0] % tile_k == 0, (
        f"This example requires K to be a multiple of {tile_k} in both inputs"
    )
    out = nl.ndarray(
        (lhs_t.shape[1], rhs.shape[1]),
        dtype=lhs_t.dtype,
        buffer=nl.shared_hbm,
    )

    lhs_blocks = nl.blocks(
        lhs_t,
        tile_shape=(tile_k, tile_m),
        block_shape=(block_k, block_m),
    )
    rhs_blocks = nl.blocks(
        rhs,
        tile_shape=(tile_k, tile_n),
        block_shape=(block_k, block_n),
    )
    out_blocks = nl.blocks(
        out,
        tile_shape=(tile_m, tile_n),
        block_shape=(block_m, block_n),
    )

    for m in range(lhs_blocks.shape[1]):
        for n in range(rhs_blocks.shape[1]):
            out_block = out_blocks[m, n]
            out_psum = nl.alloc_tiles(
                tile_shape=(tile_m, tile_n),
                element_shape=out_block.element_shape,
                buffer=nl.psum,
                dtype=nl.float32,
            )
            out_sbuf = nl.alloc_tiles(
                tile_shape=(tile_m, tile_n),
                element_shape=out_block.element_shape,
                buffer=nl.sbuf,
                dtype=lhs_t.dtype,
            )

            for k in nl.sequential_range(rhs_blocks.shape[0]):
                lhs_sbuf = nl.empty_like(lhs_blocks[k, m], buffer=nl.sbuf)
                rhs_sbuf = nl.empty_like(rhs_blocks[k, n], buffer=nl.sbuf)
                nisa.dma_copy(dst=lhs_sbuf.data, src=lhs_blocks[k, m].data)
                nisa.dma_copy(dst=rhs_sbuf.data, src=rhs_blocks[k, n].data)
                lhs_tiles_sbuf = nl.tiles(lhs_sbuf)
                rhs_tiles_sbuf = nl.tiles(rhs_sbuf)
                for i in range(out_sbuf.shape[0]):
                    for j in range(out_sbuf.shape[1]):
                        for p in range(rhs_tiles_sbuf.shape[0]):
                            is_first_contraction = k == 0 and p == 0
                            nisa.nc_matmul(
                                dst=out_psum[i, j].data,
                                stationary=lhs_tiles_sbuf[p, i].data,
                                moving=rhs_tiles_sbuf[p, j].data,
                                accumulate=not is_first_contraction,
                            )

            nisa.tensor_copy(dst=out_sbuf.data, src=out_psum.data)
            nisa.dma_copy(dst=out_block.data, src=out_sbuf.data)
    return out


# NKI_EXAMPLE_TILED_GRID_MATMUL_BLOCKED_END


@nki.jit
def matmul_blocked_hoisted(
    lhs_t, rhs, tiles_in_block_m=4, tiles_in_block_n=2, tiles_in_block_k=4
):
    """Compute ``lhs_t.T @ rhs`` while reusing one LHS block column."""
    tile_m = nl.tile_size.gemm_stationary_fmax
    tile_k = nl.tile_size.pmax
    tile_n = nl.tile_size.gemm_moving_fmax
    _, out_rows = lhs_t.shape
    _, out_cols = rhs.shape
    out = nl.ndarray((out_rows, out_cols), dtype=lhs_t.dtype, buffer=nl.shared_hbm)

    lhs_blocks = nl.blocks(
        lhs_t,
        tile_shape=(tile_k, tile_m),
        block_shape=(tiles_in_block_k, tiles_in_block_m),
    )
    rhs_blocks = nl.blocks(
        rhs,
        tile_shape=(tile_k, tile_n),
        block_shape=(tiles_in_block_k, tiles_in_block_n),
    )
    out_blocks = nl.blocks(
        out,
        tile_shape=(tile_m, tile_n),
        block_shape=(tiles_in_block_m, tiles_in_block_n),
    )

    # docs-blocked-hoisted-start
    for m in range(lhs_blocks.shape[1]):
        lhs_col_view = lhs_blocks[:, m]
        lhs_col_sbuf = nl.empty_like(lhs_col_view, buffer=nl.sbuf)
        nisa.dma_copy(dst=lhs_col_sbuf.data, src=lhs_col_view.data)

        for n in range(rhs_blocks.shape[1]):
            out_view = out_blocks[m, n]
            out_psum = nl.alloc_tiles(
                tile_shape=(tile_m, tile_n),
                element_shape=out_view.element_shape,
                buffer=nl.psum,
                dtype=nl.float32,
            )
            out_sbuf = nl.alloc_tiles(
                tile_shape=(tile_m, tile_n),
                element_shape=out_view.element_shape,
                buffer=nl.sbuf,
                dtype=lhs_t.dtype,
            )

            for k in nl.sequential_range(rhs_blocks.shape[0]):
                lhs_block_sbuf = lhs_col_sbuf[k]
                rhs_view = rhs_blocks[k, n]
                rhs_block_sbuf = nl.empty_like(rhs_view, buffer=nl.sbuf)
                nisa.dma_copy(dst=rhs_block_sbuf.data, src=rhs_view.data)
                # docs-blocked-hoisted-end
                lhs_sbuf_tiles = nl.tiles(lhs_block_sbuf)
                rhs_sbuf_tiles = nl.tiles(rhs_block_sbuf)
                for i in range(out_sbuf.shape[0]):
                    for j in range(out_sbuf.shape[1]):
                        for p in range(rhs_sbuf_tiles.shape[0]):
                            is_first_contraction = k == 0 and p == 0
                            nisa.nc_matmul(
                                dst=out_psum[i, j].data,
                                stationary=lhs_sbuf_tiles[p, i].data,
                                moving=rhs_sbuf_tiles[p, j].data,
                                accumulate=not is_first_contraction,
                            )

            for i in range(out_sbuf.shape[0]):
                for j in range(out_sbuf.shape[1]):
                    nisa.tensor_copy(
                        dst=out_sbuf[i, j].data,
                        src=out_psum[i, j].data,
                    )
            nisa.dma_copy(dst=out_view.data, src=out_sbuf.data)
    return out


# NKI_EXAMPLE_TILED_GRID_MATMUL_BLOCKED_STREAMED_BEGIN
@nki.jit
def matmul_blocked_streamed(lhs_t, rhs, block_m=4, block_n=2, block_k=4):
    """Stream RHS reduction blocks while accumulating one output block."""
    assert block_m * block_n <= 8, "output block exceeds PSUM capacity"
    assert lhs_t.shape[0] == rhs.shape[0], "Inputs must have the same K dimension"
    tile_m = nl.tile_size.gemm_stationary_fmax
    tile_k = nl.tile_size.pmax
    tile_n = nl.tile_size.gemm_moving_fmax
    out = nl.ndarray(
        (lhs_t.shape[1], rhs.shape[1]),
        dtype=lhs_t.dtype,
        buffer=nl.shared_hbm,
    )

    lhs_blocks = nl.blocks(
        lhs_t,
        tile_shape=(tile_k, tile_m),
        block_shape=(block_k, block_m),
    )
    rhs_blocks = nl.blocks(
        rhs,
        tile_shape=(tile_k, tile_n),
        block_shape=(block_k, block_n),
    )
    out_blocks = nl.blocks(
        out,
        tile_shape=(tile_m, tile_n),
        block_shape=(block_m, block_n),
    )

    for m in range(lhs_blocks.shape[1]):
        lhs_col = lhs_blocks[:, m]
        lhs_sbuf = nl.empty_like(lhs_col, buffer=nl.sbuf)
        assert lhs_col.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.data)

        for n in range(rhs_blocks.shape[1]):
            out_block = out_blocks[m, n]
            out_psum = nl.alloc_tiles(
                tile_shape=(tile_m, tile_n),
                element_shape=out_block.element_shape,
                buffer=nl.psum,
                dtype=nl.float32,
            )
            out_sbuf = nl.alloc_tiles(
                tile_shape=(tile_m, tile_n),
                element_shape=out_block.element_shape,
                buffer=nl.sbuf,
                dtype=lhs_t.dtype,
            )
            assert (
                out_block.is_data_representable
                and out_psum.is_data_representable
                and out_sbuf.is_data_representable
            ), "Split full and partial M tiles into separate output blocks"
            rhs_col = rhs_blocks[:, n]
            rhs_stream = nl.alloc_stream_buffers(
                rhs_col,
                buffer=nl.sbuf,
                dim=0,
                num_slots=2,
            )

            # Prologue: make the first RHS block available.
            nisa.dma_copy(dst=rhs_stream[0].data, src=rhs_col[0].data)

            for k in range(rhs_col.shape[0]):
                # Prefetch the next RHS block before computing the current one.
                if k + 1 < rhs_col.shape[0]:
                    nisa.dma_copy(
                        dst=rhs_stream[k + 1].data,
                        src=rhs_col[k + 1].data,
                    )

                lhs_tiles = nl.tiles(lhs_sbuf[k])
                rhs_tiles = nl.tiles(rhs_stream[k])
                for i in range(out_sbuf.shape[0]):
                    for j in range(out_sbuf.shape[1]):
                        for p in range(rhs_tiles.shape[0]):
                            nisa.nc_matmul(
                                dst=out_psum[i, j].data,
                                stationary=lhs_tiles[p, i].data,
                                moving=rhs_tiles[p, j].data,
                                accumulate=None,
                            )

            nisa.tensor_copy(dst=out_sbuf.data, src=out_psum.data)
            nisa.dma_copy(dst=out_block.data, src=out_sbuf.data)
    return out


# NKI_EXAMPLE_TILED_GRID_MATMUL_BLOCKED_STREAMED_END
