void saxpy(float a, float* x, float* y, int n) {
int i = block_idx * block_dim + thread_idx;
if (i < n) {
y[i] = a * x[i] + y[i];
}
}
void sum_reduce(const float* in, float* out, int n) {
float buf[32];
int tid = thread_idx;
buf[tid] = (tid < n) ? in[tid] : 0.0f;
group.sync();
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;
cudaMalloc((void**)&dx, N * sizeof(float));
cudaMalloc((void**)&dy, N * sizeof(float));
dim3 grid(N / 256);
dim3 block(256);
{ let _kernel = modules.get_function("saxpy"); unsafe { let _ = launch!( _kernel<<<grid as grid_size, block as block_size, 0 as usize, default>>>(2.0f, dx, dy, N) ); } };
float* out = nullptr;
cudaMalloc((void**)&out, sizeof(float));
{ let _kernel = modules.get_function("sum_reduce"); unsafe { let _ = launch!( _kernel<<<1 as grid_size, 32 as block_size, 0 as usize, default>>>(dx, out, N) ); } };
cudaDeviceSynchronize();
cudaFree(dx);
cudaFree(dy);
cudaFree(out);
return 0;
}