gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
In CUDA which function can I use to multiply two matrices?
- User
In CUDA which function can I use to multiply two matrices?
- Assistant
In CUDA, you can use the
cublasSgemmfunction to multiply two matrices (single precision) andcublasDgemmfor double precision matrices.Here is a simple example of using
cublasSgemm:#include <stdio.h> #include <stdlib.h> #include <cuda_runtime.h> #include <cublas_v2.h> #define N 3 #define M 4 #define K 5 int main() { float A[N * M] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; float B[M * K] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; float C[N * K] = {0}; cudaError_t cudaStatus; cublasStatus_t cublasStatus; cublasHandle_t handle; // Initialize cublas cublasStatus = cublasCreate(&handle); if (cublasStatus != CUBLAS_STATUS_SUCCESS) { fprintf(stderr, "Failed to create cublas handle\n"); return 1; } // Allocate device memory float *d_A, *d_B, *d_C; cudaMalloc((void**)&d_A, N * M * sizeof(float)); cudaMalloc((void**)&d_B, M * K * sizeof(float)); cudaMalloc((void**)&d_C, N * K * sizeof(float)); // Copy input matrices to device memory cudaMemcpy(d_A, A, N * M * sizeof(float), cudaMemcpyHostToDevice); cudaMemcpy(d_B, B, M * K * sizeof(float), cudaMemcpyHostToDevice); // Matrix multiplication: C = A * B float alpha = 1.0f, beta = 0.0f; cublasStatus = cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, K, N, M, &alpha, d_B, K, d_A, M, &beta, d_C, K); if (cublasStatus != CUBLAS_STATUS_SUCCESS) { fprintf(stderr, "Failed to perform matrix multiplication\n"); return 1; } // Copy result back to host memory cudaMemcpy(C, d_C, N * K * sizeof(float), cudaMemcpyDeviceToHost); // Print result printf("C = \n"); for (int i = 0; i < N; ++i) { for (int j = 0; j < K; ++j) { printf("%6.2f ", C[i * K + j]); } printf("\n"); } // Cleanup cudaFree(d_A); cudaFree(d_B); cudaFree(d_C); cublasDestroy(handle); return 0; }