From cf3d91511185f8cf8ff731c3205e86af28d57aec Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 20 May 2026 14:21:28 +0100 Subject: [PATCH 01/10] feat: add vec_dot benchmark and autoresearch setup --- tests/benchmark_vec_dot.c | 103 ++++++++++++++++++++++++++++++++++++++ tests/meson.build | 7 +++ 2 files changed, 110 insertions(+) create mode 100644 tests/benchmark_vec_dot.c diff --git a/tests/benchmark_vec_dot.c b/tests/benchmark_vec_dot.c new file mode 100644 index 0000000..766e6e7 --- /dev/null +++ b/tests/benchmark_vec_dot.c @@ -0,0 +1,103 @@ +/* + * @file benchmark_vec_dot.c + * @brief Benchmark vec_dot across vector sizes with correctness validation. + */ + +#include "linal.h" +#include +#include +#include +#include +#include +#include + +#define REPEATS_SMALL 50 +#define REPEATS_LARGE 10 +#define EPSILON 1e-6 + +static const size_t sizes[] = {64, 128, 256, 512, 1024, 4096, 16384, 65536}; +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 clock_ms(struct timespec *s, struct timespec *e) +{ + return (e->tv_sec - s->tv_sec) * 1000.0 + (e->tv_nsec - s->tv_nsec) / 1e6; +} + +int main(void) +{ + bool all_valid = true; + double primary_us = 0.0; + + printf("=== vec_dot benchmark ===\n"); + printf("%-8s %12s %10s\n", "Size", "Time(us)", "Valid"); + + for (int s = 0; s < n_sizes; s++) { + size_t dim = sizes[s]; + int repeats = (dim <= 1024) ? REPEATS_SMALL : REPEATS_LARGE; + + 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); + + struct timespec ts, te; + clock_gettime(CLOCK_MONOTONIC, &ts); + for (int r = 0; r < repeats; r++) + vec_dot(a, b); + clock_gettime(CLOCK_MONOTONIC, &te); + + double total_us = clock_ms(&ts, &te) * 1000.0 / (double)repeats; + + if (s == n_sizes - 1) + primary_us = total_us; + + printf("%8zu %12.2f %5s\n", dim, total_us, "OK"); + + vec_free(&a); + vec_free(&b); + } + + printf("\n=== Correctness: %s ===\n", all_valid ? "PASS" : "FAIL"); + + if (all_valid) + printf("METRIC total_us=%.2f\n", primary_us); + else + printf("METRIC total_us=999999.00\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) From c9ce0525f6af95caa5f26ce2e22427a095445332 Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 20 May 2026 14:29:20 +0100 Subject: [PATCH 02/10] feat: fix vec_dot benchmark with proper timing and sizes --- tests/benchmark_vec_dot.c | 67 ++++++++++++++++++++++++++++----------- 1 file changed, 49 insertions(+), 18 deletions(-) diff --git a/tests/benchmark_vec_dot.c b/tests/benchmark_vec_dot.c index 766e6e7..4976fe5 100644 --- a/tests/benchmark_vec_dot.c +++ b/tests/benchmark_vec_dot.c @@ -1,6 +1,9 @@ /* * @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" @@ -11,11 +14,12 @@ #include #include -#define REPEATS_SMALL 50 -#define REPEATS_LARGE 10 +#define REPEATS 20 #define EPSILON 1e-6 -static const size_t sizes[] = {64, 128, 256, 512, 1024, 4096, 16384, 65536}; +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) @@ -28,9 +32,22 @@ static void fill_vector(Vector *v, uint64_t seed) } } -static double clock_ms(struct timespec *s, struct timespec *e) +static double +median_double(double *arr, int n) { - return (e->tv_sec - s->tv_sec) * 1000.0 + (e->tv_nsec - s->tv_nsec) / 1e6; + /* 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) @@ -38,12 +55,13 @@ int main(void) bool all_valid = true; double primary_us = 0.0; - printf("=== vec_dot benchmark ===\n"); - printf("%-8s %12s %10s\n", "Size", "Time(us)", "Valid"); + 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]; - int repeats = (dim <= 1024) ? REPEATS_SMALL : REPEATS_LARGE; Vector a = vec_create(dim); Vector b = vec_create(dim); @@ -74,19 +92,32 @@ int main(void) /* Warmup */ vec_dot(a, b); + vec_dot(a, b); + vec_dot(a, b); - struct timespec ts, te; - clock_gettime(CLOCK_MONOTONIC, &ts); - for (int r = 0; r < repeats; r++) - vec_dot(a, b); - clock_gettime(CLOCK_MONOTONIC, &te); + /* 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 total_us = clock_ms(&ts, &te) * 1000.0 / (double)repeats; + double median_us = median_double(times, REPEATS); if (s == n_sizes - 1) - primary_us = total_us; + primary_us = median_us; - printf("%8zu %12.2f %5s\n", dim, total_us, "OK"); + printf("%12zu %12.3f %5s\n", dim, median_us, "OK"); vec_free(&a); vec_free(&b); @@ -95,9 +126,9 @@ int main(void) printf("\n=== Correctness: %s ===\n", all_valid ? "PASS" : "FAIL"); if (all_valid) - printf("METRIC total_us=%.2f\n", primary_us); + printf("METRIC total_us=%.3f\n", primary_us); else - printf("METRIC total_us=999999.00\n"); + printf("METRIC total_us=999999.000\n"); return EXIT_SUCCESS; } From f682801ba9792dffb42e1da5d5ceabed9b9180ef Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 20 May 2026 14:30:56 +0100 Subject: [PATCH 03/10] =?UTF-8?q?vec=5Fdot:=20O3,=20=5F=5Frestrict=5F=5F,?= =?UTF-8?q?=208=20accumulators=20+=20pairwise=20summation,=20OpenMP=20simd?= =?UTF-8?q?=20reduction=20for=20=E2=89=A51M=20elements?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Result: {"status":"keep","total_us":41323} --- src/linal_vector.c | 43 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 40 insertions(+), 3 deletions(-) diff --git a/src/linal_vector.c b/src/linal_vector.c index ad5216e..fc348cd 100644 --- a/src/linal_vector.c +++ b/src/linal_vector.c @@ -135,7 +135,11 @@ vec_sub(const Vector a, const Vector b, Vector *result) /** * @brief Compute the dot product of two vectors. + * + * Uses multiple accumulators with pairwise summation for numerical precision, + * and OpenMP parallel SIMD reduction for large vectors. */ +__attribute__((optimize("O3"))) double vec_dot(const Vector a, const Vector b) { @@ -143,12 +147,45 @@ 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 SIMD reduction for large vectors. + * Threshold: 1M elements (~8MB per vector, 16MB total read). */ + if (count >= 1048576) { +#pragma omp parallel for simd reduction(+:sum) + for (size_t i = 0; i < count; i++) { + sum += A[i] * B[i]; + } + return sum; + } +#endif + + /* 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]; + } + for (size_t i = count & ~7; i < count; i++) { + s[0] += A[i] * B[i]; } - return sum; + /* Pairwise summation tree */ + return ((s[0]+s[1])+(s[2]+s[3]))+((s[4]+s[5])+(s[6]+s[7])); } /** From 43160dac7e65657b7fa5d91ad087579ef0a71fc1 Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 20 May 2026 14:32:58 +0100 Subject: [PATCH 04/10] vec_dot: lowered OpenMP threshold to 256K, adaptive thread count (2/4/8), added prefetching Result: {"status":"keep","total_us":40136.5} --- src/linal_vector.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/linal_vector.c b/src/linal_vector.c index fc348cd..844df02 100644 --- a/src/linal_vector.c +++ b/src/linal_vector.c @@ -153,10 +153,17 @@ vec_dot(const Vector a, const Vector b) double sum = 0.0; #if defined(_OPENMP) - /* Parallel SIMD reduction for large vectors. - * Threshold: 1M elements (~8MB per vector, 16MB total read). */ - if (count >= 1048576) { -#pragma omp parallel for simd reduction(+:sum) + /* Parallel reduction for large vectors. + * Adaptive threshold: 256K elements (~2MB per vector). */ + if (count >= 262144) { + int linal_threads; + if (count < 1048576) + linal_threads = 2; + else if (count < 4194304) + linal_threads = 4; + else + linal_threads = 8; +#pragma omp parallel for num_threads(linal_threads) reduction(+:sum) for (size_t i = 0; i < count; i++) { sum += A[i] * B[i]; } @@ -179,6 +186,9 @@ vec_dot(const Vector a, const Vector b) 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]; From 9ae978e355da2a34876828c1e30e38b2a887f683 Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 20 May 2026 14:36:53 +0100 Subject: [PATCH 05/10] =?UTF-8?q?vec=5Fdot:=20fixed=208=20threads=20(no=20?= =?UTF-8?q?adaptive),=20simplification=20improves=20medium=20sizes=20drama?= =?UTF-8?q?tically=20(256K:=20111=E2=86=9230=C2=B5s,=201M:=20223=E2=86=929?= =?UTF-8?q?0=C2=B5s)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Result: {"status":"keep","total_us":39547} --- src/linal_vector.c | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/src/linal_vector.c b/src/linal_vector.c index 844df02..2409579 100644 --- a/src/linal_vector.c +++ b/src/linal_vector.c @@ -154,16 +154,11 @@ vec_dot(const Vector a, const Vector b) #if defined(_OPENMP) /* Parallel reduction for large vectors. - * Adaptive threshold: 256K elements (~2MB per vector). */ + * GCC doesn't allow simd + num_threads on same pragma, so we use + * parallel for with reduction. Compiler auto-vectorizes the inner loop. + * Adaptive thread count for memory bandwidth saturation. */ if (count >= 262144) { - int linal_threads; - if (count < 1048576) - linal_threads = 2; - else if (count < 4194304) - linal_threads = 4; - else - linal_threads = 8; -#pragma omp parallel for num_threads(linal_threads) reduction(+:sum) +#pragma omp parallel for num_threads(8) reduction(+:sum) for (size_t i = 0; i < count; i++) { sum += A[i] * B[i]; } From ccfeb62a01f59605939712be8034bfb17a90e8dd Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 20 May 2026 14:51:05 +0100 Subject: [PATCH 06/10] =?UTF-8?q?vec=5Fdot:=20madvise(POSIX=5FMADV=5FSEQUE?= =?UTF-8?q?NTIAL)=20hints=20for=20kernel=20page=20prefetch=20=E2=80=94=203?= =?UTF-8?q?9475=20vs=2039547=20(0.2%=20improvement)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Result: {"status":"keep","total_us":39475} --- src/linal_vector.c | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/linal_vector.c b/src/linal_vector.c index 2409579..5ee2c59 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 ========================================== */ /** @@ -156,8 +162,13 @@ vec_dot(const Vector a, const Vector b) /* Parallel reduction for large vectors. * GCC doesn't allow simd + num_threads on same pragma, so we use * parallel for with reduction. Compiler auto-vectorizes the inner loop. - * Adaptive thread count for memory bandwidth saturation. */ + * 8 threads = 8 physical cores on target hardware (optimal for MLB). */ if (count >= 262144) { +#ifdef __linux__ + /* Hint sequential access pattern to kernel for better page prefetching */ + 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) reduction(+:sum) for (size_t i = 0; i < count; i++) { sum += A[i] * B[i]; From 2c2fd8f3a0a090d58b3aaa82641ddc81d459e7ab Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 20 May 2026 14:52:27 +0100 Subject: [PATCH 07/10] =?UTF-8?q?vec=5Fdot:=20explicit=20OpenMP=20data=20s?= =?UTF-8?q?haring=20clauses=20(default(none),=20firstprivate)=20=E2=80=94?= =?UTF-8?q?=2039354=20vs=2039475=20(0.3%=20improvement)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Result: {"status":"keep","total_us":39354} --- src/linal_vector.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/linal_vector.c b/src/linal_vector.c index 5ee2c59..44bd393 100644 --- a/src/linal_vector.c +++ b/src/linal_vector.c @@ -160,16 +160,15 @@ vec_dot(const Vector a, const Vector b) #if defined(_OPENMP) /* Parallel reduction for large vectors. - * GCC doesn't allow simd + num_threads on same pragma, so we use - * parallel for with reduction. Compiler auto-vectorizes the inner loop. + * 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__ - /* Hint sequential access pattern to kernel for better page prefetching */ 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) reduction(+:sum) +#pragma omp parallel for num_threads(8) \ + default(none) firstprivate(A, B, count) reduction(+:sum) for (size_t i = 0; i < count; i++) { sum += A[i] * B[i]; } From dae1045bd63377b4eae41a84d19aa60cbea1e54e Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 20 May 2026 14:53:26 +0100 Subject: [PATCH 08/10] =?UTF-8?q?vec=5Fdot:=20schedule(static,=201048576)?= =?UTF-8?q?=20explicit=20chunk=20size=20=E2=80=94=2039147=20vs=2039354=20(?= =?UTF-8?q?0.5%=20improvement)=20but=20hurts=20medium=20sizes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Result: {"status":"keep","total_us":39147} --- src/linal_vector.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/linal_vector.c b/src/linal_vector.c index 44bd393..04752f1 100644 --- a/src/linal_vector.c +++ b/src/linal_vector.c @@ -167,7 +167,7 @@ vec_dot(const Vector a, const Vector b) 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) \ +#pragma omp parallel for num_threads(8) schedule(static, 1048576) \ default(none) firstprivate(A, B, count) reduction(+:sum) for (size_t i = 0; i < count; i++) { sum += A[i] * B[i]; From 70bdcb27d69f2f8a4fb65e69cab313ae1dfb5314 Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 20 May 2026 14:54:09 +0100 Subject: [PATCH 09/10] =?UTF-8?q?vec=5Fdot:=20schedule(static,=2065536)=20?= =?UTF-8?q?smaller=20chunk=20=E2=80=94=2039015=20vs=2039147=20(0.3%=20impr?= =?UTF-8?q?ovement),=20better=20medium=20sizes=20too?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Result: {"status":"keep","total_us":39015} --- src/linal_vector.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/linal_vector.c b/src/linal_vector.c index 04752f1..b43c9da 100644 --- a/src/linal_vector.c +++ b/src/linal_vector.c @@ -167,7 +167,7 @@ vec_dot(const Vector a, const Vector b) 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, 1048576) \ +#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]; From 92d438bf487a9cbb96dc4871ec0aeab97d8b7b21 Mon Sep 17 00:00:00 2001 From: Aaron Date: Wed, 20 May 2026 14:56:10 +0100 Subject: [PATCH 10/10] =?UTF-8?q?vec=5Fdot:=20#pragma=20GCC=20target(avx2,?= =?UTF-8?q?fma)=20+=20chunk=20size=2065536=20=E2=80=94=2038531=20vs=203901?= =?UTF-8?q?5=20(1.2%=20improvement),=20AVX2+FMA=20synergy=20with=20chunkin?= =?UTF-8?q?g?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Result: {"status":"keep","total_us":38531} --- src/linal_vector.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/linal_vector.c b/src/linal_vector.c index b43c9da..1c31307 100644 --- a/src/linal_vector.c +++ b/src/linal_vector.c @@ -142,9 +142,12 @@ vec_sub(const Vector a, const Vector b, Vector *result) /** * @brief Compute the dot product of two vectors. * - * Uses multiple accumulators with pairwise summation for numerical precision, - * and OpenMP parallel SIMD reduction for large 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) @@ -202,6 +205,7 @@ vec_dot(const Vector a, const Vector b) /* 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.