"""Example 4 — Reduction (sum) in shared memory.

Each block reduces its part of the array in log2(BLOCK) steps; the partial
sums are then added up on the host.

Concepts: shared memory, syncthreads, tree reduction, divergence.

    python examples/04_reduction.py [device]
"""

import numpy as np
from common import choose_device, size

import unigpu as gpu

BLOCK = 256


@gpu.jit
def block_sum(a, partial_sums):
    cache = gpu.shared.array(BLOCK, gpu.float32)
    tid = gpu.threadIdx.x
    acc = gpu.float32(0)
    for i in range(gpu.grid(1), a.size, gpu.gridsize(1)):   # grid-stride
        acc += a[i]
    cache[tid] = acc
    gpu.syncthreads()
    s = BLOCK // 2
    while s > 0:                     # 256 -> 128 -> ... -> 1
        if tid < s:
            cache[tid] += cache[tid + s]
        gpu.syncthreads()            # outside the if: every thread reaches it
        s //= 2
    if tid == 0:
        partial_sums[gpu.blockIdx.x] = cache[0]


def main():
    """Run the example on the device given as an argument (the best one otherwise)."""
    choose_device()
    n = size(10_000_000, 4_000)
    blocks = size(64, 4)
    a = np.random.rand(n).astype(np.float32)
    d_partial_sums = gpu.device_array(blocks, np.float32)
    block_sum[blocks, BLOCK](gpu.to_device(a), d_partial_sums)
    total = d_partial_sums.copy_to_host().sum()
    print(f"GPU: {total:.3f}   NumPy: {a.sum(dtype=np.float64):.3f}")


if __name__ == "__main__":
    main()
