"""Benchmarks of the examples: each kernel of the course, measured for several sizes.

For each example, a benchmark (``unigpu.benchmark.Case``) describes the data
of a given size, the launch of the example's kernel, and the same computation
with NumPy. The notebook ``notebooks/examples.ipynb`` uses them one by one;
on the command line, they all run:

    python examples/benchmarks.py [device] [--quick]

``--quick`` only measures the smallest size of each benchmark.

The default sizes go from "too small for a GPU" to "large enough to keep it
busy"; on the simulator, which is very slow, they stay tiny. Change them
(``benchmark.run(case, plan=benchmark.Plan(sizes=[...]))``) to see where the GPU pays off.
"""

import importlib
import sys

import numpy as np
from common import choose_device

from unigpu import benchmark
from unigpu.benchmark import Case


def _example(name):
    """Module of an example; its name starts with a digit, hence ``importlib``."""
    return importlib.import_module(name)


addition = _example("01_vector_addition")
saxpy = _example("02_saxpy_grid_stride")
matmul = _example("03_matrix_multiplication")
reduction = _example("04_reduction")
histogram = _example("05_histogram")
heat = _example("06_heat_2d")
mandelbrot = _example("07_mandelbrot")
streams = _example("09_streams_events")
smoothing = _example("10_dynamic_constant_memory")

#: Vectors: from 1,024 (2¹⁰) to 16,777,216 (2²⁴) elements; at most 4,096 on the simulator.
VECTORS, VECTORS_SIMULATOR = [2 ** k for k in range(10, 25, 2)], [256, 1024, 4096]
#: n×n matrices, images and grids.
MATRICES, MATRICES_SIMULATOR = [64, 128, 256, 512, 1024, 2048], [8, 16, 32]
IMAGES, IMAGES_SIMULATOR = [64, 128, 256, 512, 1024], [16, 32]
#: Threads per block of the 1D kernels.
THREADS = 256


def random_array(*shape):
    """Pseudo-random ``float32`` array, always the same for a given shape."""
    return np.random.RandomState(0).random_sample(shape).astype(np.float32)


def blocks(n, threads=THREADS):
    """Number of blocks needed to cover ``n`` elements."""
    return (n + threads - 1) // threads


def square(n):
    """How the size of a matrix, an image or a grid is written: ``512×512``."""
    return f"{n}×{n}"


def vector_case(name, *, arrays, launch, reference, bytes_per_element, **options):
    """Benchmark on vectors of ``n`` elements (``bytes_per_element`` read and written)."""
    return Case(name, arrays, launch, reference, VECTORS, VECTORS_SIMULATOR,
                bytes_moved=lambda n: bytes_per_element * n, **options)


def square_case(name, *, arrays, launch, reference, sizes, simulator_sizes, what, **options):
    """Benchmark on ``n×n`` arrays (matrices, images, grids)."""
    return Case(name, arrays, launch, reference, sizes, simulator_sizes,
                size_label=square, size_name=f"n ({what} n×n)", **options)


# --- Example 1: vector addition ------------------------------------------------------------

ADDITION = vector_case(
    "Vector addition (example 1)",
    arrays=lambda n: (random_array(n), random_array(n) + 1, np.zeros(n, np.float32)),
    launch=lambda a, b, c: addition.addition[blocks(c.size), THREADS](a, b, c),
    reference=lambda a, b, c: a + b,
    bytes_per_element=3 * 4)                        # read a and b, write c (float32)

# --- Example 2: SAXPY, with and without a "grid-stride" loop -------------------------------

SAXPY_GRID_STRIDE = vector_case(
    "SAXPY, fixed grid of 32 blocks and grid-stride loop (example 2)",
    arrays=lambda n: (random_array(n), random_array(n) + 1),
    launch=lambda x, y: saxpy.saxpy[32, THREADS](np.float32(2), x, y),
    reference=lambda x, y: np.float32(2) * x + y,
    bytes_per_element=3 * 4)                        # read x and y, write y

