Shared Code

by dorsa.am18·14 views·Oct 25, 2026Open in Playground →
main.cu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
#include <cuda_runtime.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>

#define CUDA(call)                                                           \
    do {                                                                     \
        cudaError_t status = (call);                                         \
        if (status != cudaSuccess) {                                         \
            fprintf(stderr, "CUDA error: %s\n", cudaGetErrorString(status)); \
            exit(EXIT_FAILURE);                                              \
        }                                                                    \
    } while (0)

constexpr int TILE = 16;
using Clock = std::chrono::steady_clock;

__global__ void matmulGPU(const float* A, const float* B, float* C, int m, int k, int n) {
    __shared__ float As[TILE][TILE];
    __shared__ float Bs[TILE][TILE];

    int tx = threadIdx.x;
    int ty = threadIdx.y;
    int row = blockIdx.y * TILE + ty;
    int col = blockIdx.x * TILE + tx;

    float sum = 0.0f;

    for (int base = 0; base < k; base += TILE) {
        As[ty][tx] = (row < m && base + tx < k) ? A[row * k + base + tx] : 0.0f;

        Bs[ty][tx] = (base + ty < k && col < n) ? B[(base + ty) * n + col] : 0.0f;

        __syncthreads();

        for (int p = 0; p < TILE; ++p) sum += As[ty][p] * Bs[p][tx];

        __syncthreads();
    }

    if (row < m && col < n) C[row * n + col] = sum;
}

void matmulCPU(const float* A, const float* B, float* C, int m, int k, int n) {
    std::fill(C, C + static_cast<size_t>(m) * n, 0.0f);

    for (int i = 0; i < m; ++i) {
        for (int p = 0; p < k; ++p) {
            float a = A[i * k + p];

            for (int j = 0; j < n; ++j) C[i * n + j] += a * B[p * n + j];
        }
    }
}

bool runTest(const char* name, int m, int k, int n) {
    size_t aCount = static_cast<size_t>(m) * k;
    size_t bCount = static_cast<size_t>(k) * n;
    size_t cCount = static_cast<size_t>(m) * n;

    size_t aBytes = aCount * sizeof(float);
    size_t bBytes = bCount * sizeof(float);
    size_t cBytes = cCount * sizeof(float);

    float* A = static_cast<float*>(malloc(aBytes));
    float* B = static_cast<float*>(malloc(bBytes));
    float* cpuC = static_cast<float*>(malloc(cBytes));
    float* gpuC = static_cast<float*>(malloc(cBytes));

    if (!A || !B || !cpuC || !gpuC) {
        fprintf(stderr, "Not enough CPU memory for %s.\n", name);
        free(A);
        free(B);
        free(cpuC);
        free(gpuC);
        return false;
    }

    float *dA = nullptr, *dB = nullptr, *dC = nullptr;

    CUDA(cudaMalloc(reinterpret_cast<void**>(&dA), aBytes));
    CUDA(cudaMalloc(reinterpret_cast<void**>(&dB), bBytes));
    CUDA(cudaMalloc(reinterpret_cast<void**>(&dC), cBytes));

    for (size_t i = 0; i < aCount; ++i) A[i] = static_cast<float>(rand()) / RAND_MAX;

    for (size_t i = 0; i < bCount; ++i) B[i] = static_cast<float>(rand()) / RAND_MAX;

    dim3 block(TILE, TILE);
    dim3 grid((n + TILE - 1) / TILE, (m + TILE - 1) / TILE);

    // GPU warm-up: excluded from timing.
    CUDA(cudaMemcpy(dA, A, aBytes, cudaMemcpyHostToDevice));
    CUDA(cudaMemcpy(dB, B, bBytes, cudaMemcpyHostToDevice));

    matmulGPU<<<grid, block>>>(dA, dB, dC, m, k, n);
    CUDA(cudaGetLastError());
    CUDA(cudaDeviceSynchronize());

    // CPU timing.
    auto cpuStart = Clock::now();

    matmulCPU(A, B, cpuC, m, k, n);

    double cpuMs = std::chrono::duration<double, std::milli>(Clock::now() - cpuStart).count();

    cudaEvent_t start, stop;
    CUDA(cudaEventCreate(&start));
    CUDA(cudaEventCreate(&stop));

    // GPU total timing: copies + computation.
    auto gpuStart = Clock::now();

    CUDA(cudaMemcpy(dA, A, aBytes, cudaMemcpyHostToDevice));
    CUDA(cudaMemcpy(dB, B, bBytes, cudaMemcpyHostToDevice));

    CUDA(cudaEventRecord(start));

    matmulGPU<<<grid, block>>>(dA, dB, dC, m, k, n);
    CUDA(cudaGetLastError());

    CUDA(cudaEventRecord(stop));
    CUDA(cudaEventSynchronize(stop));

    CUDA(cudaMemcpy(gpuC, dC, cBytes, cudaMemcpyDeviceToHost));

    double gpuTotalMs = std::chrono::duration<double, std::milli>(Clock::now() - gpuStart).count();

    float gpuKernelMs = 0.0f;
    CUDA(cudaEventElapsedTime(&gpuKernelMs, start, stop));

    // Validate every output element.
    bool correct = true;
    double maxError = 0.0;

    for (size_t i = 0; i < cCount; ++i) {
        double error = std::fabs(static_cast<double>(cpuC[i]) - gpuC[i]);

        maxError = std::max(maxError, error);

        double tolerance = 1e-3 + 1e-4 * std::fabs(cpuC[i]);

        if (!std::isfinite(gpuC[i]) || error > tolerance) correct = false;
    }

    printf("\n%s: A(%d x %d) * B(%d x %d) = C(%d x %d)\n", name, m, k, k, n, m, n);

    printf("Operations (2*m*k*n): %.0f\n", 2.0 * m * k * n);
    printf("CPU time:             %.3f ms\n", cpuMs);
    printf("GPU kernel time:      %.3f ms\n", gpuKernelMs);
    printf("GPU total time:       %.3f ms\n", gpuTotalMs);

    printf("Speedup (kernel):     %.2fx\n", gpuKernelMs > 0 ? cpuMs / gpuKernelMs : 0.0);

    printf("Speedup (total):      %.2fx\n", gpuTotalMs > 0 ? cpuMs / gpuTotalMs : 0.0);

    printf("Check: %s | Max absolute error: %.6g\n", correct ? "PASS" : "FAIL", maxError);

    printf("C[0,0] = %.6f\n", gpuC[0]);

    CUDA(cudaEventDestroy(start));
    CUDA(cudaEventDestroy(stop));

    CUDA(cudaFree(dA));
    CUDA(cudaFree(dB));
    CUDA(cudaFree(dC));

    free(A);
    free(B);
    free(cpuC);
    free(gpuC);

    return correct;
}

int main() {
    CUDA(cudaSetDevice(0));

    cudaDeviceProp prop;
    CUDA(cudaGetDeviceProperties(&prop, 0));

    printf("GPU: %s\n", prop.name);
    printf("GPU total = input copies + kernel + output copy.\n");
    printf("Allocation, initialization and warm-up are excluded.\n");

    srand(42);

    bool smallOK = runTest("Small", 128, 256, 192);
    bool mediumOK = runTest("Medium", 512, 768, 384);
    bool largeOK = runTest("Large", 1024, 1536, 768);

    return (smallOK && mediumOK && largeOK) ? EXIT_SUCCESS : EXIT_FAILURE;
}

Comments (0)

to post comments and vote
No comments yet. Be the first to share your thoughts!