Skip to content

Distribute and run LLMs with a single file.

CPU flash-attention fixes for #975 (workaround + AVX-512 helpers + simd_gemm) (#978)

Davide Eynard4905d747e038
diff --git a/llama.cpp.patches/patches/ggml_src_ggml-cpu_ops.cpp.patch b/llama.cpp.patches/patches/ggml_src_ggml-cpu_ops.cpp.patch
new file mode 100644
index 00000000..443fc909
--- /dev/null
+++ b/llama.cpp.patches/patches/ggml_src_ggml-cpu_ops.cpp.patch
@@ -0,0 +1,227 @@
+diff --git a/ggml/src/ggml-cpu/ops.cpp b/ggml/src/ggml-cpu/ops.cpp
+--- a/llama.cpp/ggml/src/ggml-cpu/ops.cpp
++++ b/llama.cpp/ggml/src/ggml-cpu/ops.cpp
+@@ -12,6 +12,18 @@
+ #include <cfloat>
+ #include <cmath>
+
++#if GGML_USE_LLAMAFILE
++// [jart] llamafile #975: forward declarations for the optimized AVX-512
++// flash-attention helpers implemented in llamafile/fa_helpers_* and
++// fa_simd_gemm_*. extern "C" because the implementations are exported
++// as C symbols from llamafile/sgemm.cpp; can't use llamafile/sgemm.h
++// directly because the submodule includes a shadowing upstream sgemm.h.
++extern "C" bool llamafile_fa_vec_dot_f16(int, float *, const void *, const void *);
++extern "C" bool llamafile_fa_fp16_to_fp32_row(const void *, float *, int64_t);
++extern "C" bool llamafile_fa_simd_gemm(float *, const float *, const float *,
++ int, int, int);
++#endif
++
+ // ggml_compute_forward_dup
+
+ static void ggml_compute_forward_dup_same_cont(
+@@ -8247,6 +8259,15 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
+ GGML_ASSERT(( q_to_vec_dot) && "fattn: unsupported K-type");
+ GGML_ASSERT((v->type == GGML_TYPE_F32 || v_to_float ) && "fattn: unsupported V-type");
+
++#if GGML_USE_LLAMAFILE
++ // [jart] llamafile #975: see file-scope extern "C" declarations of
++ // llamafile_fa_vec_dot_f16 / llamafile_fa_fp16_to_fp32_row above.
++ // Their multi-arch implementations live in llamafile/fa_helpers_*
++ // and are runtime-dispatched via llamafile/sgemm.cpp.
++ const bool kq_is_f16 = (k->type == GGML_TYPE_F16 && k_vec_dot_type == GGML_TYPE_F16);
++ const bool v_is_f16 = (v->type == GGML_TYPE_F16);
++#endif
++
+ int ith = params->ith;
+
+ for (int ir = ir0; ir < ir1; ++ir) {
+@@ -8266,10 +8287,22 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
+ ggml_fp16_t * VKQ16 = (ggml_fp16_t *) (VKQ32 + 1*DV); // (temporary) FP16 VKQ accumulator
+ ggml_fp16_t * Q_q = (ggml_fp16_t *) (VKQ32 + 2*DV); // (temporary) buffer for Q converted to quantized/FP16
+
+- if (v->type == GGML_TYPE_F16) {
+- memset(VKQ16, 0, DV*sizeof(ggml_fp16_t));
+- } else {
++ // [jart] llamafile #975: when V is f16 and the hardware lacks
++ // native f16 FMA, accumulate VKQ in f32 instead of f16. The f16
++ // accumulator path round-trips f16<->f32 every KV iteration via
++ // _mm512_cvtph_ps / _mm512_cvtps_ph (see simd-mappings.h
++ // GGML_F32Cx16_*), dominating the FA inner loop on Xeon Gold /
++ // Skylake-X / Ice Lake / Zen 4 without AVX-512-FP16. Hardware
++ // with native f16 FMA keeps the existing fast path.
++#if defined(__AVX512FP16__) || defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC) || defined(__riscv_zvfh)
++ const bool use_f32_accum = (v->type != GGML_TYPE_F16);
++#else
++ const bool use_f32_accum = true;
++#endif
++ if (use_f32_accum) {
+ memset(VKQ32, 0, DV*sizeof(float));
++ } else {
++ memset(VKQ16, 0, DV*sizeof(ggml_fp16_t));
+ }
+
+ const ggml_fp16_t * mp = mask ? (ggml_fp16_t *)((char *) mask->data + iq1*mask->nb[1] + (iq2%mask->ne[2])*mask->nb[2] + (iq3%mask->ne[3])*mask->nb[3]) : NULL;
+@@ -8298,7 +8331,13 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
+ float s; // KQ value
+
+ const char * k_data = (const char *) k->data + ( ic*nbk1 + ik2*nbk2 + ik3*nbk3);
++#if GGML_USE_LLAMAFILE
++ if (!kq_is_f16 || !llamafile_fa_vec_dot_f16(DK, &s, k_data, Q_q)) {
++ kq_vec_dot(DK, &s, 0, k_data, 0, Q_q, 0, 1);
++ }
++#else
+ kq_vec_dot(DK, &s, 0, k_data, 0, Q_q, 0, 1);
++#endif
+
+ s = s*scale; // scale KQ value
+
+@@ -8315,21 +8354,36 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
+
+ const char * v_data = ((const char *) v->data + (ic*nbv1 + iv2*nbv2 + iv3*nbv3));
+
+- if (v->type == GGML_TYPE_F16) {
++ if (use_f32_accum) {
+ if (s > M) {
+ // s is new maximum, ms < 1.0f, vs == expf(s - s) == 1.0f
+ M = s;
+ ms = expf(Mold - M);
+
+ // V = V*expf(Mold - M)
+- ggml_vec_scale_f16(DV, VKQ16, ms);
++ ggml_vec_scale_f32(DV, VKQ32, ms);
+ } else {
+ // no new maximum, ms == 1.0f, vs != 1.0f
+ vs = expf(s - M);
+ }
+
+ // V += v*expf(s - M)
+- ggml_vec_mad_f16(DV, VKQ16, (const ggml_fp16_t *) v_data, vs);
++ if (v_to_float) {
++ // f16/quant -> f32 (covers GGML_TYPE_F16 too once
++ // we're in the f32 accumulator path; v_to_float is
++ // ggml_fp16_to_fp32_row for V=f16)
++#if GGML_USE_LLAMAFILE
++ if (!v_is_f16 || !llamafile_fa_fp16_to_fp32_row(v_data, V32, DV)) {
++ v_to_float(v_data, V32, DV);
++ }
++#else
++ v_to_float(v_data, V32, DV);
++#endif
++ ggml_vec_mad_f32(DV, VKQ32, V32, vs);
++ } else {
++ // V is F32
++ ggml_vec_mad_f32(DV, VKQ32, (const float *) v_data, vs);
++ }
+ } else {
+ if (s > M) {
+ // s is new maximum, ms < 1.0f, vs == expf(s - s) == 1.0f
+@@ -8337,26 +8391,20 @@ static void ggml_compute_forward_flash_attn_ext_f16_one_chunk(
+ ms = expf(Mold - M);
+
+ // V = V*expf(Mold - M)
+- ggml_vec_scale_f32(DV, VKQ32, ms);
++ ggml_vec_scale_f16(DV, VKQ16, ms);
+ } else {
+ // no new maximum, ms == 1.0f, vs != 1.0f
+ vs = expf(s - M);
+ }
+
+ // V += v*expf(s - M)
+- if (v_to_float) {
+- v_to_float(v_data, V32, DV);
+- ggml_vec_mad_f32(DV, VKQ32, V32, vs);
+- } else {
+- // V is F32
+- ggml_vec_mad_f32(DV, VKQ32, (const float *) v_data, vs);
+- }
++ ggml_vec_mad_f16(DV, VKQ16, (const ggml_fp16_t *) v_data, vs);
+ }
+
+ S = S*ms + vs; // scale and increment sum with partial sum
+ }
+
+- if (v->type == GGML_TYPE_F16) {
++ if (!use_f32_accum) {
+ for (int64_t d = 0; d < DV; ++d) {
+ VKQ32[d] = GGML_CPU_FP16_TO_FP32(VKQ16[d]);
+ }
+@@ -8577,8 +8625,24 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
+ const char * k_data = (const char *)k->data + (ic + tk)*nbk1 + ik2*nbk2 + ik3*nbk3;
+ if (kv_type == GGML_TYPE_F16) {
+ const ggml_fp16_t * k_f16 = (const ggml_fp16_t *)k_data;
+- for (int64_t dk = 0; dk < DK; dk++) {
+- K_f32[dk * KV_TILE_SZ + tk] = GGML_CPU_FP16_TO_FP32(k_f16[dk]);
++#if GGML_USE_LLAMAFILE
++ // [jart] llamafile #975: dequant the K row contiguously
++ // via SIMD (AVX-512 cvtph_ps), then scalar-transpose into
++ // K_f32. ~2x faster than the upstream per-element table
++ // lookup. Falls back to upstream's scalar loop on CPUs
++ // without our optimized helper. DK up to 1024 covers all
++ // realistic attention head dims (Qwen3=128, DeepSeek-MLA=576).
++ alignas(64) float k_scratch[1024];
++ if (DK <= 1024 && llamafile_fa_fp16_to_fp32_row(k_f16, k_scratch, DK)) {
++ for (int64_t dk = 0; dk < DK; dk++) {
++ K_f32[dk * KV_TILE_SZ + tk] = k_scratch[dk];
++ }
++ } else
++#endif
++ {
++ for (int64_t dk = 0; dk < DK; dk++) {
++ K_f32[dk * KV_TILE_SZ + tk] = GGML_CPU_FP16_TO_FP32(k_f16[dk]);
++ }
+ }
+ } else {
+ const float * k_f32_src = (const float *)k_data;
+@@ -8588,7 +8652,18 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
+ }
+ }
+ memset(KQ, 0, Q_TILE_SZ * KV_TILE_SZ * sizeof(float));
++#if GGML_USE_LLAMAFILE
++ // [jart] llamafile #975: prefer our AVX-512 simd_gemm wrapper
++ // (4x4 zmm tile, ~2.7x the FMA throughput of ops.cpp's
++ // default AVX2 6x2 ymm tile). Falls back to upstream's
++ // header-inlined simd_gemm on CPUs without AVX-512F.
++ if (!llamafile_fa_simd_gemm(KQ, (const float *)Q_q, K_f32,
++ Q_TILE_SZ, DK, KV_TILE_SZ)) {
++ simd_gemm(KQ, (const float *)Q_q, K_f32, Q_TILE_SZ, DK, KV_TILE_SZ);
++ }
++#else
+ simd_gemm(KQ, (const float *)Q_q, K_f32, Q_TILE_SZ, DK, KV_TILE_SZ);
++#endif
+ ggml_vec_scale_f32(Q_TILE_SZ * KV_TILE_SZ, KQ, scale);
+
+ // Set padded KQ entries to -inf so softmax gives them zero weight
+@@ -8641,7 +8716,15 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
+ for (int tk = 0; tk < kv_tile; tk++) {
+ const char * v_data = (const char *)v->data + (ic + tk)*nbv1 + iv2*nbv2 + iv3*nbv3;
+ if (kv_type == GGML_TYPE_F16) {
++#if GGML_USE_LLAMAFILE
++ // [jart] llamafile #975: route through optimized AVX-512
++ // dequant when available; fall back to upstream's helper.
++ if (!llamafile_fa_fp16_to_fp32_row((const ggml_fp16_t *)v_data, V32 + tk * DV, DV)) {
++ ggml_fp16_to_fp32_row((const ggml_fp16_t *)v_data, V32 + tk * DV, DV);
++ }
++#else
+ ggml_fp16_to_fp32_row((const ggml_fp16_t *)v_data, V32 + tk * DV, DV);
++#endif
+ } else {
+ memcpy(V32 + tk * DV, v_data, DV * sizeof(float));
+ }
+@@ -8651,7 +8734,16 @@ static void ggml_compute_forward_flash_attn_ext_tiled(
+ memset(KQ + tq * KV_TILE_SZ, 0, KV_TILE_SZ * sizeof(float));
+ }
+ }
++#if GGML_USE_LLAMAFILE
++ // [jart] llamafile #975: same AVX-512 simd_gemm wrapper as the
++ // KQ matmul above (4x4 zmm tile vs default AVX2 6x2).
++ if (!llamafile_fa_simd_gemm(VKQ32, KQ, V32,
++ Q_TILE_SZ, KV_TILE_SZ, DV)) {
++ simd_gemm(VKQ32, KQ, V32, Q_TILE_SZ, KV_TILE_SZ, DV);
++ }
++#else
+ simd_gemm(VKQ32, KQ, V32, Q_TILE_SZ, KV_TILE_SZ, DV);
++#endif
+ }
+
+ // sinks (apply only to valid rows in the tile)
diff --git a/llama.cpp.patches/patches/src_llama-context.cpp.patch b/llama.cpp.patches/patches/src_llama-context.cpp.patch
new file mode 100644
index 00000000..2d46b892
--- /dev/null
+++ b/llama.cpp.patches/patches/src_llama-context.cpp.patch
@@ -0,0 +1,20 @@
+diff --git a/src/llama-context.cpp b/src/llama-context.cpp
+--- a/llama.cpp/src/llama-context.cpp
++++ b/llama.cpp/src/llama-context.cpp
+@@ -426,6 +426,16 @@ void llama_context::sched_reserve() {
+ LLAMA_LOG_DEBUG("%s: worst-case: n_tokens = %d, n_seqs = %d, n_outputs = %d\n", __func__, n_tokens, n_seqs, n_outputs);
+
+ // resolve automatic Flash Attention use
++ if (cparams.auto_fa && model.devices.empty()) {
++ // llamafile: the CPU Flash Attention path (f16 mad/dot) is significantly
++ // slower than the non-FA path on x86 (see mozilla-ai/llamafile#975).
++ // When no GPU devices are present, default -fa auto to OFF. Users who
++ // want FA for memory savings on long contexts can still pass -fa on.
++ cparams.flash_attn = false;
++ cparams.auto_fa = false;
++ LLAMA_LOG_INFO("%s: Flash Attention was auto, set to disabled (CPU-only)\n", __func__);
++ }
++
+ if (cparams.auto_fa) {
+ auto * gf = graph_reserve(1, n_seqs, n_outputs, mctx.get(), true);
+ if (!gf) {
diff --git a/llamafile/BUILD.mk b/llamafile/BUILD.mk
index 2aef7863..eb2dc2bd 100644
--- a/llamafile/BUILD.mk
+++ b/llamafile/BUILD.mk
@@ -184,11 +184,17 @@ TINYBLAS_CPU_IQK_SRCS := \
llamafile/iqk_mul_mat_amd_zen4.cpp \
llamafile/iqk_mul_mat_arm82.cpp
+TINYBLAS_CPU_FA_HELPERS_SRCS := \
+ llamafile/fa_helpers_amd_avx512f.cpp \
+ llamafile/fa_helpers_unsupported.cpp \
+ llamafile/fa_simd_gemm_amd_avx512f.cpp
+
TINYBLAS_CPU_SRCS := \
llamafile/sgemm.cpp \
$(TINYBLAS_CPU_SGEMM_SRCS) \
$(TINYBLAS_CPU_MIXMUL_SRCS) \
- $(TINYBLAS_CPU_IQK_SRCS)
+ $(TINYBLAS_CPU_IQK_SRCS) \
+ $(TINYBLAS_CPU_FA_HELPERS_SRCS)
TINYBLAS_CPU_OBJS := $(TINYBLAS_CPU_SRCS:%.cpp=o/$(MODE)/%.o)
@@ -398,6 +404,11 @@ o/$(MODE)/llamafile/iqk_mul_mat_amd_avx2.o: \
o/$(MODE)/llamafile/iqk_mul_mat_amd_zen4.o: \
private TARGET_ARCH += -Xx86_64-mtune=skylake -Xx86_64-mavx -Xx86_64-mavx2 -Xx86_64-mfma -Xx86_64-mf16c -Xx86_64-mavx512f -Xx86_64-mavx512vl -Xx86_64-mavx512vnni -Xx86_64-mavx512bw -Xx86_64-mavx512dq
+# Flash-attention helpers (issue #975) - AVX-512F variant
+o/$(MODE)/llamafile/fa_helpers_amd_avx512f.o \
+o/$(MODE)/llamafile/fa_simd_gemm_amd_avx512f.o: \
+ private TARGET_ARCH += -Xx86_64-mtune=cannonlake -Xx86_64-mavx -Xx86_64-mf16c -Xx86_64-mfma -Xx86_64-mavx2 -Xx86_64-mavx512f
+
# ARM82 variant (Apple M1+, Raspberry Pi 5)
o/$(MODE)/llamafile/iqk_mul_mat_arm82.o: \
private TARGET_ARCH += -Xaarch64-march=armv8.2-a+dotprod+fp16
diff --git a/llamafile/fa_helpers_amd_avx512f.cpp b/llamafile/fa_helpers_amd_avx512f.cpp
new file mode 100644
index 00000000..5dd27ebf
--- /dev/null
+++ b/llamafile/fa_helpers_amd_avx512f.cpp
@@ -0,0 +1,71 @@
+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi
+//
+// AVX-512F-optimized flash-attention helpers (issue #975).
+//
+// Routes around ops.cpp's f16 helpers (ggml_vec_dot_f16,
+// ggml_fp16_to_fp32_row), which cosmocc compiles at AVX2 baseline so
+// the APE binary stays portable. These wrappers are compiled with
+// per-arch flags via BUILD.mk and dispatched at runtime by sgemm.cpp
+// based on X86_HAVE(AVX512F).
+//
+// Functions return true when handled by the optimized kernel; the
+// caller (the FA function in ops.cpp) falls back to the upstream
+// helper otherwise.
+
+#ifdef __x86_64__
+
+#include "sgemm.h"
+#include "ggml-impl.h"
+#include <immintrin.h>
+#include <cstdint>
+
+extern "C" {
+
+bool llamafile_fa_vec_dot_f16_amd_avx512f(int n, float *s,
+ const void *vx, const void *vy) {
+ const ggml_fp16_t *x = (const ggml_fp16_t *)vx;
+ const ggml_fp16_t *y = (const ggml_fp16_t *)vy;
+ __m512 acc0 = _mm512_setzero_ps();
+ __m512 acc1 = _mm512_setzero_ps();
+ int i = 0;
+ // Unrolled by 2: 32 f16 elements per iteration.
+ for (; i + 32 <= n; i += 32) {
+ __m512 xv0 = _mm512_cvtph_ps(_mm256_loadu_si256((const __m256i *)(x + i)));
+ __m512 yv0 = _mm512_cvtph_ps(_mm256_loadu_si256((const __m256i *)(y + i)));
+ __m512 xv1 = _mm512_cvtph_ps(_mm256_loadu_si256((const __m256i *)(x + i + 16)));
+ __m512 yv1 = _mm512_cvtph_ps(_mm256_loadu_si256((const __m256i *)(y + i + 16)));
+ acc0 = _mm512_fmadd_ps(xv0, yv0, acc0);
+ acc1 = _mm512_fmadd_ps(xv1, yv1, acc1);
+ }
+ acc0 = _mm512_add_ps(acc0, acc1);
+ for (; i + 16 <= n; i += 16) {
+ __m512 xv = _mm512_cvtph_ps(_mm256_loadu_si256((const __m256i *)(x + i)));
+ __m512 yv = _mm512_cvtph_ps(_mm256_loadu_si256((const __m256i *)(y + i)));
+ acc0 = _mm512_fmadd_ps(xv, yv, acc0);
+ }
+ float sum = _mm512_reduce_add_ps(acc0);
+ for (; i < n; ++i) {
+ sum += GGML_COMPUTE_FP16_TO_FP32(x[i]) * GGML_COMPUTE_FP16_TO_FP32(y[i]);
+ }
+ *s = sum;
+ return true;
+}
+
+bool llamafile_fa_fp16_to_fp32_row_amd_avx512f(const void *vx, float *y,
+ int64_t n) {
+ const ggml_fp16_t *x = (const ggml_fp16_t *)vx;
+ int64_t i = 0;
+ for (; i + 16 <= n; i += 16) {
+ __m512 v = _mm512_cvtph_ps(_mm256_loadu_si256((const __m256i *)(x + i)));
+ _mm512_storeu_ps(y + i, v);
+ }
+ for (; i < n; ++i) {
+ y[i] = GGML_COMPUTE_FP16_TO_FP32(x[i]);
+ }
+ return true;
+}
+
+} // extern "C"
+
+#endif // __x86_64__
diff --git a/llamafile/fa_helpers_unsupported.cpp b/llamafile/fa_helpers_unsupported.cpp
new file mode 100644
index 00000000..2573e99c
--- /dev/null
+++ b/llamafile/fa_helpers_unsupported.cpp
@@ -0,0 +1,31 @@
+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi
+//
+// Fallback stubs for flash-attention helpers (issue #975).
+//
+// Returning false tells the caller to use the upstream ggml helper.
+// Selected at runtime by sgemm.cpp when the CPU lacks AVX-512F (and
+// any future per-arch FA helper variants we add).
+
+#include "sgemm.h"
+#include "ggml-impl.h"
+#include <cstdint>
+
+extern "C" {
+
+bool llamafile_fa_vec_dot_f16_unsupported(int, float *, const void *,
+ const void *) {
+ return false;
+}
+
+bool llamafile_fa_fp16_to_fp32_row_unsupported(const void *, float *,
+ int64_t) {
+ return false;
+}
+
+bool llamafile_fa_simd_gemm_unsupported(float *, const float *, const float *,
+ int, int, int) {
+ return false;
+}
+
+} // extern "C"
diff --git a/llamafile/fa_simd_gemm_amd_avx512f.cpp b/llamafile/fa_simd_gemm_amd_avx512f.cpp
new file mode 100644
index 00000000..fc1040d6
--- /dev/null
+++ b/llamafile/fa_simd_gemm_amd_avx512f.cpp
@@ -0,0 +1,35 @@
+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi
+//
+// AVX-512F-optimized inline GEMM for CPU flash-attention tiled path
+// (llamafile issue #975).
+//
+// Wraps ggml-cpu's static-inline simd_gemm (in simd-gemm.h) compiled
+// with AVX-512 flags so the FMA inner loop uses 16-lane zmm registers
+// and the wider 4x4 tile config (GEMM_RM=4, GEMM_RN=4 — 16 register-
+// width FMAs per inner iteration) instead of the AVX2 6x2 tile that
+// ops.cpp's default-ISA build gets. Roughly 2.7x peak FMA throughput
+// on Skylake-X+ CPUs (4x16 vs 6x8 lane-FMAs).
+//
+// Called from the tiled FA function at ops.cpp:8660 (KQ = Q @ K) and
+// :8740 (VKQ += KQ @ V). Runtime-dispatched via sgemm.cpp; falls back
+// to upstream's simd_gemm (already inlined in ops.cpp) on CPUs without
+// AVX-512F by returning false.
+
+#ifdef __x86_64__
+
+#include "sgemm.h"
+#include "simd-gemm.h"
+
+extern "C" bool llamafile_fa_simd_gemm_amd_avx512f(float *C, const float *A,
+ const float *B,
+ int M, int K, int N) {
+ // Computes C[M x N] += A[M x K] * B[K x N]. simd_gemm in
+ // simd-gemm.h is a header-static template; compiling this TU with
+ // -Xx86_64-mavx512f gives the included simd_gemm the AVX-512
+ // codegen we want.
+ simd_gemm(C, A, B, M, K, N);
+ return true;
+}
+
+#endif // __x86_64__
diff --git a/llamafile/sgemm.cpp b/llamafile/sgemm.cpp
index 23111a44..82ad0115 100644
--- a/llamafile/sgemm.cpp
+++ b/llamafile/sgemm.cpp
@@ -38,15 +38,27 @@ static bool sgemm_disabled() {
typedef bool (*iqk_mixmul_func_t)(long, long, long, int, int, const void *, const void *, float *,
long, long, const void *, int, int);
+// Flash-attention helper function pointers (issue #975).
+typedef bool (*fa_vec_dot_f16_func_t)(int, float *, const void *, const void *);
+typedef bool (*fa_fp16_to_fp32_row_func_t)(const void *, float *, int64_t);
+typedef bool (*fa_simd_gemm_func_t)(float *, const float *, const float *,
+ int, int, int);
+
static const struct GemmFuncs {
sgemm_func_t sgemm;
typeof(llamafile_mixmul) *mixmul;
iqk_mixmul_func_t iqk_mixmul = iqk_mul_mat_moe_unsupported;
+ fa_vec_dot_f16_func_t fa_vec_dot_f16 = llamafile_fa_vec_dot_f16_unsupported;
+ fa_fp16_to_fp32_row_func_t fa_fp16_to_fp32_row = llamafile_fa_fp16_to_fp32_row_unsupported;
+ fa_simd_gemm_func_t fa_simd_gemm = llamafile_fa_simd_gemm_unsupported;
GemmFuncs() {
if (sgemm_disabled()) {
sgemm = llamafile_sgemm_unsupported;
mixmul = llamafile_mixmul_unsupported;
iqk_mixmul = iqk_mul_mat_moe_unsupported;
+ fa_vec_dot_f16 = llamafile_fa_vec_dot_f16_unsupported;
+ fa_fp16_to_fp32_row = llamafile_fa_fp16_to_fp32_row_unsupported;
+ fa_simd_gemm = llamafile_fa_simd_gemm_unsupported;
return;
}
#ifdef __x86_64__
@@ -54,6 +66,10 @@ static const struct GemmFuncs {
if (X86_HAVE(FMA)) {
if (X86_HAVE(AVX2)) {
if (X86_HAVE(AVX512F)) {
+ // FA helpers (issue #975): AVX-512F is enough.
+ fa_vec_dot_f16 = llamafile_fa_vec_dot_f16_amd_avx512f;
+ fa_fp16_to_fp32_row = llamafile_fa_fp16_to_fp32_row_amd_avx512f;
+ fa_simd_gemm = llamafile_fa_simd_gemm_amd_avx512f;
if (X86_HAVE(AVX512VL) && //
X86_HAVE(AVX512BW) && //
X86_HAVE(AVX512DQ) && //
@@ -173,6 +189,35 @@ bool llamafile_mixmul_iqk(long Nx, long Ny, long ne00, int ne11, int typeA, cons
return funcs.iqk_mixmul(Nx, Ny, ne00, ne11, typeA, A, B, C, nb1, nb2, vrow_mapping, ith, nth);
}
+/**
+ * Optimized f16 dot product for CPU flash-attention inner loop (#975).
+ * Returns true on success; false signals the caller to fall back to
+ * upstream's ggml_vec_dot_f16.
+ */
+bool llamafile_fa_vec_dot_f16(int n, float *s, const void *x, const void *y) {
+ return funcs.fa_vec_dot_f16(n, s, x, y);
+}
+
+/**
+ * Optimized f16-to-f32 row conversion for CPU flash-attention V dequant
+ * (#975). Returns true on success; false signals the caller to fall
+ * back to upstream's ggml_fp16_to_fp32_row.
+ */
+bool llamafile_fa_fp16_to_fp32_row(const void *x, float *y, int64_t n) {
+ return funcs.fa_fp16_to_fp32_row(x, y, n);
+}
+
+/**
+ * Optimized inline GEMM for CPU flash-attention tiled path (#975).
+ * Computes C[M x N] += A[M x K] * B[K x N] in f32. Returns true on
+ * success; false signals the caller (the tiled FA function) to fall
+ * back to ggml-cpu's static-inline simd_gemm.
+ */
+bool llamafile_fa_simd_gemm(float *C, const float *A, const float *B,
+ int M, int K, int N) {
+ return funcs.fa_simd_gemm(C, A, B, M, K, N);
+}
+
/**
* Returns the name of the selected sgemm kernel for diagnostics.
*/
diff --git a/llamafile/sgemm.h b/llamafile/sgemm.h
index d03893a7..eb9e31f6 100644
--- a/llamafile/sgemm.h
+++ b/llamafile/sgemm.h
@@ -86,6 +86,27 @@ bool llamafile_mixmul_arm82(const struct ggml_compute_params *, const struct ggm
bool llamafile_mixmul_iqk(long, long, long, int, int, const void *, const void *, float *, long,
long, const void *, int, int);
+// Flash-attention helpers (issue #975). Optimized replacements for the
+// hot ggml-cpu inner-loop helpers that cosmocc compiles at baseline
+// AVX2. Returns true when handled by the optimized kernel; caller
+// falls back to upstream's ggml helper on false. Public API takes
+// void* so callers don't need ggml.h.
+bool llamafile_fa_vec_dot_f16(int n, float *s, const void *x, const void *y);
+bool llamafile_fa_fp16_to_fp32_row(const void *x, float *y, int64_t n);
+// C[M x N] += A[M x K] * B[K x N], all f32.
+bool llamafile_fa_simd_gemm(float *C, const float *A, const float *B,
+ int M, int K, int N);
+
+// Internal arch-specific implementations of the FA helpers.
+bool llamafile_fa_vec_dot_f16_amd_avx512f(int, float *, const void *, const void *);
+bool llamafile_fa_vec_dot_f16_unsupported(int, float *, const void *, const void *);
+bool llamafile_fa_fp16_to_fp32_row_amd_avx512f(const void *, float *, int64_t);
+bool llamafile_fa_fp16_to_fp32_row_unsupported(const void *, float *, int64_t);
+bool llamafile_fa_simd_gemm_amd_avx512f(float *, const float *, const float *,
+ int, int, int);
+bool llamafile_fa_simd_gemm_unsupported(float *, const float *, const float *,
+ int, int, int);
+
#ifdef __cplusplus
}
#endif
diff --git a/tests/BUILD.mk b/tests/BUILD.mk
index 46b2730b..9ef384ea 100644
--- a/tests/BUILD.mk
+++ b/tests/BUILD.mk
@@ -49,10 +49,60 @@ o/$(MODE)/tests/extract_data_uris_test: \
@mkdir -p $(@D)
$(CXX) $(LDFLAGS) -o $@ $^ $(LDLIBS)
+# ==============================================================================
+# Test: fa_helpers_test (issue #975 numerical equivalence)
+# ==============================================================================
+#
+# Compares llamafile_fa_vec_dot_f16 / llamafile_fa_fp16_to_fp32_row
+# against upstream ggml_vec_dot_f16 / ggml_fp16_to_fp32_row on the
+# same random + edge-case inputs. Catches numerical regressions in
+# the alternative AVX-512F implementations we ship via sgemm.cpp's
+# dispatch. On CPUs without AVX-512F the helpers report unsupported
+# and the corresponding assertions are skipped.
+
+FA_HELPERS_TEST_DEPS := \
+ o/$(MODE)/llamafile/sgemm.o \
+ o/$(MODE)/llamafile/llamafile.o \
+ o/$(MODE)/llamafile/fa_helpers_amd_avx512f.o \
+ o/$(MODE)/llamafile/fa_helpers_unsupported.o \
+ o/$(MODE)/llamafile/fa_simd_gemm_amd_avx512f.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_sgemm_amd_avx.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_sgemm_amd_fma.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_sgemm_amd_avx2.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_sgemm_amd_avxvnni.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_sgemm_amd_avx512f.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_sgemm_amd_zen4.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_sgemm_arm80.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_sgemm_arm82.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_unsupported.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_mixmul_amd_avx.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_mixmul_amd_fma.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_mixmul_amd_avx2.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_mixmul_amd_avxvnni.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_mixmul_amd_avx512f.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_mixmul_amd_zen4.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_mixmul_arm80.o \
+ o/$(MODE)/llamafile/tinyblas_cpu_mixmul_arm82.o \
+ o/$(MODE)/llamafile/iqk_mul_mat_amd_avx2.o \
+ o/$(MODE)/llamafile/iqk_mul_mat_amd_zen4.o \
+ o/$(MODE)/llamafile/iqk_mul_mat_arm82.o \
+ o/$(MODE)/llama.cpp/llama.cpp.a
+
+o/$(MODE)/tests/fa_helpers_test.o: tests/fa_helpers_test.cpp
+ @mkdir -p $(@D)
+ $(CXX) $(CXXFLAGS) $(TESTS_CPPFLAGS) -fopenmp -c -o $@ $<
+
+o/$(MODE)/tests/fa_helpers_test: \
+ o/$(MODE)/tests/fa_helpers_test.o \
+ $(FA_HELPERS_TEST_DEPS)
+ @mkdir -p $(@D)
+ $(CXX) $(LDFLAGS) -fopenmp -o $@ $^ $(LDLIBS)
+
# ==============================================================================
# Phony targets
# ==============================================================================
.PHONY: o/$(MODE)/tests
o/$(MODE)/tests: \
- o/$(MODE)/tests/extract_data_uris_test.runs
+ o/$(MODE)/tests/extract_data_uris_test.runs \
+ o/$(MODE)/tests/fa_helpers_test.runs
diff --git a/tests/fa_helpers_test.cpp b/tests/fa_helpers_test.cpp
new file mode 100644
index 00000000..3e92ba0e
--- /dev/null
+++ b/tests/fa_helpers_test.cpp
@@ -0,0 +1,523 @@
+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi
+//
+// Copyright 2026 Mozilla Foundation
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+// Numerical-equivalence tests for the llamafile flash-attention helpers
+// (issue #975).
+//
+// These tests compare our AVX-512-optimized llamafile_fa_* helpers
+// against the upstream ggml-cpu reference implementations. Goal: ensure
+// the alternative low-level math we ship via llamafile/sgemm.cpp's
+// dispatch produces output that's numerically equivalent to the
+// reference (bit-identical for the conversion helper, within ULP
+// tolerance for the reduction helper).
+//
+// Run via `make check`. On CPUs without AVX-512F the helpers report
+// "not supported" and the corresponding assertions are skipped (the
+// test reports skipped count); the test still validates the dispatch
+// table wiring.
+
+#include "ggml.h"
+#include "sgemm.h"
+#include <cstdio>
+#include <cstdint>
+#include <cstring>
+#include <cmath>
+#include <cfloat>
+#include <random>
+#include <vector>
+#include <algorithm>
+
+// ggml_vec_dot_f16 is defined in ggml-cpu/vec.cpp but not declared in a
+// public header (it's reached through type_traits dispatch). Declare it
+// here for the test.
+extern "C" void ggml_vec_dot_f16(int n, float *s, size_t bs,
+ ggml_fp16_t *x, size_t bx,
+ ggml_fp16_t *y, size_t by, int nrc);
+
+static int test_count = 0;
+static int fail_count = 0;
+static int skip_count = 0;
+
+// Each TEST() body runs from main(), NOT at static-init time, because
+// the upstream ggml helpers we compare against (ggml_fp16_to_fp32_row
+// in particular) depend on a lookup table populated by ggml's graph-
+// compute first-call init. We init that via a tiny graph-compute in
+// main() before invoking any test. Tests register themselves into a
+// list at static-init time, then main() iterates and runs them.
+struct TestEntry {
+ const char *name;
+ void (*fn)();
+};
+static TestEntry g_tests[64];
+static int g_test_count_registered = 0;
+
+#define TEST(name) \
+ static void test_##name(); \
+ static struct TestRegister_##name { \
+ TestRegister_##name() { \
+ g_tests[g_test_count_registered++] = { #name, test_##name }; \
+ } \
+ } test_register_##name; \
+ static void test_##name()
+
+#define ASSERT_TRUE(cond, msg) \
+ do { \
+ test_count++; \
+ if (!(cond)) { \
+ fprintf(stderr, "FAIL: %s (%s:%d)\n condition: %s\n", \
+ msg, __FILE__, __LINE__, #cond); \
+ fail_count++; \
+ } \
+ } while (0)
+
+#define ASSERT_BITEQ_F32(expected, actual, msg) \
+ do { \
+ test_count++; \
+ uint32_t e_bits, a_bits; \
+ memcpy(&e_bits, &(expected), sizeof(uint32_t)); \
+ memcpy(&a_bits, &(actual), sizeof(uint32_t)); \
+ if (e_bits != a_bits) { \
+ fprintf(stderr, "FAIL: %s (%s:%d)\n" \
+ " expected: %.9g (0x%08x)\n" \
+ " actual: %.9g (0x%08x)\n", \
+ msg, __FILE__, __LINE__, \
+ (double)(expected), e_bits, \
+ (double)(actual), a_bits); \
+ fail_count++; \
+ } \
+ } while (0)
+
+#define ASSERT_NEAR_F32(expected, actual, tol, msg) \
+ do { \
+ test_count++; \
+ float diff = fabsf((expected) - (actual)); \
+ if (!(diff <= (tol))) { /* using <= to fail on NaN */ \
+ fprintf(stderr, "FAIL: %s (%s:%d)\n" \
+ " expected: %.9g\n" \
+ " actual: %.9g\n" \
+ " diff: %.9g (tol %.9g)\n", \
+ msg, __FILE__, __LINE__, \
+ (double)(expected), (double)(actual), \
+ (double)diff, (double)(tol)); \
+ fail_count++; \
+ } \
+ } while (0)
+
+// Test sizes covering typical attention head dims plus odd tail sizes
+// to exercise the scalar leftover loop.
+static const std::vector<int> kTestSizes = {
+ 1, 8, 15, 16, 17, 32, 33, 64, 80, 96, 128, 129, 192, 256, 512, 1024
+};
+
+// Fill a vector with random f16 values in N(0, 0.1) — typical layer
+// activation range after LayerNorm. Uses a fixed seed for determinism.
+static void fill_random_f16(std::vector<ggml_fp16_t> &out, uint64_t seed) {
+ std::mt19937_64 rng(seed);
+ std::normal_distribution<float> dist(0.0f, 0.1f);
+ for (auto &v : out) {
+ v = ggml_fp32_to_fp16(dist(rng));
+ }
+}
+
+// Tolerance for vec_dot_f16: both implementations convert to f32 and
+// sum, but in different chunk sizes (AVX2: 8-wide; AVX-512: 16-wide).
+// The reduction order differs, so we allow a relative error
+// proportional to n (Wilkinson-style summed-product bound: O(n) terms
+// each at unit-roundoff eps/2, with a small safety factor). max_abs
+// here is the peak |x[i]*y[i]|, an upper bound for the running partial
+// sum scale.
+static float vec_dot_tol(int n, const std::vector<ggml_fp16_t> &x,
+ const std::vector<ggml_fp16_t> &y) {
+ float max_abs = 0.0f;
+ for (int i = 0; i < n; ++i) {
+ float xv = ggml_fp16_to_fp32(x[i]);
+ float yv = ggml_fp16_to_fp32(y[i]);
+ max_abs = std::max(max_abs, std::fabs(xv) * std::fabs(yv));
+ }
+ return std::max(1e-5f, 8.0f * (float)n * FLT_EPSILON * max_abs);
+}
+
+// ============================================================================
+// fp16_to_fp32_row: per-element conversion. Both ggml's helper and ours
+// use _mm*_cvtph_ps, which is IEEE-754 deterministic per element. We
+// expect BIT-IDENTICAL output regardless of SIMD width.
+// ============================================================================
+
+TEST(fp16_to_fp32_row_normal_inputs) {
+ for (int n : kTestSizes) {
+ std::vector<ggml_fp16_t> input(n);
+ std::vector<float> ref_out(n), our_out(n);
+ fill_random_f16(input, /*seed=*/0xDEADBEEFCAFEull ^ (uint64_t)n);
+
+ ggml_fp16_to_fp32_row(input.data(), ref_out.data(), n);
+ bool handled = llamafile_fa_fp16_to_fp32_row(input.data(), our_out.data(), n);
+
+ if (!handled) {
+ skip_count++;
+ continue;
+ }
+
+ char msg[128];
+ for (int i = 0; i < n; ++i) {
+ snprintf(msg, sizeof(msg),
+ "fp16_to_fp32_row n=%d i=%d (normal inputs)", n, i);
+ ASSERT_BITEQ_F32(ref_out[i], our_out[i], msg);
+ }
+ }
+}
+
+TEST(fp16_to_fp32_row_edge_values) {
+ // Include ±0, ±INF, denormals, NaN, and the f16 min/max.
+ std::vector<ggml_fp16_t> input = {
+ ggml_fp32_to_fp16( 0.0f),
+ ggml_fp32_to_fp16(-0.0f),
+ ggml_fp32_to_fp16( INFINITY),
+ ggml_fp32_to_fp16(-INFINITY),
+ ggml_fp32_to_fp16(NAN),
+ ggml_fp32_to_fp16( 65504.0f), // f16 max finite
+ ggml_fp32_to_fp16(-65504.0f), // f16 min finite
+ ggml_fp32_to_fp16( 6.10e-5f), // f16 smallest normal
+ ggml_fp32_to_fp16( 5.96e-8f), // f16 smallest denormal
+ ggml_fp32_to_fp16( 1.0f),
+ ggml_fp32_to_fp16(-1.0f),
+ ggml_fp32_to_fp16( 0.5f),
+ ggml_fp32_to_fp16( 0.125f),
+ ggml_fp32_to_fp16( 0.0625f),
+ ggml_fp32_to_fp16( 0.00390625f),
+ ggml_fp32_to_fp16( 65000.0f),
+ };
+ int n = (int)input.size();
+ std::vector<float> ref_out(n), our_out(n);
+
+ ggml_fp16_to_fp32_row(input.data(), ref_out.data(), n);
+ bool handled = llamafile_fa_fp16_to_fp32_row(input.data(), our_out.data(), n);
+
+ if (!handled) {
+ skip_count++;
+ return;
+ }
+
+ char msg[128];
+ for (int i = 0; i < n; ++i) {
+ // For NaN, only assert both are NaN (any NaN representation is OK).
+ if (std::isnan(ref_out[i]) || std::isnan(our_out[i])) {
+ test_count++;
+ if (!(std::isnan(ref_out[i]) && std::isnan(our_out[i]))) {
+ fprintf(stderr,
+ "FAIL: fp16_to_fp32_row edge values i=%d: "
+ "NaN mismatch (ref nan=%d, our nan=%d)\n",
+ i, std::isnan(ref_out[i]), std::isnan(our_out[i]));
+ fail_count++;
+ }
+ continue;
+ }
+ snprintf(msg, sizeof(msg),
+ "fp16_to_fp32_row edge values i=%d", i);
+ ASSERT_BITEQ_F32(ref_out[i], our_out[i], msg);
+ }
+}
+
+// ============================================================================
+// vec_dot_f16: reduction, allow ULP tolerance because chunk widths
+// differ between ref (AVX2 8-wide) and ours (AVX-512 16-wide).
+// ============================================================================
+
+TEST(vec_dot_f16_normal_inputs) {
+ for (int n : kTestSizes) {
+ std::vector<ggml_fp16_t> x(n), y(n);
+ fill_random_f16(x, /*seed=*/0xA5A5A5A5A5A5A5A5ull ^ (uint64_t)n);
+ fill_random_f16(y, /*seed=*/0x5A5A5A5A5A5A5A5Aull ^ (uint64_t)n);
+
+ float ref = 0.0f, our = 0.0f;
+ ggml_vec_dot_f16(n, &ref, /*bs=*/0, x.data(), /*bx=*/0,
+ y.data(), /*by=*/0, /*nrc=*/1);
+ bool handled = llamafile_fa_vec_dot_f16(n, &our, x.data(), y.data());
+
+ if (!handled) {
+ skip_count++;
+ continue;
+ }
+
+ char msg[128];
+ snprintf(msg, sizeof(msg),
+ "vec_dot_f16 n=%d (normal inputs)", n);
+ ASSERT_NEAR_F32(ref, our, vec_dot_tol(n, x, y), msg);
+ }
+}
+
+TEST(vec_dot_f16_adversarial_reduction_order) {
+ // To actually stress reduction-order sensitivity, the per-element
+ // products x[i]*y[i] must alternate sign — otherwise SIMD width
+ // doesn't change the result. Use a scale of 10 so |product| = 100
+ // (well within f16 range): partial sums oscillate by ±100 across
+ // steps, and AVX2 (8-wide) vs AVX-512 (16-wide) reduction trees
+ // pair the cancelling terms in different orders, amplifying any
+ // floating-point drift.
+ // x[i] = (i & 1) ? -10 : +10 → [+, -, +, -, ...]
+ // y[i] = ((i / 2) & 1) ? -10 : +10 → [+, +, -, -, ...]
+ // products = x[i]*y[i] alternate as [+, -, -, +, +, -, -, +, ...]
+ for (int n : kTestSizes) {
+ if (n < 2) continue;
+ std::vector<ggml_fp16_t> x(n), y(n);
+ const float scale = 10.0f;
+ for (int i = 0; i < n; ++i) {
+ x[i] = ggml_fp32_to_fp16((i & 1) ? -scale : scale);
+ y[i] = ggml_fp32_to_fp16(((i / 2) & 1) ? -scale : scale);
+ }
+
+ float ref = 0.0f, our = 0.0f;
+ ggml_vec_dot_f16(n, &ref, 0, x.data(), 0, y.data(), 0, 1);
+ bool handled = llamafile_fa_vec_dot_f16(n, &our, x.data(), y.data());
+
+ if (!handled) {
+ skip_count++;
+ continue;
+ }
+
+ // Worst-case drift bound: ~n * eps * max_partial_sum_scale.
+ // max |x[i]*y[i]| = scale^2 = 100. Use 4 * n * eps * 100 with
+ // a small absolute floor for tiny n.
+ float tol = std::max(1e-4f, 4.0f * (float)n * FLT_EPSILON * scale * scale);
+ char msg[128];
+ snprintf(msg, sizeof(msg),
+ "vec_dot_f16 n=%d (adversarial alternating-sign products)", n);
+ ASSERT_NEAR_F32(ref, our, tol, msg);
+ }
+}
+
+TEST(vec_dot_f16_zeros) {
+ // All-zero inputs: result must be exactly 0.0f, bit-identical.
+ for (int n : kTestSizes) {
+ std::vector<ggml_fp16_t> x(n, ggml_fp32_to_fp16(0.0f));
+ std::vector<ggml_fp16_t> y(n, ggml_fp32_to_fp16(0.0f));
+
+ float ref = 999.0f, our = 999.0f;
+ ggml_vec_dot_f16(n, &ref, 0, x.data(), 0, y.data(), 0, 1);
+ bool handled = llamafile_fa_vec_dot_f16(n, &our, x.data(), y.data());
+
+ if (!handled) {
+ skip_count++;
+ continue;
+ }
+
+ float zero = 0.0f;
+ char msg[128];
+ snprintf(msg, sizeof(msg), "vec_dot_f16 n=%d (zeros) ref", n);
+ ASSERT_BITEQ_F32(zero, ref, msg);
+ snprintf(msg, sizeof(msg), "vec_dot_f16 n=%d (zeros) ours", n);
+ ASSERT_BITEQ_F32(zero, our, msg);
+ }
+}
+
+TEST(dispatch_wiring) {
+ // Sanity check: regardless of whether the AVX-512F variant is
+ // available, the wrapper must return without crashing for trivial
+ // input. If our dispatch table got mis-wired (e.g., function pointer
+ // to wrong arch), this would catch it.
+ std::vector<ggml_fp16_t> tiny = {
+ ggml_fp32_to_fp16(0.5f), ggml_fp32_to_fp16(-0.25f),
+ ggml_fp32_to_fp16(1.0f), ggml_fp32_to_fp16( 0.125f),
+ };
+ float dot = -1.0f;
+ bool dot_handled = llamafile_fa_vec_dot_f16((int)tiny.size(), &dot,
+ tiny.data(), tiny.data());
+ ASSERT_TRUE(dot_handled || dot == -1.0f,
+ "vec_dot_f16: if not handled, output must be untouched");
+
+ std::vector<float> out(tiny.size(), -999.0f);
+ bool conv_handled = llamafile_fa_fp16_to_fp32_row(tiny.data(), out.data(),
+ (int64_t)tiny.size());
+ ASSERT_TRUE(conv_handled || out[0] == -999.0f,
+ "fp16_to_fp32_row: if not handled, output must be untouched");
+}
+
+// ============================================================================
+// simd_gemm: C[M x N] += A[M x K] * B[K x N], all f32. We compare our
+// AVX-512 wrapper against a scalar reference because the upstream
+// ggml-cpu simd_gemm is `static inline` in a header and isn't directly
+// linkable here. The scalar reference is the exact math the wrapper
+// must reproduce; both implementations are well-defined up to FMA
+// associativity (FMA rounding doesn't commute across reduction orders).
+// Tolerance: 4 * K * eps * max(|A|*|B|) which matches the worst-case
+// summed-product bound.
+// ============================================================================
+
+static void scalar_gemm_reference(float *C, const float *A, const float *B,
+ int M, int K, int N) {
+ for (int i = 0; i < M; ++i) {
+ for (int j = 0; j < N; ++j) {
+ float acc = C[i * N + j];
+ for (int k = 0; k < K; ++k) {
+ acc += A[i * K + k] * B[k * N + j];
+ }
+ C[i * N + j] = acc;
+ }
+ }
+}
+
+static float gemm_tol(int K, float scale) {
+ return std::max(1e-4f, 8.0f * (float)K * FLT_EPSILON * scale * scale);
+}
+
+static void fill_random_f32(std::vector<float> &v, uint64_t seed,
+ float stddev = 0.1f) {
+ std::mt19937_64 rng(seed);
+ std::normal_distribution<float> dist(0.0f, stddev);
+ for (auto &x : v) x = dist(rng);
+}
+
+TEST(simd_gemm_typical_fa_tile_shapes) {
+ // Shapes that match the FA tile dispatch in ops.cpp's tiled function
+ // (Q_TILE_SZ x KV_TILE_SZ for the KQ matmul, Q_TILE_SZ x DV for the
+ // VKQ accumulation). Common head dims: 64, 80, 96, 128. Common tile
+ // sizes from ggml_fa_tile_config: 4-16 Q rows, 32-128 KV columns.
+ struct Shape { int M, K, N; const char *label; };
+ Shape shapes[] = {
+ { 4, 128, 64, "KQ: Q4 x DK128 x KV64" },
+ { 8, 128, 64, "KQ: Q8 x DK128 x KV64" },
+ { 16, 128, 128, "KQ: Q16 x DK128 x KV128" },
+ { 4, 64, 128, "VKQ: Q4 x KV64 x DV128" },
+ { 8, 64, 128, "VKQ: Q8 x KV64 x DV128" },
+ { 16, 128, 128, "VKQ: Q16 x KV128 x DV128" },
+ { 4, 96, 80, "odd: Q4 x 96 x 80" },
+ { 16, 64, 32, "narrow: Q16 x 64 x 32" },
+ };
+ for (auto &s : shapes) {
+ std::vector<float> A(s.M * s.K), B(s.K * s.N);
+ std::vector<float> C_ref(s.M * s.N), C_our(s.M * s.N);
+ uint64_t seed = 0xC0FFEEull ^ (uint64_t)(s.M * 31 + s.K * 17 + s.N);
+ fill_random_f32(A, seed);
+ fill_random_f32(B, seed ^ 0xDEADBEEFull);
+ // Pre-fill C with random values to test the += accumulation.
+ fill_random_f32(C_ref, seed ^ 0xFACEFEEDull);
+ C_our = C_ref;
+
+ scalar_gemm_reference(C_ref.data(), A.data(), B.data(),
+ s.M, s.K, s.N);
+ bool handled = llamafile_fa_simd_gemm(C_our.data(), A.data(),
+ B.data(), s.M, s.K, s.N);
+
+ if (!handled) {
+ skip_count++;
+ continue;
+ }
+
+ char msg[160];
+ float tol = gemm_tol(s.K, 0.5f); // stddev 0.1 → max |a|*|b| ~ 0.5
+ for (int i = 0; i < s.M; ++i) {
+ for (int j = 0; j < s.N; ++j) {
+ snprintf(msg, sizeof(msg),
+ "simd_gemm %s i=%d j=%d", s.label, i, j);
+ ASSERT_NEAR_F32(C_ref[i * s.N + j], C_our[i * s.N + j], tol, msg);
+ }
+ }
+ }
+}
+
+TEST(simd_gemm_zero_accumulator) {
+ // Start from C=0 so the result is purely A*B (no += round-off).
+ // Verifies the kernel handles a zero starting accumulator correctly.
+ int M = 8, K = 128, N = 128;
+ std::vector<float> A(M * K), B(K * N);
+ std::vector<float> C_ref(M * N, 0.0f), C_our(M * N, 0.0f);
+ fill_random_f32(A, 0x1234);
+ fill_random_f32(B, 0x5678);
+
+ scalar_gemm_reference(C_ref.data(), A.data(), B.data(), M, K, N);
+ bool handled = llamafile_fa_simd_gemm(C_our.data(), A.data(), B.data(),
+ M, K, N);
+ if (!handled) {
+ skip_count++;
+ return;
+ }
+ char msg[160];
+ float tol = gemm_tol(K, 0.5f);
+ for (int i = 0; i < M; ++i) {
+ for (int j = 0; j < N; ++j) {
+ snprintf(msg, sizeof(msg),
+ "simd_gemm zero-acc i=%d j=%d", i, j);
+ ASSERT_NEAR_F32(C_ref[i * N + j], C_our[i * N + j], tol, msg);
+ }
+ }
+}
+
+TEST(simd_gemm_dispatch_wiring) {
+ int M = 4, K = 16, N = 32;
+ std::vector<float> A(M * K, 1.0f), B(K * N, 1.0f);
+ std::vector<float> C(M * N, -777.0f);
+ bool handled = llamafile_fa_simd_gemm(C.data(), A.data(), B.data(),
+ M, K, N);
+ ASSERT_TRUE(handled || C[0] == -777.0f,
+ "simd_gemm: if not handled, output must be untouched");
+ if (handled) {
+ // Each C[i,j] = -777 + sum_k(1 * 1) = -777 + K = -761
+ for (int i = 0; i < M; ++i) {
+ for (int j = 0; j < N; ++j) {
+ test_count++;
+ float expected = -777.0f + (float)K;
+ if (fabsf(C[i * N + j] - expected) > 1e-5f) {
+ fprintf(stderr, "FAIL: simd_gemm dispatch i=%d j=%d "
+ "expected %.3f got %.3f\n",
+ i, j, expected, C[i * N + j]);
+ fail_count++;
+ }
+ }
+ }
+ }
+}
+
+// ggml's f16↔f32 lookup table (used by ggml_vec_dot_f16's scalar tail
+// in simd-mappings.h via GGML_CPU_FP16_TO_FP32). Populated by ggml's
+// graph compute first-call init; we replicate the population here so
+// the tests don't depend on running a graph.
+extern "C" float ggml_table_f32_f16[1 << 16];
+
+static void init_ggml_tables() {
+ for (int i = 0; i < (1 << 16); ++i) {
+ ggml_fp16_t f16 = (ggml_fp16_t)(uint16_t)i;
+ ggml_table_f32_f16[i] = ggml_fp16_to_fp32(f16);
+ }
+}
+
+int main(int argc, char *argv[]) {
+ (void)argc;
+ (void)argv;
+
+ // Must happen before any test runs ggml_vec_dot_f16.
+ init_ggml_tables();
+
+ fprintf(stderr, "Running fa_helpers tests (issue #975) — %d tests registered\n",
+ g_test_count_registered);
+
+ for (int i = 0; i < g_test_count_registered; ++i) {
+ fprintf(stderr, " [%d/%d] %s\n", i + 1, g_test_count_registered,
+ g_tests[i].name);
+ g_tests[i].fn();
+ }
+
+ if (fail_count > 0) {
+ fprintf(stderr, "\n%d/%d assertions FAILED (%d skipped — CPU "
+ "doesn't have the optimized variant)\n",
+ fail_count, test_count, skip_count);
+ return 1;
+ }
+
+ fprintf(stderr, "All %d assertions PASSED (%d skipped — CPU doesn't "
+ "have the optimized variant)\n",
+ test_count, skip_count);
+ return 0;
+}