#include #include #include #include #define HIP_CHECK(call) do { \ hipError_t error = (call); \ if (error != hipSuccess) { \ std::fprintf(stderr, "%s: %s\n", #call, hipGetErrorString(error)); \ std::exit(1); \ } \ } while (0) #define BLAS_CHECK(call) do { \ rocblas_status status = (call); \ if (status != rocblas_status_success) { \ std::fprintf(stderr, "%s: rocBLAS status %d\n", #call, int(status)); \ std::exit(1); \ } \ } while (0) __global__ void vector_add(const float* a, const float* b, float* result) { int i = blockIdx.x * blockDim.x + threadIdx.x; result[i] = a[i] + b[i]; } int main() { constexpr int count = 1024; float a[count], b[count], result[count]; for (int i = 0; i < count; ++i) { a[i] = float(i); b[i] = float(count - i); } hipDeviceProp_t properties{}; HIP_CHECK(hipGetDeviceProperties(&properties, 0)); float *device_a, *device_b, *device_result; HIP_CHECK(hipMalloc(&device_a, sizeof(a))); HIP_CHECK(hipMalloc(&device_b, sizeof(b))); HIP_CHECK(hipMalloc(&device_result, sizeof(result))); HIP_CHECK(hipMemcpy(device_a, a, sizeof(a), hipMemcpyHostToDevice)); HIP_CHECK(hipMemcpy(device_b, b, sizeof(b), hipMemcpyHostToDevice)); vector_add<<>>(device_a, device_b, device_result); HIP_CHECK(hipGetLastError()); HIP_CHECK(hipMemcpy(result, device_result, sizeof(result), hipMemcpyDeviceToHost)); for (int i = 0; i < count; ++i) { if (result[i] != float(count)) { std::fprintf(stderr, "vector add mismatch at %d: %f\n", i, result[i]); return 1; } } const float matrix_a[] = {1, 3, 2, 4}; const float matrix_b[] = {5, 7, 6, 8}; const float expected[] = {19, 43, 22, 50}; float matrix_result[4]; HIP_CHECK(hipMemcpy(device_a, matrix_a, sizeof(matrix_a), hipMemcpyHostToDevice)); HIP_CHECK(hipMemcpy(device_b, matrix_b, sizeof(matrix_b), hipMemcpyHostToDevice)); rocblas_handle handle; BLAS_CHECK(rocblas_create_handle(&handle)); const float alpha = 1, beta = 0; BLAS_CHECK(rocblas_sgemm(handle, rocblas_operation_none, rocblas_operation_none, 2, 2, 2, &alpha, device_a, 2, device_b, 2, &beta, device_result, 2)); HIP_CHECK(hipMemcpy(matrix_result, device_result, sizeof(matrix_result), hipMemcpyDeviceToHost)); for (int i = 0; i < 4; ++i) { if (matrix_result[i] != expected[i]) { std::fprintf(stderr, "rocBLAS matrix multiply mismatch at %d: %f\n", i, matrix_result[i]); return 1; } } BLAS_CHECK(rocblas_destroy_handle(handle)); HIP_CHECK(hipFree(device_a)); HIP_CHECK(hipFree(device_b)); HIP_CHECK(hipFree(device_result)); std::printf("HIP vector add and rocBLAS matmul OK: %s (%s), %d elements\n", properties.name, properties.gcnArchName, count); }