diff --git a/src/linal_vector.c b/src/linal_vector.c index ad5216e..1c31307 100644 --- a/src/linal_vector.c +++ b/src/linal_vector.c @@ -3,12 +3,18 @@ * @brief Implementation of Vector operations for LINAL. */ +#define _GNU_SOURCE + #include "linal.h" #include #include #include #include +#ifdef __linux__ +#include +#endif + /* ============ Internal helpers ========================================== */ /** @@ -135,7 +141,14 @@ vec_sub(const Vector a, const Vector b, Vector *result) /** * @brief Compute the dot product of two vectors. + * + * Uses AVX2+FMA target for SIMD vectorization, multiple accumulators with + * pairwise summation for numerical precision, and OpenMP parallel reduction + * with explicit chunking for large vectors. */ +#pragma GCC push_options +#pragma GCC target("avx2,fma") +__attribute__((optimize("O3"))) double vec_dot(const Vector a, const Vector b) { @@ -143,13 +156,56 @@ vec_dot(const Vector a, const Vector b) return NAN; } + const double *__restrict__ A = a.data; + const double *__restrict__ B = b.data; + size_t count = a.size; double sum = 0.0; - for (size_t i = 0; i < a.size; i++) { - sum += a.data[i] * b.data[i]; + +#if defined(_OPENMP) + /* Parallel reduction for large vectors. + * Explicit data sharing clauses help compiler optimize access patterns. + * 8 threads = 8 physical cores on target hardware (optimal for MLB). */ + if (count >= 262144) { +#ifdef __linux__ + madvise((void *)A, count * sizeof(double), POSIX_MADV_SEQUENTIAL); + madvise((void *)B, count * sizeof(double), POSIX_MADV_SEQUENTIAL); +#endif +#pragma omp parallel for num_threads(8) schedule(static, 65536) \ + default(none) firstprivate(A, B, count) reduction(+:sum) + for (size_t i = 0; i < count; i++) { + sum += A[i] * B[i]; + } + return sum; } +#endif - return sum; + /* 8 accumulators with pairwise summation tree for ILP + precision */ + double s[8]; + for (int k = 0; k < 8; k++) + s[k] = 0.0; + + #pragma GCC ivdep + for (size_t i = 0; i + 7 < count; i += 8) { + s[0] += A[i] * B[i]; + s[1] += A[i + 1] * B[i + 1]; + s[2] += A[i + 2] * B[i + 2]; + s[3] += A[i + 3] * B[i + 3]; + s[4] += A[i + 4] * B[i + 4]; + s[5] += A[i + 5] * B[i + 5]; + s[6] += A[i + 6] * B[i + 6]; + s[7] += A[i + 7] * B[i + 7]; + /* Prefetch next cache line every 4 iterations */ + if ((i >> 5) & 1) + __builtin_prefetch(&A[i + 256], 0, 1); + } + for (size_t i = count & ~7; i < count; i++) { + s[0] += A[i] * B[i]; + } + + /* Pairwise summation tree */ + return ((s[0]+s[1])+(s[2]+s[3]))+((s[4]+s[5])+(s[6]+s[7])); } +#pragma GCC pop_options /** * @brief Scale a vector by a scalar factor. diff --git a/tests/benchmark_vec_dot.c b/tests/benchmark_vec_dot.c new file mode 100644 index 0000000..4976fe5 --- /dev/null +++ b/tests/benchmark_vec_dot.c @@ -0,0 +1,134 @@ +/* + * @file benchmark_vec_dot.c + * @brief Benchmark vec_dot across vector sizes with correctness validation. + * + * Uses CLOCK_MONOTONIC_RAW for nanosecond precision. + * Runs multiple repeats per size and reports median to reduce noise. + */ + +#include "linal.h" +#include +#include +#include +#include +#include +#include + +#define REPEATS 20 +#define EPSILON 1e-6 + +static const size_t sizes[] = { + 65536, 262144, 1048576, 4194304, 16777216, 67108864 +}; +static const int n_sizes = sizeof(sizes) / sizeof(sizes[0]); + +static void fill_vector(Vector *v, uint64_t seed) +{ + double *d = v->data; + uint64_t state = seed; + for (size_t i = 0; i < v->size; i++) { + state = state * 6364136223846793005ULL + 1442695040888963407ULL; + d[i] = (double)((state >> 11) & 0x3FFFFF) / (double)(1 << 21) - 1.0; + } +} + +static double +median_double(double *arr, int n) +{ + /* Simple insertion sort for small n */ + for (int i = 1; i < n; i++) { + double key = arr[i]; + int j = i - 1; + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j--; + } + arr[j + 1] = key; + } + if (n % 2 == 0) + return (arr[n / 2 - 1] + arr[n / 2]) / 2.0; + return arr[n / 2]; +} + +int main(void) +{ + bool all_valid = true; + double primary_us = 0.0; + + printf("=== vec_dot benchmark (median of %d runs) ===\n", REPEATS); + printf("%-12s %12s %10s\n", "Size", "Time(us)", "Valid"); + + double times[REPEATS]; + + for (int s = 0; s < n_sizes; s++) { + size_t dim = sizes[s]; + + Vector a = vec_create(dim); + Vector b = vec_create(dim); + + if (!a.data || !b.data) { + printf("FAIL allocation %zu\n", dim); + all_valid = false; + continue; + } + + fill_vector(&a, 42 + s * 7); + fill_vector(&b, 99 + s * 13); + + /* Compute reference */ + double ref = 0.0; + for (size_t i = 0; i < dim; i++) + ref += a.data[i] * b.data[i]; + + double result = vec_dot(a, b); + bool valid = fabs(result - ref) < EPSILON; + + if (!valid) { + printf("FAIL %zu: validation error (got %.10f, expected %.10f)\n", + dim, result, ref); + all_valid = false; + continue; + } + + /* Warmup */ + vec_dot(a, b); + vec_dot(a, b); + vec_dot(a, b); + + /* Timed runs */ + for (int r = 0; r < REPEATS; r++) { + struct timespec ts, te; + clock_gettime(CLOCK_MONOTONIC_RAW, &ts); + result = vec_dot(a, b); + clock_gettime(CLOCK_MONOTONIC_RAW, &te); + + double ns = (double)(te.tv_sec - ts.tv_sec) * 1e9 + + (double)(te.tv_nsec - ts.tv_nsec); + times[r] = ns / 1000.0; /* Convert to µs */ + } + + /* Prevent compiler from optimizing away the result */ + if (result != result) { /* Never true, but uses 'result' */ + printf("unexpected\n"); + } + + double median_us = median_double(times, REPEATS); + + if (s == n_sizes - 1) + primary_us = median_us; + + printf("%12zu %12.3f %5s\n", dim, median_us, "OK"); + + vec_free(&a); + vec_free(&b); + } + + printf("\n=== Correctness: %s ===\n", all_valid ? "PASS" : "FAIL"); + + if (all_valid) + printf("METRIC total_us=%.3f\n", primary_us); + else + printf("METRIC total_us=999999.000\n"); + + return EXIT_SUCCESS; +} diff --git a/tests/meson.build b/tests/meson.build index f665cf3..db2a66e 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -133,6 +133,13 @@ benchmark_mat_transpose = executable( include_directories: [public_headers, generated_headers], ) +benchmark_vec_dot = executable( + 'benchmark_vec_dot', + files('benchmark_vec_dot.c'), + dependencies: [linal_dep], + include_directories: [public_headers, generated_headers], +) + # Run all tests test('mat_create', test_mat_create) test('mat_memory', test_mat_memory)