Shared Code

by dorsa.am18·7 views·Nov 13, 2026Open in Playground →
main.cu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
#include <cuda_runtime.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <limits>
#include <vector>

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

constexpr int TILE = 16;
constexpr int WARMUP = 2;
constexpr int CPU_TRIALS = 3;
constexpr int GPU_TRIALS = 5;
constexpr int KERNEL_REPEATS = 20;

using Clock = std::chrono::steady_clock;

// ------------------------------------------------------------
// GPU without tiling
// Each thread computes one output element.
// ------------------------------------------------------------
__global__ void matmulNaive(
    const float* A,
    const float* B,
    float* C,
    int m,
    int k,
    int n
) {
    int row = blockIdx.y * blockDim.y + threadIdx.y;
    int col = blockIdx.x * blockDim.x + threadIdx.x;

    if (row < m && col < n) {
        float sum = 0.0f;

        for (int p = 0; p < k; ++p) {
            sum += A[row * k + p] * B[p * n + col];
        }

        C[row * n + col] = sum;
    }
}

// ------------------------------------------------------------
// GPU with tiling and boundary conditions
// ------------------------------------------------------------
__global__ void matmulTiled(
    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 * blockDim.y + ty;
    int col = blockIdx.x * blockDim.x + tx;

    float sum = 0.0f;

    // Do not return early for threads outside C.
    // Such threads may still be needed to load valid inputs.
    for (int base = 0; base < k; base += TILE) {

        // A has m rows and k columns.
        if (row < m && base + tx < k) {
            As[ty][tx] = A[row * k + base + tx];
        } else {
            As[ty][tx] = 0.0f;
        }

        // B has k rows and n columns.
        if (base + ty < k && col < n) {
            Bs[ty][tx] = B[(base + ty) * n + col];
        } else {
            Bs[ty][tx] = 0.0f;
        }

        // Wait until all threads finish loading the current tiles.
        __syncthreads();

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

        // Wait before overwriting shared memory with the next tiles.
        __syncthreads();
    }

    // C has m rows and n columns.
    if (row < m && col < n) {
        C[row * n + col] = sum;
    }
}

// ------------------------------------------------------------
// CPU reference
// Same loop ordering as the previous program.
// ------------------------------------------------------------
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];
            }
        }
    }
}

// ------------------------------------------------------------
// Launch either GPU version.
// ------------------------------------------------------------
void launch(
    bool tiled,
    dim3 grid,
    dim3 block,
    const float* A,
    const float* B,
    float* C,
    int m,
    int k,
    int n
) {
    if (tiled) {
        matmulTiled<<<grid, block>>>(A, B, C, m, k, n);
    } else {
        matmulNaive<<<grid, block>>>(A, B, C, m, k, n);
    }
}

double median(std::vector<double> values) {
    std::sort(values.begin(), values.end());
    return values[values.size() / 2];
}

// ------------------------------------------------------------
// Validate every output element.
// ------------------------------------------------------------
bool check(
    const char* label,
    const std::vector<float>& reference,
    const std::vector<float>& actual
) {
    bool ok = true;
    double maxError = 0.0;

    for (size_t i = 0; i < reference.size(); ++i) {
        if (!std::isfinite(reference[i]) ||
            !std::isfinite(actual[i])) {
            ok = false;
            maxError = std::numeric_limits<double>::infinity();
            continue;
        }

        double error =
            std::fabs(static_cast<double>(reference[i]) - actual[i]);

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

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

        if (error > tolerance) {
            ok = false;
        }
    }

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

    return ok;
}

// ------------------------------------------------------------
// Kernel timing using CUDA events.
// Returns average milliseconds per launch for one trial.
// ------------------------------------------------------------
double kernelTime(
    bool tiled,
    dim3 grid,
    dim3 block,
    const float* A,
    const float* B,
    float* C,
    int m,
    int k,
    int n,
    cudaEvent_t start,
    cudaEvent_t stop
) {
    CUDA(cudaEventRecord(start));

    for (int r = 0; r < KERNEL_REPEATS; ++r) {
        launch(tiled, grid, block, A, B, C, m, k, n);
    }

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

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

    return elapsed / KERNEL_REPEATS;
}

