openaccel-lab
aien-dev/openaccel-lab
Brought by drakestapleton
openaccel-lab / workloads / argmax / kernel.cu
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // (value, index) pairs; (v2, i2) beats (v1, i1) when v2 > v1, or v2 == v1 and i2 < i1 (first maximum). |
| 3 | // Pass 1: each block of 256 reduces its slice in shared memory. Pass 2: one block reduces the nb |
| 4 | // partials. Padding is (-INFINITY, INT_MAX), which never beats a real element. |
| 5 | #include <cuda_runtime.h> |
| 6 | #include <limits.h> |
| 7 | #include <math.h> |
| 8 | |
| 9 | #define OAL_B 256 |
| 10 | #define OAL_BEATS(v2, i2, v1, i1) ((v2) > (v1) || ((v2) == (v1) && (i2) < (i1))) |
| 11 | |
| 12 | __global__ void amax_part(const float *x, float *pval, int *pidx, long long n) |
| 13 | { |
| 14 | __shared__ float sv[OAL_B]; |
| 15 | __shared__ int si[OAL_B]; |
| 16 | int l = threadIdx.x; |
| 17 | long long i = (long long)blockIdx.x * OAL_B + l; |
| 18 | sv[l] = i < n ? x[i] : -INFINITY; |
| 19 | si[l] = i < n ? (int)i : INT_MAX; |
| 20 | __syncthreads(); |
| 21 | for (int k = OAL_B / 2; k > 0; k >>= 1) { |
| 22 | if (l < k && OAL_BEATS(sv[l + k], si[l + k], sv[l], si[l])) { |
| 23 | sv[l] = sv[l + k]; |
| 24 | si[l] = si[l + k]; |
| 25 | } |
| 26 | __syncthreads(); |
| 27 | } |
| 28 | if (l == 0) { |
| 29 | pval[blockIdx.x] = sv[0]; |
| 30 | pidx[blockIdx.x] = si[0]; |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | __global__ void amax_fin(const float *pval, const int *pidx, int *y, long long nb) |
| 35 | { |
| 36 | __shared__ float sv[OAL_B]; |
| 37 | __shared__ int si[OAL_B]; |
| 38 | int l = threadIdx.x; |
| 39 | float bv = -INFINITY; |
| 40 | int bi = INT_MAX; |
| 41 | for (long long j = l; j < nb; j += OAL_B) { |
| 42 | if (OAL_BEATS(pval[j], pidx[j], bv, bi)) { |
| 43 | bv = pval[j]; |
| 44 | bi = pidx[j]; |
| 45 | } |
| 46 | } |
| 47 | sv[l] = bv; |
| 48 | si[l] = bi; |
| 49 | __syncthreads(); |
| 50 | for (int k = OAL_B / 2; k > 0; k >>= 1) { |
| 51 | if (l < k && OAL_BEATS(sv[l + k], si[l + k], sv[l], si[l])) { |
| 52 | sv[l] = sv[l + k]; |
| 53 | si[l] = si[l + k]; |
| 54 | } |
| 55 | __syncthreads(); |
| 56 | } |
| 57 | if (l == 0) |
| 58 | y[0] = si[0]; |
| 59 | } |
| 60 | |
| 61 | void oal_launch(const long long *p, void *const *buf) |
| 62 | { |
| 63 | long long n = p[0], nb = p[1]; |
| 64 | amax_part<<<(unsigned)nb, OAL_B>>>((const float *)buf[0], (float *)buf[2], (int *)buf[3], n); |
| 65 | amax_fin<<<1, OAL_B>>>((const float *)buf[2], (const int *)buf[3], (int *)buf[1], nb); |
| 66 | } |