SAXPY_ONE_THREAD_PER_ELEMENT = vector_case(
    "SAXPY, one thread per element (example 2)",
    arrays=lambda n: (random_array(n), random_array(n) + 1),
    launch=lambda x, y: saxpy.saxpy_simple[blocks(x.size), THREADS](np.float32(2), x, y),
    reference=lambda x, y: np.float32(2) * x + y,
    bytes_per_element=3 * 4)

# --- Example 3: matrix multiplication, naive and tiled -------------------------------------


def _launch_matmul(kernel):
    tpb = matmul.TPB
    return lambda A, B, C: kernel[(blocks(C.shape[1], tpb), blocks(C.shape[0], tpb)),
                                  (tpb, tpb)](A, B, C)


def _matmul(name, kernel):
    return square_case(
        name, arrays=lambda n: (random_array(n, n), random_array(n, n),
                                np.zeros((n, n), np.float32)),
        launch=_launch_matmul(kernel), reference=lambda A, B, C: A @ B,
        sizes=MATRICES, simulator_sizes=MATRICES_SIMULATOR, what="matrices",
        check=lambda C, expected: np.allclose(C, expected, rtol=1e-3, atol=1e-3),
        flops=lambda n: 2 * n ** 3)                 # n³ multiplications and n³ additions


MATMUL_NAIVE = _matmul("Naive matrix multiplication (example 3)", matmul.matmul_naive)
MATMUL_TILED = _matmul("Tiled matrix multiplication, shared memory (example 3)",
                       matmul.matmul_tiled)

# --- Example 4: reduction ------------------------------------------------------------------