// ------------------------------------------------------------
// Total GPU time:
// input copies + one kernel launch + output copy.
// ------------------------------------------------------------
double totalTime(
    bool tiled,
    dim3 grid,
    dim3 block,
    const std::vector<float>& A,
    const std::vector<float>& B,
    std::vector<float>& C,
    float* dA,
    float* dB,
    float* dC,
    int m,
    int k,
    int n
) {
    // Outside the timed interval.
    CUDA(cudaDeviceSynchronize());

    auto start = Clock::now();

    CUDA(cudaMemcpy(
        dA,
        A.data(),
        A.size() * sizeof(float),
        cudaMemcpyHostToDevice
    ));

    CUDA(cudaMemcpy(
        dB,
        B.data(),
        B.size() * sizeof(float),
        cudaMemcpyHostToDevice
    ));

    launch(tiled, grid, block, dA, dB, dC, m, k, n);
    CUDA(cudaGetLastError());

    // Blocking copy: waits for the kernel and returns the output.
    CUDA(cudaMemcpy(
        C.data(),
        dC,
        C.size() * sizeof(float),
        cudaMemcpyDeviceToHost
    ));

    return std::chrono::duration<double, std::milli>(
        Clock::now() - start
    ).count();
}

struct Result {
    const char* name;
    int m, k, n;

    double cpu;
    double naiveKernel;
    double tiledKernel;
    double naiveTotal;
    double tiledTotal;

    bool ok;
};

