"""Example 3 — Matrix multiplication: naive version and tiled version.

The tiled version loads TPB x TPB tiles into shared memory, synchronizes the
block, then computes: each element of A and B is read from global memory TPB
times less often.

Concepts: 2D grid, shared memory, syncthreads, coalesced accesses.

    python examples/03_matrix_multiplication.py [device]
"""

import numpy as np
from common import choose_device, size

import unigpu as gpu

TPB = 16  # threads per block in each dimension (compile-time constant)


@gpu.jit
def matmul_naive(A, B, C):
    col, row = gpu.grid(2)        # x = column: neighbouring threads -> neighbouring cells
    if row < C.shape[0] and col < C.shape[1]:
        acc = gpu.float32(0)
        for k in range(A.shape[1]):
            acc += A[row, k] * B[k, col]
        C[row, col] = acc


@gpu.jit
def matmul_tiled(A, B, C):
    sA = gpu.shared.array((TPB, TPB), gpu.float32)
    sB = gpu.shared.array((TPB, TPB), gpu.float32)
    col, row = gpu.grid(2)
    tx = gpu.threadIdx.x
    ty = gpu.threadIdx.y
    acc = gpu.float32(0)
    for t in range((A.shape[1] + TPB - 1) // TPB):
        # 1. each thread loads one element of each tile
        if row < A.shape[0] and t * TPB + tx < A.shape[1]:
            sA[ty, tx] = A[row, t * TPB + tx]
        else:
            sA[ty, tx] = 0
        if col < B.shape[1] and t * TPB + ty < B.shape[0]:
            sB[ty, tx] = B[t * TPB + ty, col]
        else:
            sB[ty, tx] = 0
        gpu.syncthreads()          # 2. wait until the tiles are complete
        for k in range(TPB):       # 3. compute from shared memory
            acc += sA[ty, k] * sB[k, tx]
        gpu.syncthreads()          # 4. before overwriting the tiles
    if row < C.shape[0] and col < C.shape[1]:
        C[row, col] = acc


def time_kernel(kernel, grid, *arguments):
    """Duration on the GPU, measured with events."""
    kernel[grid, (TPB, TPB)](*arguments)          # compilation
    start, end = gpu.event(), gpu.event()
    start.record()
    kernel[grid, (TPB, TPB)](*arguments)
    end.record()
    end.synchronize()
    return start.elapsed_time(end)


def main():
    """Run the example on the device given as an argument (the best one otherwise)."""
    choose_device()
    n = size(512, 32)
    A = np.random.rand(n, n).astype(np.float32)
    B = np.random.rand(n, n).astype(np.float32)
    d_A, d_B = gpu.to_device(A), gpu.to_device(B)
    d_C = gpu.device_array((n, n), np.float32)
    grid = ((n + TPB - 1) // TPB, (n + TPB - 1) // TPB)

    gflop = 2 * n ** 3 / 1e9
    for kernel in (matmul_naive, matmul_tiled):
        ms = time_kernel(kernel, grid, d_A, d_B, d_C)
        assert np.allclose(d_C.copy_to_host(), A @ B, rtol=1e-3)
        print(f"{kernel.__name__:13s}: {ms:8.2f} ms ({gflop / max(ms, 1e-6) * 1e3:7.1f} GFLOP/s)")


if __name__ == "__main__":
    main()
