openaccel-lab
aien-dev/openaccel-lab
Brought by drakestapleton
openaccel-lab / controls / reduce_drop_last / kernel.cu
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // CONTROL (deliberately wrong): pass 1 reads x[0..n-2] only, dropping the last element. |
| 3 | // Pass 1: each block of 256 sums its slice in a shared-memory tree and writes one partial. |
| 4 | // Pass 2: one block sums the nb partials (strided, then a tree) into y[0]. |
| 5 | #include <cuda_runtime.h> |
| 6 | |
| 7 | #define OAL_B 256 |
| 8 | |
| 9 | __global__ void rsum_part(const float *x, float *part, long long n) |
| 10 | { |
| 11 | __shared__ float s[OAL_B]; |
| 12 | int l = threadIdx.x; |
| 13 | long long i = (long long)blockIdx.x * OAL_B + l; |
| 14 | s[l] = i < n - 1 ? x[i] : 0.0f; |
| 15 | __syncthreads(); |
| 16 | for (int k = OAL_B / 2; k > 0; k >>= 1) { |
| 17 | if (l < k) |
| 18 | s[l] += s[l + k]; |
| 19 | __syncthreads(); |
| 20 | } |
| 21 | if (l == 0) |
| 22 | part[blockIdx.x] = s[0]; |
| 23 | } |
| 24 | |
| 25 | __global__ void rsum_fin(const float *part, float *y, long long nb) |
| 26 | { |
| 27 | __shared__ float s[OAL_B]; |
| 28 | int l = threadIdx.x; |
| 29 | float a = 0.0f; |
| 30 | for (long long j = l; j < nb; j += OAL_B) |
| 31 | a += part[j]; |
| 32 | s[l] = a; |
| 33 | __syncthreads(); |
| 34 | for (int k = OAL_B / 2; k > 0; k >>= 1) { |
| 35 | if (l < k) |
| 36 | s[l] += s[l + k]; |
| 37 | __syncthreads(); |
| 38 | } |
| 39 | if (l == 0) |
| 40 | y[0] = s[0]; |
| 41 | } |
| 42 | |
| 43 | void oal_launch(const long long *p, void *const *buf) |
| 44 | { |
| 45 | long long n = p[0], nb = p[1]; |
| 46 | rsum_part<<<(unsigned)nb, OAL_B>>>((const float *)buf[0], (float *)buf[2], n); |
| 47 | rsum_fin<<<1, OAL_B>>>((const float *)buf[2], (float *)buf[1], nb); |
| 48 | } |