#include <hip/hip_runtime.h>
__global__ void saxpy(float a, float* x, float* y, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
y[i] = a * x[i] + y[i];
}
}
__global__ void sum_reduce(const float* in, float* out, int n) {
__shared__ float buf[32];
int tid = threadIdx.x;
buf[tid] = (tid < n) ? in[tid] : 0.0f;
__syncthreads();
if (tid == 0) {
float s = 0.0f;
for (int i = 0; i < 32; ++i) s += buf[i];
*out = s;
}
}
int main(void) {
const int N = 1024;
float *dx = nullptr, *dy = nullptr;
hipMalloc((void**)&dx, N * sizeof(float));
hipMalloc((void**)&dy, N * sizeof(float));
dim3 grid(N / 256);
dim3 block(256);
hipLaunchKernelGGL(saxpy, dim3(grid), dim3(block), 0, 0, 2.0f, dx, dy, N);
float* out = nullptr;
hipMalloc((void**)&out, sizeof(float));
hipLaunchKernelGGL(sum_reduce, dim3(1), dim3(32), 0, 0, dx, out, N);
hipDeviceSynchronize();
hipFree(dx);
hipFree(dy);
hipFree(out);
return 0;
}