"""Example 2 — SAXPY with a "grid-stride" loop, and forall.

A grid of fixed size processes an array of any size: each thread moves on
by steps of ``gridsize`` (the total number of threads).

    python examples/02_saxpy_grid_stride.py [device]
"""

import time

import numpy as np
from common import choose_device, size

import unigpu as gpu


@gpu.jit("void(float32, float32[:], float32[:])")   # numba-style signature
def saxpy(alpha, x, y):
    for i in range(gpu.grid(1), x.size, gpu.gridsize(1)):
        y[i] = alpha * x[i] + y[i]


@gpu.jit
def saxpy_simple(alpha, x, y):
    i = gpu.grid(1)
    if i < x.size:
        y[i] = alpha * x[i] + y[i]


def main():
    """Run the example on the device given as an argument (the best one otherwise)."""
    choose_device()
    n = size(1 << 22, 5_000)
    x = np.random.rand(n).astype(np.float32)
    y = np.random.rand(n).astype(np.float32)
    d_x, d_y = gpu.to_device(x), gpu.to_device(y)

    saxpy[32, 256](2.0, d_x, d_y)          # first call: compilation
    gpu.synchronize()
    d_y.copy_to_device(y)

    t0 = time.perf_counter()
    saxpy[32, 256](2.0, d_x, d_y)
    gpu.synchronize()                      # launches are asynchronous!
    duration = time.perf_counter() - t0
    assert np.allclose(d_y.copy_to_host(), 2.0 * x + y)
    print(f"grid-stride: {n} elements in {duration * 1e3:.2f} ms "
          f"({3 * 4 * n / duration / 1e9:.1f} GB/s)")

    # forall: unigpu chooses the grid that covers n tasks
    d_y.copy_to_device(y)
    saxpy_simple.forall(n)(np.float32(2.0), d_x, d_y)
    assert np.allclose(d_y.copy_to_host(), 2.0 * x + y)
    print("forall: OK")


if __name__ == "__main__":
    main()