def _partial_sums(n):
    """One partial sum per block, 256 blocks at most (grid-stride loop beyond)."""
    return np.zeros(max(1, min(256, n // reduction.BLOCK)), np.float32)


REDUCTION = vector_case(
    "Reduction (sum) in shared memory (example 4)",
    arrays=lambda n: (random_array(n), _partial_sums(n)),
    launch=lambda a, p: reduction.block_sum[p.size, reduction.BLOCK](a, p),
    fetch=lambda a, p: p.copy_to_host().sum(),      # the partial sums, finished on the host
    reference=lambda a, p: a.sum(),
    check=lambda total, expected: np.isclose(total, expected, rtol=1e-4),
    bytes_per_element=4)                            # read each element once

# --- Example 5: histogram ------------------------------------------------------------------


def _bins(n):
    return np.random.RandomState(0).randint(0, histogram.NUM_BINS, n).astype(np.int32)


def _histogram(name, kernel):
    return vector_case(
        name, arrays=lambda n: (_bins(n), np.zeros(histogram.NUM_BINS, np.int32)),
        launch=lambda d, h: kernel[min(256, blocks(d.size, 128)), 128](d, h),
        reference=lambda d, h: np.bincount(d, minlength=histogram.NUM_BINS),
        check=np.array_equal, bytes_per_element=4)


HISTOGRAM_GLOBAL = _histogram("Histogram, atomics in global memory (example 5)",
                              histogram.histo_global)
HISTOGRAM_SHARED = _histogram("Histogram, private to the block in shared memory (example 5)",
                              histogram.histo_shared)

# --- Example 6: heat equation --------------------------------------------------------------

#: Time steps per measurement; even, so the final result is in the first array.
STEPS = 20


def _hot_square(n):
    u = np.zeros((n, n), np.float32)
    u[n // 4: 3 * n // 4, n // 4: 3 * n // 4] = 100.0
    return u


def _time_steps(u, v):
    grid = (blocks(u.shape[1], 16), blocks(u.shape[0], 16))
    for _ in range(STEPS):
        heat.time_step[grid, (16, 16)](u, v, np.float32(0.2))
        u, v = v, u


HEAT = square_case(
    f"Heat equation, {STEPS} time steps (example 6)",
    arrays=lambda n: (_hot_square(n), _hot_square(n)),
    launch=_time_steps, fetch=lambda u, v: u.copy_to_host(),
    reference=lambda u, v: heat.heat_numpy(u, STEPS),
    sizes=MATRICES, simulator_sizes=MATRICES_SIMULATOR[:2], what="grid",
    check=lambda u, expected: np.allclose(u, expected, atol=1e-3),
    bytes_moved=lambda n: STEPS * 2 * 4 * n * n)    # per step: read u, write v

# --- Example 7: Mandelbrot -----------------------------------------------------------------

#: Maximum iterations per point, and window of the complex plane.
MAX_ITER = 100
WINDOW = (np.float32(-2.0), np.float32(1.0), np.float32(-1.5), np.float32(1.5))


def _mandelbrot_gpu(image):
    height, width = image.shape
    mandelbrot.mandelbrot[(blocks(width, 16), blocks(height, 16)), (16, 16)](
        image, *WINDOW, np.int32(MAX_ITER))


def mandelbrot_numpy(image):
    """The same computation with NumPy: every point advances together, iteration by iteration."""
    height, width = image.shape
    xmin, xmax, ymin, ymax = WINDOW
    cr = xmin + np.arange(width, dtype=np.float32) * (xmax - xmin) / np.float32(width)
    ci = ymin + np.arange(height, dtype=np.float32) * (ymax - ymin) / np.float32(height)
    cr, ci = np.broadcast_to(cr, image.shape), np.broadcast_to(ci[:, None], image.shape)
    zr, zi = np.zeros(image.shape, np.float32), np.zeros(image.shape, np.float32)
    counts = np.full(image.shape, MAX_ITER, np.int32)
    active = np.ones(image.shape, bool)
    with np.errstate(over="ignore", invalid="ignore"):   # escaped points diverge
        for k in range(MAX_ITER):
            escaped = active & (zr * zr + zi * zi > 4)
            counts[escaped] = k
            active &= ~escaped
            zr, zi = zr * zr - zi * zi + cr, 2 * zr * zi + ci
    return counts


MANDELBROT = square_case(
    f"Mandelbrot set, at most {MAX_ITER} iterations (example 7)",
    arrays=lambda n: (np.zeros((n, n), np.int32),),
    launch=_mandelbrot_gpu, reference=mandelbrot_numpy,
    sizes=IMAGES, simulator_sizes=IMAGES_SIMULATOR, what="image",
    # float32 rounding can change the fate of a few points on the border of the set
    check=lambda image, expected: np.mean(image == expected) >= 0.99)

# --- Example 9: transfers ------------------------------------------------------------------

TRANSFERS = vector_case(
    "Host ↔ device transfers and a minimal kernel (example 9)",
    arrays=lambda n: (random_array(n),),
    launch=lambda a: streams.scale[blocks(a.size), THREADS](a, np.float32(2)),
    reference=lambda a: a * np.float32(2),
    bytes_per_element=2 * 4)                        # read and write each element

# --- Example 10: dynamic shared memory and constant memory ---------------------------------


def _smooth(a, output, positives):
    smoothing.smooth[positives.size, THREADS, 0, THREADS * 4](a, output, positives)


SMOOTHING = vector_case(
    "Smoothing, dynamic shared memory and constant memory (example 10)",
    arrays=lambda n: (random_array(n), np.zeros(n, np.float32), np.zeros(n // THREADS, np.int32)),
    launch=_smooth, fetch=lambda a, output, positives: output.copy_to_host(),
    reference=lambda a, output, positives: smoothing.smooth_numpy(a, THREADS),
    bytes_per_element=2 * 4)

#: Every benchmark, in the order of the examples.
ALL = (ADDITION, SAXPY_GRID_STRIDE, SAXPY_ONE_THREAD_PER_ELEMENT, MATMUL_NAIVE, MATMUL_TILED,
       REDUCTION, HISTOGRAM_GLOBAL, HISTOGRAM_SHARED, HEAT, MANDELBROT, TRANSFERS, SMOOTHING)


def main():
    """Measure every benchmark on the chosen device; 0 if every result is correct."""
    choose_device()
    limit = 1 if "--quick" in sys.argv[1:] else None
    all_correct = True
    for case in ALL:
        results = benchmark.run(case, plan=benchmark.Plan(limit=limit))
        print(benchmark.format_table(results))
        print(benchmark.summarize(results), end="\n\n")
        all_correct = all_correct and all(r.correct for r in results)
    return 0 if all_correct else 1


if __name__ == "__main__":
    sys.exit(main())