// ------------------------------------------------------------
// Run one matrix size.
// ------------------------------------------------------------
Result runCase(
    const char* name,
    int m,
    int k,
    int n,
    bool benchmark
) {
    Result out = {
        name, m, k, n,
        0, 0, 0, 0, 0,
        false
    };

    std::vector<float> A(static_cast<size_t>(m) * k);
    std::vector<float> B(static_cast<size_t>(k) * n);

    std::vector<float> reference(static_cast<size_t>(m) * n);
    std::vector<float> naive(reference.size());
    std::vector<float> tiled(reference.size());

    for (size_t i = 0; i < A.size(); ++i) {
        A[i] = float(rand()) / RAND_MAX;
    }

    for (size_t i = 0; i < B.size(); ++i) {
        B[i] = float(rand()) / RAND_MAX;
    }

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

    CUDA(cudaMalloc(
        reinterpret_cast<void**>(&dA),
        A.size() * sizeof(float)
    ));

    CUDA(cudaMalloc(
        reinterpret_cast<void**>(&dB),
        B.size() * sizeof(float)
    ));

    CUDA(cudaMalloc(
        reinterpret_cast<void**>(&dC),
        reference.size() * sizeof(float)
    ));

    dim3 block(TILE, TILE);

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

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

    // CPU timing.
    std::vector<double> cpuTimes;

    for (int r = 0; r < (benchmark ? CPU_TRIALS : 1); ++r) {
        auto start = Clock::now();

        matmulCPU(
            A.data(), B.data(), reference.data(),
            m, k, n
        );

        cpuTimes.push_back(
            std::chrono::duration<double, std::milli>(
                Clock::now() - start
            ).count()
        );
    }

    out.cpu = median(cpuTimes);

    CUDA(cudaMemcpy(
        dA,
        A.data(),
        A.size() * sizeof(float),
        cudaMemcpyHostToDevice
    ));

    CUDA(cudaMemcpy(
        dB,
        B.data(),
        B.size() * sizeof(float),
        cudaMemcpyHostToDevice
    ));

    // Initialize output with NaN bit patterns before validation.
    // Missing output writes will therefore fail the check.
    CUDA(cudaMemset(
        dC, 0xff, reference.size() * sizeof(float)
    ));

    launch(false, grid, block, dA, dB, dC, m, k, n);
    CUDA(cudaGetLastError());

    CUDA(cudaMemcpy(
        naive.data(),
        dC,
        naive.size() * sizeof(float),
        cudaMemcpyDeviceToHost
    ));

    CUDA(cudaMemset(
        dC, 0xff, reference.size() * sizeof(float)
    ));

    launch(true, grid, block, dA, dB, dC, m, k, n);
    CUDA(cudaGetLastError());

    CUDA(cudaMemcpy(
        tiled.data(),
        dC,
        tiled.size() * sizeof(float),
        cudaMemcpyDeviceToHost
    ));

    bool naiveOK = check("Naive vs CPU", reference, naive);
    bool tiledOK = check("Tiled vs CPU", reference, tiled);
    bool agree = check("Tiled vs Naive", naive, tiled);

    out.ok = naiveOK && tiledOK && agree;

    if (benchmark && out.ok) {

        // GPU warm-up: excluded from timing.
        for (int r = 0; r < WARMUP; ++r) {
            launch(false, grid, block, dA, dB, dC, m, k, n);
            launch(true, grid, block, dA, dB, dC, m, k, n);
        }

        CUDA(cudaGetLastError());
        CUDA(cudaDeviceSynchronize());

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

        // Index 0: naive; index 1: tiled.
        std::vector<double> kernel[2];
        std::vector<double> total[2];

        for (int r = 0; r < GPU_TRIALS; ++r) {

            // Alternate order to reduce first/second-run bias.
            for (int order = 0; order < 2; ++order) {
                int which = (r + order) % 2;

                kernel[which].push_back(
                    kernelTime(
                        which == 1,
                        grid, block,
                        dA, dB, dC,
                        m, k, n,
                        start, stop
                    )
                );
            }

            for (int order = 0; order < 2; ++order) {
                int which = (r + order) % 2;

                total[which].push_back(
                    totalTime(
                        which == 1,
                        grid, block,
                        A, B,
                        which == 1 ? tiled : naive,
                        dA, dB, dC,
                        m, k, n
                    )
                );
            }
        }

        out.naiveKernel = median(kernel[0]);
        out.tiledKernel = median(kernel[1]);
        out.naiveTotal = median(total[0]);
        out.tiledTotal = median(total[1]);

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

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

    return out;
}

// ------------------------------------------------------------
// Main
// ------------------------------------------------------------
int main() {
    setvbuf(stdout, nullptr, _IONBF, 0);

    CUDA(cudaSetDevice(0));

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

    printf(
        "GPU: %s | Compute capability: %d.%d\n",
        prop.name, prop.major, prop.minor
    );

    printf(
        "TILE=%d | Same %dx%d block for both GPU versions\n",
        TILE, TILE, TILE
    );

    printf(
        "CPU: median of %d runs; GPU: median of %d trials\n",
        CPU_TRIALS, GPU_TRIALS
    );

    printf(
        "Kernel: event time per launch, averaged over "
        "%d launches per trial\n",
        KERNEL_REPEATS
    );

    printf(
        "Total: H2D copies + one kernel launch + D2H copy "
        "(host wall time)\n"
    );

    printf(
        "Allocation, input generation, validation and "
        "warm-up are excluded.\n"
    );

    printf(
        "Tolerance: abs(error) <= "
        "1e-3 + 1e-4 * abs(reference)\n"
    );

    srand(42);

    Result results[] = {
        runCase("Small", 128, 256, 192, true),
        runCase("Medium", 512, 768, 384, true),
        runCase("Large", 1024, 1536, 768, true)
    };

    bool allOK = true;

    for (const Result& r : results) {
        allOK = r.ok && allOK;
    }

    // Main timing table.
    printf(
        "\nTIMING TABLE "
        "(milliseconds; NaN means validation failed)\n"
    );

    printf(
        "Case,m,k,n,CPU_ms,"
        "Naive_kernel_ms,Tiled_kernel_ms,"
        "Naive_total_ms,Tiled_total_ms,Check\n"
    );

    for (const Result& r : results) {
        double bad = std::numeric_limits<double>::quiet_NaN();

        printf(
            "%s,%d,%d,%d,%.6f,%.6f,%.6f,%.6f,%.6f,%s\n",
            r.name,
            r.m,
            r.k,
            r.n,
            r.cpu,
            r.ok ? r.naiveKernel : bad,
            r.ok ? r.tiledKernel : bad,
            r.ok ? r.naiveTotal : bad,
            r.ok ? r.tiledTotal : bad,
            r.ok ? "PASS" : "FAIL"
        );
    }

    // Speedup table.
    printf("\nSPEEDUP TABLE\n");

    printf(
        "Case,CPU_over_Tiled_total,"
        "Tiling_kernel_speedup,"
        "Tiling_total_speedup,"
        "Kernel_time_reduction_percent\n"
    );

    for (const Result& r : results) {
        if (!r.ok) {
            continue;
        }

        printf(
            "%s,%.4f,%.4f,%.4f,%.2f\n",
            r.name,
            r.cpu / r.tiledTotal,
            r.naiveKernel / r.tiledKernel,
            r.naiveTotal / r.tiledTotal,
            100.0 * (1.0 - r.tiledKernel / r.naiveKernel)
        );
    }

    // Additional correctness tests for incomplete tiles.
    // These are not included in the main benchmark table.
    printf(
        "\nBOUNDARY TESTS "
        "(correctness only; outside the timing table)\n"
    );

    const int edges[][3] = {
        {1, 1, 1},
        {3, 5, 7},
        {17, 16, 16},
        {16, 17, 16},
        {16, 16, 17},
        {129, 259, 193}
    };

    for (const auto& dims : edges) {
        Result r = runCase(
            "Boundary",
            dims[0],
            dims[1],
            dims[2],
            false
        );

        allOK = r.ok && allOK;
    }

    printf(
        "\nOVERALL: %s\n",
        allOK ? "PASS" : "FAIL"
    );

    return allOK ? EXIT_SUCCESS : EXIT_FAILURE;
}

Comments (0)

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