#include <hip/hip_runtime.h>
#include <array>
#include <cassert>
#include <cstdlib>
#include <iostream>
void check(hipError_t error) {
if (error != hipSuccess) {
std::cerr << hipGetErrorString(error) << std::endl;
std::exit(1);
}
}
__global__ void matmul2(const float* A, const float* B, float* C) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
if (row < 2 && col < 2) {
float sum = 0.0f;
for (int k = 0; k < 2; ++k)
sum += A[row * 2 + k] * B[k * 2 + col];
C[row * 2 + col] = sum;
}
}
int main() {
std::array<float, 4> hA{1, 2, 3, 4};
std::array<float, 4> hB{5, 6, 7, 8};
std::array<float, 4> hC{};
constexpr size_t bytes = 4 * sizeof(float);
float *dA = nullptr, *dB = nullptr, *dC = nullptr;
check(hipSetDevice(0));
check(hipMalloc(reinterpret_cast<void**>(&dA), bytes));
check(hipMalloc(reinterpret_cast<void**>(&dB), bytes));
check(hipMalloc(reinterpret_cast<void**>(&dC), bytes));
check(hipMemcpy(dA, hA.data(), bytes, hipMemcpyHostToDevice));
check(hipMemcpy(dB, hB.data(), bytes, hipMemcpyHostToDevice));
hipLaunchKernelGGL(matmul2, dim3(1, 1), dim3(2, 2), 0, 0,
dA, dB, dC);
check(hipGetLastError());
check(hipDeviceSynchronize());
check(hipMemcpy(hC.data(), dC, bytes, hipMemcpyDeviceToHost));
assert((hC == std::array<float, 4>{19, 22, 43, 50}));
std::cout << "PASS: [" << hC[0] << ", " << hC[1]
<< ", " << hC[2] << ", " << hC[3] << "]"
<< std::endl;
check(hipFree(dA));
check(hipFree(dB));
check(hipFree(dC));
}