From 5fcce7c1d8da668e263277dfdd54b6508018d53d Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 6 Nov 2026 23:42:08 -0500 Subject: [PATCH 1/6] Fix ARM F16 dot accumulation overflow --- .github/workflows/validate_wrapper.yml | 4 +- CMakeLists.txt | 13 + docs/native174_f16_dot_accumulation.md | 71 ++++++ .../0005-arm-f16-dot-f32-accumulation.patch | 48 ++++ patches/llama.cpp/README.md | 17 ++ patches/llama.cpp/series.json | 11 + tests/f16_dot_accumulation_test.cpp | 234 ++++++++++++++++++ tests/test_llama_cpp_patches.py | 39 ++- tools/linux_cpu_variant_smoke.c | 91 ++++++- 9 files changed, 525 insertions(+), 3 deletions(-) create mode 100644 docs/native174_f16_dot_accumulation.md create mode 100644 patches/llama.cpp/0005-arm-f16-dot-f32-accumulation.patch create mode 100644 tests/f16_dot_accumulation_test.cpp diff --git a/.github/workflows/validate_wrapper.yml b/.github/workflows/validate_wrapper.yml index 70d679f5..b4ed2f7c 100644 --- a/.github/workflows/validate_wrapper.yml +++ b/.github/workflows/validate_wrapper.yml @@ -519,6 +519,7 @@ jobs: run: >- cmake --build build/wrapper-contract --target llamadart_owner_api_test llamadart_owner_reentrancy_test + llamadart_f16_dot_accumulation_test llamadart_speculative_api_test llamadart_build_identity_test llamadart_cancel_flag_test @@ -717,6 +718,7 @@ jobs: cmake --build ${{ matrix.build_dir }} --target llamadart_owner_api_test llamadart_owner_reentrancy_test llamadart_exit_teardown_test llamadart_image_token_limit_test llamadart_build_identity_test llamadart_cancel_flag_test + llamadart_f16_dot_accumulation_test - name: Validate wrapper exports and the static destructor binding run: >- python3 tools/validate_exports.py --format nm --tool nm @@ -727,7 +729,7 @@ jobs: # the Metal library, which takes most of a minute. - name: Run the exit teardown scenarios run: >- - ctest --test-dir ${{ matrix.build_dir }} -R "owner_|exit_teardown|image_token_limit|build_identity|cancel_flag" + ctest --test-dir ${{ matrix.build_dir }} -R "owner_|exit_teardown|image_token_limit|build_identity|cancel_flag|f16_dot_accumulation" --timeout 300 --output-on-failure # A model that nothing tracks aborts at exit when Metal residency sets # are live. Whether a runner has them is outside this repository's diff --git a/CMakeLists.txt b/CMakeLists.txt index 4aa1dc0c..fe3b5b1d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -313,6 +313,19 @@ target_include_directories(llamadart_lib PRIVATE if (LLAMADART_BUILD_TESTS) enable_testing() + add_executable(llamadart_f16_dot_accumulation_test tests/f16_dot_accumulation_test.cpp) + target_compile_features(llamadart_f16_dot_accumulation_test PRIVATE cxx_std_17) + target_link_libraries(llamadart_f16_dot_accumulation_test PRIVATE ggml ggml-base) + if (GGML_BACKEND_DL) + target_compile_definitions(llamadart_f16_dot_accumulation_test PRIVATE + LLAMADART_TEST_CPU_BACKEND="$") + add_dependencies(llamadart_f16_dot_accumulation_test ggml-cpu) + else() + target_link_libraries(llamadart_f16_dot_accumulation_test PRIVATE ggml-cpu) + endif() + add_test(NAME llamadart_f16_dot_accumulation_test COMMAND llamadart_f16_dot_accumulation_test) + set_tests_properties(llamadart_f16_dot_accumulation_test PROPERTIES TIMEOUT 30) + add_library(llamadart_owner_creation_gate SHARED tests/owner_creation_gate.cpp) target_compile_features(llamadart_owner_creation_gate PRIVATE cxx_std_17) target_include_directories(llamadart_owner_creation_gate PRIVATE diff --git a/docs/native174_f16_dot_accumulation.md b/docs/native174_f16_dot_accumulation.md new file mode 100644 index 00000000..51544a54 --- /dev/null +++ b/docs/native174_f16_dot_accumulation.md @@ -0,0 +1,71 @@ +# ARM F16 dot accumulation candidate (#174) + +This source candidate repairs non-SVE NEON F16 dot products that overflow in +F16 before being returned as F32. It changes only `ggml_vec_dot_f16` in a +build-tree copy of upstream `ggml/src/ggml-cpu/vec.cpp`. Multiplication, +accumulation and reduction use F32; four low/high accumulator pairs preserve +the 32-element unroll, with full eight-element and scalar tails. + +Tracking: [native #174](https://github.com/leehack/llamadart-native/issues/174), +[upstream #31734](https://github.com/ggml-org/llama.cpp/issues/31734). +The base is owner `05ef9a48a2bd1db2f4208a89c393794412e9cb74`, pinned upstream +`8642541b255bfb5dc39cd351a178be09013a55d6`. + +## Evidence and scope + +ROOT reproduced `inf` with success status for the magnitude 80/90/100 F16 +operator cases against actual public `v0.8.0-3` macOS ARM64 and Linux ARM64 +`linux_armv8.2_2`/`linux_armv8.6_1` modules. The Linux baseline passes all +11 cases. These are model-free operator results, not public-model/app +failures or proof of a new release regression. Severity remains P2. + +The carried branch requires NEON, FMA, IEEE F16, FP16 vector arithmetic and +no SVE. Global SIMD mappings, ABI, ISA flags, CPU variant selection and cache +defaults are unchanged. FHM intrinsics are deferred: this conversion/F32-FMA +candidate adds no instruction-family or toolchain requirement. Other F16 +kernels, including separate llamafile GEMM, are outside the repair. + +Patch 0005 requests the explicit, issue-specific policy exception described +in [the patch policy](../patches/llama.cpp/README.md#proposed-exception-for-native-174). +Disabling optimized FP16 is a broad build workaround; this internal correctness +repair is more than a few lines. Neither original eligibility condition is +claimed satisfied. Acceptance requires explicit maintainer approval of this +exception in the PR; publication is a separate decision. + +## Durable checks and remaining gates + +`llamadart_f16_dot_accumulation_test` uses production ggml graph/backend APIs, +with one CPU thread and checks that remain active in Release. It covers +operator magnitudes, vector/tail boundaries and synthetic ordinary/flash +attention. These tests must be compiled and run before claiming corrected +behavior. Attention failure/restoration is unverified until then. Zero-length kernel +execution and noncontiguous/strided tensor paths are not covered by this +candidate test; the width sweep begins at one. +The Linux compatibility smoke retains its original matrix shape and rejects +nonfinite results/errors explicitly. + +Source-only Python patch checks cover exact application, markers, mismatch +skip/strict failure and pristine upstream preservation. Android and Apple +artifact markers retain the patch in release validation. The always-active +negative-length guard carries the marker; its presence proves inclusion, +not numerical correctness. Verify the marker in every actual optimized and +baseline module, including Linux variants. + +Before merge or publication, ROOT must provide: + +- Paired original/candidate/reverted builds with identical source and flags, + finite/reference checks and exact module identities for the frozen 11-case + probe and the durable numeric test. Preserve original failures as evidence. +- Actual selected Linux/Android variant correctness and ISA containment; + SVE, iOS and Windows remain separate platform gates. Existing ISA source + fingerprints cover pristine upstream, so audit compiled patched copies too. +- Paired timing for dot lengths 64/128/256 and CPU prefill/decode with F16 KV, + FA off/on, using identical available public model bytes, threads and inputs. + F32 widening can slow the hot loop; no zero-regression claim is made. +- An independent review of the exact candidate revision and explicit approval + of the narrow patch-policy exception. No owner release or core/Apple pin + adoption follows automatically. + +Remove this patch only when the pinned upstream and every compatibility lane +contain a verified upstream repair, or the defect no longer reproduces without +it. No `upstream_fix` string is invented before such a repair exists. diff --git a/patches/llama.cpp/0005-arm-f16-dot-f32-accumulation.patch b/patches/llama.cpp/0005-arm-f16-dot-f32-accumulation.patch new file mode 100644 index 00000000..4be4e528 --- /dev/null +++ b/patches/llama.cpp/0005-arm-f16-dot-f32-accumulation.patch @@ -0,0 +1,48 @@ +--- a/ggml/src/ggml-cpu/vec.cpp ++++ b/ggml/src/ggml-cpu/vec.cpp +@@ -263,4 +263,5 @@ + + void ggml_vec_dot_f16(int n, float * GGML_RESTRICT s, size_t bs, ggml_fp16_t * GGML_RESTRICT x, size_t bx, ggml_fp16_t * GGML_RESTRICT y, size_t by, int nrc) { ++ GGML_ASSERT(n >= 0 && "llamadart F16 dot F32 accumulation"); + assert(nrc == 1); + GGML_UNUSED(nrc); +@@ -272,5 +273,38 @@ + + +-#if defined(GGML_SIMD) ++#if defined(__ARM_NEON) && defined(__ARM_FEATURE_FMA) && defined(__ARM_FP16_FORMAT_IEEE) && \ ++ defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC) && !defined(__ARM_FEATURE_SVE) ++ // F16 products and partial sums can overflow before the F32 result is stored. ++ float32x4_t sum_lo[4], sum_hi[4]; ++ for (int j = 0; j < 4; ++j) { ++ sum_lo[j] = vdupq_n_f32(0.0f); ++ sum_hi[j] = vdupq_n_f32(0.0f); ++ } ++ const int np = n - n % 32; ++ const int np8 = n - n % 8; ++ int i = 0; ++ for (; i < np; i += 32) { ++ for (int j = 0; j < 4; ++j) { ++ const float16x8_t vx = vld1q_f16((const __fp16 *) (x + i + 8*j)); ++ const float16x8_t vy = vld1q_f16((const __fp16 *) (y + i + 8*j)); ++ sum_lo[j] = vfmaq_f32(sum_lo[j], vcvt_f32_f16(vget_low_f16(vx)), vcvt_f32_f16(vget_low_f16(vy))); ++ sum_hi[j] = vfmaq_f32(sum_hi[j], vcvt_f32_f16(vget_high_f16(vx)), vcvt_f32_f16(vget_high_f16(vy))); ++ } ++ } ++ for (; i < np8; i += 8) { ++ const float16x8_t vx = vld1q_f16((const __fp16 *) (x + i)); ++ const float16x8_t vy = vld1q_f16((const __fp16 *) (y + i)); ++ sum_lo[0] = vfmaq_f32(sum_lo[0], vcvt_f32_f16(vget_low_f16(vx)), vcvt_f32_f16(vget_low_f16(vy))); ++ sum_hi[0] = vfmaq_f32(sum_hi[0], vcvt_f32_f16(vget_high_f16(vx)), vcvt_f32_f16(vget_high_f16(vy))); ++ } ++ for (int j = 1; j < 4; ++j) { ++ sum_lo[0] = vaddq_f32(sum_lo[0], sum_lo[j]); ++ sum_hi[0] = vaddq_f32(sum_hi[0], sum_hi[j]); ++ } ++ sumf = (ggml_float) vaddvq_f32(vaddq_f32(sum_lo[0], sum_hi[0])); ++ for (; i < n; ++i) { ++ sumf += (ggml_float) GGML_CPU_FP16_TO_FP32(x[i]) * (ggml_float) GGML_CPU_FP16_TO_FP32(y[i]); ++ } ++#elif defined(GGML_SIMD) + #if defined(__ARM_FEATURE_SVE) + const int ggml_f16_epr = svcnth(); diff --git a/patches/llama.cpp/README.md b/patches/llama.cpp/README.md index c2836f26..fae222ba 100644 --- a/patches/llama.cpp/README.md +++ b/patches/llama.cpp/README.md @@ -17,6 +17,23 @@ these hold: The v0.7.0 embedding-mode reservation repair and its exact baseline/candidate evidence are documented in [v070_native_contracts.md](../../docs/v070_native_contracts.md). +## Proposed exception for native #174 + +Patch 0005 requests a narrow exception to the first two eligibility conditions +above; accepting this change requires explicit maintainer approval of that +exception. Disabling optimized FP16 arithmetic is a build workaround, and this +localized correctness branch is more than a few lines. The ordinary policy +therefore does not literally cover it. + +Published ARM64 artifacts return nonfinite results for finite F16 dot products. +The internal kernel cannot be repaired in wrapper `src/`; globally disabling +FP16 arithmetic would change unrelated kernels and undo optimized CPU variant +performance. Patch 0005 changes only the non-SVE NEON F16 dot implementation, +without changing ISA flags, ABI, variants or cache defaults. Qualification, +performance risk and retirement gates are in +[native174_f16_dot_accumulation.md](../../docs/native174_f16_dot_accumulation.md). +This exception does not extend eligibility to other patches. + ## Files - `series.json` lists the patches in the order they apply. Each entry has the diff --git a/patches/llama.cpp/series.json b/patches/llama.cpp/series.json index 154d7528..82c4321c 100644 --- a/patches/llama.cpp/series.json +++ b/patches/llama.cpp/series.json @@ -38,6 +38,17 @@ "path": "ggml/src/ggml-metal/kernels/unary.metal", "text": "inline constexpr bfloat4 ggml_metal_unary_cast(float4 x) {" } + }, + { + "file": "0005-arm-f16-dot-f32-accumulation.patch", + "tracking": "https://github.com/leehack/llamadart-native/issues/174", + "upstream": "https://github.com/ggml-org/llama.cpp/issues/31734", + "android_markers": [ + {"library": "libggml-cpu.so", "text": "llamadart F16 dot F32 accumulation"} + ], + "apple_markers": [ + {"library": "libllamadart.dylib", "text": "llamadart F16 dot F32 accumulation"} + ] } ] } diff --git a/tests/f16_dot_accumulation_test.cpp b/tests/f16_dot_accumulation_test.cpp new file mode 100644 index 00000000..4d5c084a --- /dev/null +++ b/tests/f16_dot_accumulation_test.cpp @@ -0,0 +1,234 @@ +#include "ggml.h" +#include "ggml-alloc.h" +#include "ggml-backend.h" +#if !defined(LLAMADART_TEST_CPU_BACKEND) +#include "ggml-cpu.h" +#endif + +#include +#include +#include +#include + +namespace { + +void require(bool condition, const char *message) { + if (!condition) { + std::fprintf(stderr, "FAIL: %s\n", message); + std::exit(1); + } +} + +float rounded_f16(float value) { + return ggml_fp16_to_fp32(ggml_fp32_to_fp16(value)); +} + +class Graph { + public: + explicit Graph(ggml_backend_t backend) : backend_(backend) { + ggml_init_params params = {1024 * 1024, nullptr, true}; + ctx = ggml_init(params); + require(ctx != nullptr, "context allocation failed"); + } + + ~Graph() { + ggml_backend_buffer_free(buffer_); + ggml_free(ctx); + } + + void allocate(ggml_tensor *output) { + graph_ = ggml_new_graph(ctx); + require(graph_ != nullptr, "graph allocation failed"); + ggml_build_forward_expand(graph_, output); + buffer_ = ggml_backend_alloc_ctx_tensors(ctx, backend_); + require(buffer_ != nullptr, "tensor buffer allocation failed"); + } + + void compute() { + require(ggml_backend_graph_compute(backend_, graph_) == GGML_STATUS_SUCCESS, + "CPU graph computation failed"); + } + + ggml_context *ctx = nullptr; + + private: + ggml_backend_t backend_; + ggml_cgraph *graph_ = nullptr; + ggml_backend_buffer_t buffer_ = nullptr; +}; + +void check_result(float actual, double expected, double tolerance, + const char *name, int width) { + const double error = std::fabs(static_cast(actual) - expected); + if (!std::isfinite(actual) || !std::isfinite(expected) || + !std::isfinite(error) || error > tolerance) { + std::fprintf(stderr, + "FAIL: %s width=%d expected=%.17g actual=%.9g tolerance=%.9g\n", + name, width, expected, actual, tolerance); + std::exit(1); + } +} + +enum class Pattern { positive, cancellation, large_product, maximum, subnormal }; + +void dot_case(ggml_backend_t backend, int width, float magnitude, + Pattern pattern, ggml_type weight_type, const char *name) { + Graph graph(backend); + auto *k = ggml_new_tensor_2d(graph.ctx, weight_type, width, 1); + auto *q = ggml_new_tensor_2d(graph.ctx, GGML_TYPE_F32, width, 1); + auto *out = ggml_mul_mat(graph.ctx, k, q); + ggml_mul_mat_set_prec(out, GGML_PREC_F32); + graph.allocate(out); + + std::vector keys(width), queries(width); + std::vector half_keys(width); + double reference = 0.0; + double absolute_sum = 0.0; + for (int i = 0; i < width; ++i) { + float kv = magnitude * (1.0f + 0.1f * (i % 5)); + float qv = magnitude * (1.0f + 0.1f * ((i * 3) % 5)); + if (pattern == Pattern::cancellation) { + kv = magnitude; + qv = i < width / 2 ? magnitude : -magnitude; + } else if (pattern == Pattern::large_product) { + kv = qv = 256.0f; + } else if (pattern == Pattern::maximum) { + kv = qv = 65504.0f; + } else if (pattern == Pattern::subnormal) { + kv = ggml_fp16_to_fp32(static_cast(1 + i % 7)); + qv = i % 2 == 0 ? 1.0f : -1.0f; + } + half_keys[i] = ggml_fp32_to_fp16(kv); + keys[i] = kv; + queries[i] = qv; + const double actual_k = weight_type == GGML_TYPE_F16 + ? ggml_fp16_to_fp32(half_keys[i]) : keys[i]; + // The F16 CPU type trait rounds the F32 query before its dot product. + const double actual_q = weight_type == GGML_TYPE_F16 + ? rounded_f16(queries[i]) : queries[i]; + const double product = actual_k * actual_q; + reference += product; + absolute_sum += std::fabs(product); + } + if (weight_type == GGML_TYPE_F16) { + ggml_backend_tensor_set(k, half_keys.data(), 0, half_keys.size() * sizeof(ggml_fp16_t)); + } else { + ggml_backend_tensor_set(k, keys.data(), 0, keys.size() * sizeof(float)); + } + ggml_backend_tensor_set(q, queries.data(), 0, queries.size() * sizeof(float)); + graph.compute(); + float actual = 0.0f; + ggml_backend_tensor_get(out, &actual, 0, sizeof(actual)); + check_result(actual, reference, 1e-7 + 2e-6 * absolute_sum, name, width); +} + +void attention_case(ggml_backend_t backend, bool flash, float magnitude) { + constexpr int width = 64; + constexpr int values = 64; + Graph graph(backend); + auto *q = ggml_new_tensor_2d(graph.ctx, GGML_TYPE_F32, width, 1); + auto *k = ggml_new_tensor_2d(graph.ctx, GGML_TYPE_F16, width, 2); + auto *v = ggml_new_tensor_2d(graph.ctx, GGML_TYPE_F16, + flash ? values : 2, flash ? 2 : values); + const float scale = 1.0f / std::sqrt(static_cast(width)); + ggml_tensor *out; + if (flash) { + out = ggml_flash_attn_ext(graph.ctx, q, k, v, nullptr, scale, 0.0f, 0.0f); + ggml_flash_attn_ext_set_prec(out, GGML_PREC_F32); + } else { + auto *scores = ggml_mul_mat(graph.ctx, k, q); + ggml_mul_mat_set_prec(scores, GGML_PREC_F32); + auto *probabilities = ggml_soft_max_ext(graph.ctx, scores, nullptr, scale, 0.0f); + out = ggml_mul_mat(graph.ctx, v, probabilities); + } + graph.allocate(out); + + std::vector queries(width); + std::vector keys(2 * width), value_data(2 * values); + double score = 0.0; + for (int i = 0; i < width; ++i) { + queries[i] = magnitude * (1.0f + 0.1f * ((i * 3) % 5)); + keys[i] = ggml_fp32_to_fp16(magnitude * (1.0f + 0.1f * (i % 5))); + keys[width + i] = ggml_fp32_to_fp16(0.0f); + score += static_cast(ggml_fp16_to_fp32(keys[i])) * rounded_f16(queries[i]); + } + const double probability0 = 1.0 / (1.0 + std::exp(-score * scale)); + const double probability1 = 1.0 - probability0; + std::vector expected(values); + for (int i = 0; i < values; ++i) { + const float v0 = 1.0f + (i % 7) * 0.125f; + const float v1 = 2.0f + (i % 5) * 0.25f; + value_data[flash ? i : 2 * i] = ggml_fp32_to_fp16(v0); + value_data[flash ? values + i : 2 * i + 1] = ggml_fp32_to_fp16(v1); + // Ordinary F16 V matmul also rounds its probability input to F16. + const double p0 = flash ? probability0 : rounded_f16(static_cast(probability0)); + const double p1 = flash ? probability1 : rounded_f16(static_cast(probability1)); + expected[i] = v0 * p0 + v1 * p1; + } + ggml_backend_tensor_set(q, queries.data(), 0, queries.size() * sizeof(float)); + ggml_backend_tensor_set(k, keys.data(), 0, keys.size() * sizeof(ggml_fp16_t)); + ggml_backend_tensor_set(v, value_data.data(), 0, value_data.size() * sizeof(ggml_fp16_t)); + graph.compute(); + std::vector actual(values); + ggml_backend_tensor_get(out, actual.data(), 0, actual.size() * sizeof(float)); + for (int i = 0; i < values; ++i) { + check_result(actual[i], expected[i], 1e-3, flash ? "flash-attention" : "attention", width); + } +} + +} // namespace + +int main() { +#if defined(LLAMADART_TEST_CPU_BACKEND) + ggml_backend_reg_t reg = ggml_backend_load(LLAMADART_TEST_CPU_BACKEND); + std::printf("CPU module: %s\n", LLAMADART_TEST_CPU_BACKEND); +#else + ggml_backend_reg_t reg = ggml_backend_cpu_reg(); + std::printf("CPU module: statically linked\n"); +#endif + require(reg != nullptr, "requested CPU module did not load"); + require(ggml_backend_reg_dev_count(reg) == 1, "unexpected CPU module device count"); + auto device = ggml_backend_reg_dev_get(reg, 0); + require(device != nullptr && ggml_backend_dev_type(device) == GGML_BACKEND_DEVICE_TYPE_CPU, + "requested module did not provide a CPU device"); + auto backend = ggml_backend_dev_init(device, nullptr); + require(backend != nullptr, "CPU backend initialization failed"); + auto set_threads = reinterpret_cast( + ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads")); + require(set_threads != nullptr, "CPU thread setter unavailable"); + set_threads(backend, 1); + auto get_features = reinterpret_cast( + ggml_backend_reg_get_proc_address(reg, "ggml_backend_get_features")); + require(get_features != nullptr, "CPU features unavailable"); + std::printf("CPU features:"); + for (auto *feature = get_features(reg); feature->name != nullptr; ++feature) { + std::printf(" %s=%s", feature->name, feature->value); + } + std::printf("\n"); + + for (int magnitude = 30; magnitude <= 100; magnitude += 10) { + dot_case(backend, 64, static_cast(magnitude), Pattern::positive, + GGML_TYPE_F16, "upstream-positive"); + } + const int widths[] = {1, 7, 8, 15, 16, 31, 32, 33, 63, 64, 65, 127, 128, 129}; + for (int width : widths) { + dot_case(backend, width, 100.0f, Pattern::positive, GGML_TYPE_F16, "tail-positive"); + dot_case(backend, width, 100.0f, Pattern::cancellation, GGML_TYPE_F16, "cancellation"); + dot_case(backend, width, 0.0f, Pattern::subnormal, GGML_TYPE_F16, "subnormal"); + } + dot_case(backend, 64, 1.0f, Pattern::positive, GGML_TYPE_F16, "low-positive"); + dot_case(backend, 64, 0.0f, Pattern::positive, GGML_TYPE_F16, "zero"); + dot_case(backend, 32, 0.0f, Pattern::large_product, GGML_TYPE_F16, "large-product"); + dot_case(backend, 64, 0.0f, Pattern::maximum, GGML_TYPE_F16, "maximum-finite"); + dot_case(backend, 64, 100.0f, Pattern::positive, GGML_TYPE_F32, "f32-control"); + for (float magnitude : {0.0f, 1.0f, 80.0f, 100.0f}) { + attention_case(backend, false, magnitude); + attention_case(backend, true, magnitude); + } + ggml_backend_free(backend); +#if defined(LLAMADART_TEST_CPU_BACKEND) + ggml_backend_unload(reg); +#endif + std::printf("PASS: finite F16 dot, tails, controls and ordinary/flash attention\n"); + return 0; +} diff --git a/tests/test_llama_cpp_patches.py b/tests/test_llama_cpp_patches.py index a3f79aaa..7d7aa903 100644 --- a/tests/test_llama_cpp_patches.py +++ b/tests/test_llama_cpp_patches.py @@ -381,6 +381,43 @@ def test_the_embedding_reserve_patch_is_retired_only_where_upstream_has_the_fix( self.assertIn(patch, self.carried_after(unfixed)) self.assertIn(patch, self.carried_after(None), "a missing source retires nothing") + @unittest.skipUnless((UPSTREAM / "CMakeLists.txt").is_file(), + "third_party/llama.cpp is not checked out") + def test_f16_dot_patch_applies_only_to_the_exact_source_and_preserves_upstream(self) -> None: + name = "0005-arm-f16-dot-f32-accumulation.patch" + entry = next(entry for entry in patches.load_series() if entry["file"] == name) + patch_text = (patches.PATCHES_DIR / name).read_text(encoding="utf-8") + parsed = patches.parse_patch(name, patch_text) + self.assertEqual("ggml/src/ggml-cpu/vec.cpp", parsed.path) + original = (UPSTREAM / parsed.path).read_text(encoding="utf-8") + with tempfile.TemporaryDirectory() as directory: + fixture = Path(directory) + source = fixture / "upstream" / parsed.path + source.parent.mkdir(parents=True) + source.write_text(original, encoding="utf-8") + patch_dir = fixture / "patches" + patch_dir.mkdir() + (patch_dir / name).write_text(patch_text, encoding="utf-8") + (patch_dir / "series.json").write_text( + json.dumps({"patches": [entry]}), encoding="utf-8") + result = patches.apply_series(fixture / "upstream", patch_dir) + self.assertEqual([parsed.path], list(result)) + marker = "llamadart F16 dot F32 accumulation" + self.assertNotIn(marker, original) + self.assertIn(marker, result[parsed.path]) + self.assertEqual(original, source.read_text(encoding="utf-8")) + source.write_text(original.replace("void ggml_vec_dot_f16(", + "void changed_vec_dot_f16("), encoding="utf-8") + rejected = source.read_text(encoding="utf-8") + applied, skipped = patches.apply_available(fixture / "upstream", patch_dir) + self.assertEqual({}, applied) + self.assertEqual(1, len(skipped)) + self.assertIn(name, skipped[0]) + with self.assertRaises(patches.PatchError): + patches.apply_series(fixture / "upstream", patch_dir) + self.assertEqual(rejected, source.read_text(encoding="utf-8")) + self.assertEqual(original, (UPSTREAM / parsed.path).read_text(encoding="utf-8")) + METAL_PATCH = "0004-metal-unary-cast-older-os-compilers.patch" UNARY = "ggml/src/ggml-metal/kernels/unary.metal" @@ -429,7 +466,7 @@ def test_the_manifest_command_reads_the_given_upstream_not_the_submodule(self) - [sys.executable, str(ROOT / "tools/llama_cpp_patches.py"), "manifest", "--upstream", directory], capture_output=True, text=True) self.assertEqual(0, result.returncode, result.stderr) - self.assertEqual(["0001", "0002", "0003", "0004"], + self.assertEqual(["0001", "0002", "0003", "0004", "0005"], [e["file"][:4] for e in json.loads(result.stdout)]) @unittest.skipUnless((UPSTREAM / "CMakeLists.txt").is_file(), diff --git a/tools/linux_cpu_variant_smoke.c b/tools/linux_cpu_variant_smoke.c index e506233b..e52c2328 100644 --- a/tools/linux_cpu_variant_smoke.c +++ b/tools/linux_cpu_variant_smoke.c @@ -81,6 +81,11 @@ static int run_f16_matmul(ggml_backend_dev_t device) { expected += a32[n * K + k] * b32[m * K + k]; } float error = fabsf(out[m * N + n] - expected); + if (!isfinite(out[m * N + n]) || !isfinite(error)) { + fprintf(stderr, "F16 matmul produced a nonfinite output/error at row %d col %d\n", n, m); + status = 1; + break; + } max_error = error > max_error ? error : max_error; } } @@ -98,6 +103,89 @@ static int run_f16_matmul(ggml_backend_dev_t device) { return status; } +static int run_finite_dot_cases(ggml_backend_dev_t device) { + ggml_backend_t backend = ggml_backend_dev_init(device, NULL); + if (backend == NULL) { + fprintf(stderr, "ggml_backend_dev_init failed\n"); + return 1; + } + ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(device); + ggml_backend_set_n_threads_t set_threads = + (ggml_backend_set_n_threads_t)ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads"); + if (set_threads == NULL) { + fprintf(stderr, "CPU thread setter unavailable\n"); + ggml_backend_free(backend); + return 1; + } + set_threads(backend, 1); + int status = 0; + for (int test_case = 0; test_case < 11 && status == 0; test_case++) { + const int f32_control = test_case == 10; + const int cancellation = test_case == 9; + const float magnitude = test_case < 8 ? 30.0f + 10.0f * test_case : test_case == 8 ? 1.0f : 100.0f; + struct ggml_init_params params = { + .mem_size = 4 * ggml_tensor_overhead() + ggml_graph_overhead(), + .mem_buffer = NULL, + .no_alloc = true, + }; + struct ggml_context *ctx = ggml_init(params); + if (ctx == NULL) { + fprintf(stderr, "finite dot context allocation failed\n"); + status = 1; + break; + } + struct ggml_tensor *k = ggml_new_tensor_2d(ctx, f32_control ? GGML_TYPE_F32 : GGML_TYPE_F16, 64, 1); + struct ggml_tensor *q = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 64, 1); + struct ggml_tensor *out = ggml_mul_mat(ctx, k, q); + struct ggml_cgraph *graph = ggml_new_graph(ctx); + ggml_build_forward_expand(graph, out); + ggml_backend_buffer_t buffer = ggml_backend_alloc_ctx_tensors(ctx, backend); + if (buffer == NULL) { + fprintf(stderr, "finite dot tensor buffer allocation failed\n"); + ggml_free(ctx); + status = 1; + break; + } + ggml_fp16_t keys16[64]; + float keys32[64], queries[64]; + double reference = 0.0, absolute_sum = 0.0; + for (int i = 0; i < 64; i++) { + keys32[i] = cancellation ? magnitude : magnitude * (1.0f + 0.1f * (i % 5)); + queries[i] = cancellation ? (i < 32 ? magnitude : -magnitude) + : magnitude * (1.0f + 0.1f * ((i * 3) % 5)); + keys16[i] = ggml_fp32_to_fp16(keys32[i]); + const double actual_k = f32_control ? keys32[i] : ggml_fp16_to_fp32(keys16[i]); + const double actual_q = f32_control ? queries[i] : ggml_fp16_to_fp32(ggml_fp32_to_fp16(queries[i])); + const double product = actual_k * actual_q; + reference += product; + absolute_sum += fabs(product); + } + ggml_backend_tensor_set(k, f32_control ? (void *)keys32 : (void *)keys16, 0, + f32_control ? sizeof(keys32) : sizeof(keys16)); + ggml_backend_tensor_set(q, queries, 0, sizeof(queries)); + if (ggml_backend_graph_compute(backend, graph) != GGML_STATUS_SUCCESS) { + fprintf(stderr, "finite dot graph computation failed\n"); + status = 1; + } else { + float actual; + ggml_backend_tensor_get(out, &actual, 0, sizeof(actual)); + const double error = fabs((double)actual - reference); + if (!isfinite(actual) || !isfinite(error) || error > 1e-7 + 2e-6 * absolute_sum) { + fprintf(stderr, "finite dot case %d mag %.0f expected %.17g got %.9g\n", + test_case, magnitude, reference, actual); + status = 1; + } + } + ggml_backend_buffer_free(buffer); + ggml_free(ctx); + } + ggml_backend_free(backend); + if (status == 0) { + printf("finite F16 dot: magnitude sweep, low/cancellation/F32 controls passed\n"); + } + return status; +} + int main(int argc, char **argv) { if (argc != 3) { fprintf(stderr, "Usage: %s \n", argv[0]); @@ -117,5 +205,6 @@ int main(int argc, char **argv) { fprintf(stderr, "Expected %s to be selected\n", argv[2]); return 1; } - return run_f16_matmul(device); + int status = run_f16_matmul(device); + return status != 0 ? status : run_finite_dot_cases(device); } From acebd2303da026444ea7dac5ab9c7c4ca46f3e03 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Sat, 7 Nov 2026 00:31:29 -0500 Subject: [PATCH 2/6] Use FHM for ARM F16 dot accumulation --- .../0005-arm-f16-dot-f32-accumulation.patch | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/patches/llama.cpp/0005-arm-f16-dot-f32-accumulation.patch b/patches/llama.cpp/0005-arm-f16-dot-f32-accumulation.patch index 4be4e528..89611545 100644 --- a/patches/llama.cpp/0005-arm-f16-dot-f32-accumulation.patch +++ b/patches/llama.cpp/0005-arm-f16-dot-f32-accumulation.patch @@ -6,7 +6,7 @@ + GGML_ASSERT(n >= 0 && "llamadart F16 dot F32 accumulation"); assert(nrc == 1); GGML_UNUSED(nrc); -@@ -272,5 +273,38 @@ +@@ -272,5 +273,48 @@ -#if defined(GGML_SIMD) @@ -25,15 +25,25 @@ + for (int j = 0; j < 4; ++j) { + const float16x8_t vx = vld1q_f16((const __fp16 *) (x + i + 8*j)); + const float16x8_t vy = vld1q_f16((const __fp16 *) (y + i + 8*j)); ++#if defined(__ARM_FEATURE_FP16_FML) ++ sum_lo[j] = vfmlalq_low_f16(sum_lo[j], vx, vy); ++ sum_hi[j] = vfmlalq_high_f16(sum_hi[j], vx, vy); ++#else + sum_lo[j] = vfmaq_f32(sum_lo[j], vcvt_f32_f16(vget_low_f16(vx)), vcvt_f32_f16(vget_low_f16(vy))); + sum_hi[j] = vfmaq_f32(sum_hi[j], vcvt_f32_f16(vget_high_f16(vx)), vcvt_f32_f16(vget_high_f16(vy))); ++#endif + } + } + for (; i < np8; i += 8) { + const float16x8_t vx = vld1q_f16((const __fp16 *) (x + i)); + const float16x8_t vy = vld1q_f16((const __fp16 *) (y + i)); ++#if defined(__ARM_FEATURE_FP16_FML) ++ sum_lo[0] = vfmlalq_low_f16(sum_lo[0], vx, vy); ++ sum_hi[0] = vfmlalq_high_f16(sum_hi[0], vx, vy); ++#else + sum_lo[0] = vfmaq_f32(sum_lo[0], vcvt_f32_f16(vget_low_f16(vx)), vcvt_f32_f16(vget_low_f16(vy))); + sum_hi[0] = vfmaq_f32(sum_hi[0], vcvt_f32_f16(vget_high_f16(vx)), vcvt_f32_f16(vget_high_f16(vy))); ++#endif + } + for (int j = 1; j < 4; ++j) { + sum_lo[0] = vaddq_f32(sum_lo[0], sum_lo[j]); From abae2a1e07b38395c0c28df37d0abc42861a76e1 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Sat, 7 Nov 2026 00:45:18 -0500 Subject: [PATCH 3/6] Document FHM dot accumulation path and qualification --- docs/native174_f16_dot_accumulation.md | 33 +++++++++++++++++++------- patches/llama.cpp/README.md | 5 ++-- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/docs/native174_f16_dot_accumulation.md b/docs/native174_f16_dot_accumulation.md index 51544a54..0d93e8a4 100644 --- a/docs/native174_f16_dot_accumulation.md +++ b/docs/native174_f16_dot_accumulation.md @@ -20,10 +20,13 @@ operator cases against actual public `v0.8.0-3` macOS ARM64 and Linux ARM64 failures or proof of a new release regression. Severity remains P2. The carried branch requires NEON, FMA, IEEE F16, FP16 vector arithmetic and -no SVE. Global SIMD mappings, ABI, ISA flags, CPU variant selection and cache -defaults are unchanged. FHM intrinsics are deferred: this conversion/F32-FMA -candidate adds no instruction-family or toolchain requirement. Other F16 -kernels, including separate llamafile GEMM, are outside the repair. +no SVE. When the compiler defines `__ARM_FEATURE_FP16_FML`, it uses +FMLAL/FMLAL2 to accumulate the low/high F16 halves directly into F32. +Otherwise it retains the conversion/F32-FMA path. The fast path uses only +the existing compiler-advertised capability; it adds no ISA flags or runtime +dispatch. Global SIMD mappings, ABI, CPU variant selection and cache defaults +are unchanged. Other F16 kernels, including separate llamafile GEMM, are +outside the repair. Patch 0005 requests the explicit, issue-specific policy exception described in [the patch policy](../patches/llama.cpp/README.md#proposed-exception-for-native-174). @@ -37,13 +40,27 @@ exception in the PR; publication is a separate decision. `llamadart_f16_dot_accumulation_test` uses production ggml graph/backend APIs, with one CPU thread and checks that remain active in Release. It covers operator magnitudes, vector/tail boundaries and synthetic ordinary/flash -attention. These tests must be compiled and run before claiming corrected -behavior. Attention failure/restoration is unverified until then. Zero-length kernel -execution and noncontiguous/strided tensor paths are not covered by this -candidate test; the width sweep begins at one. +attention. Run it against each exact candidate/control platform before +claiming corrected behavior there. A candidate pass alone does not establish +causal attention failure/restoration. Zero-length kernel execution and +noncontiguous/strided tensor paths are not covered by this candidate test; +the width sweep begins at one. The Linux compatibility smoke retains its original matrix shape and rejects nonfinite results/errors explicitly. +Local M4 Max CPU source builds pass the full numerical test for both the +conversion-only `5fcce7c` and FHM `acebd230` candidates; the original control +fails. With one hash-bound cached GGUF, the conversion-only build's median +decode throughput was 1.6–1.9% lower than the original, with FA off/on. This +does not measure FHM model performance, model quality or an affected public +model. + +Across 27 rotated direct-dot runs at lengths 64/128/256, the FHM build's median +latency was 27–46% lower than conversion-only, but still 19–25% higher than the +original. The first length-64 run had a broad outlier; retain the full ranges +and provenance in the PR evidence. These kernel measurements do not establish +FHM whole-model performance or other-platform qualification. + Source-only Python patch checks cover exact application, markers, mismatch skip/strict failure and pristine upstream preservation. Android and Apple artifact markers retain the patch in release validation. The always-active diff --git a/patches/llama.cpp/README.md b/patches/llama.cpp/README.md index fae222ba..5aa9d05d 100644 --- a/patches/llama.cpp/README.md +++ b/patches/llama.cpp/README.md @@ -28,8 +28,9 @@ therefore does not literally cover it. Published ARM64 artifacts return nonfinite results for finite F16 dot products. The internal kernel cannot be repaired in wrapper `src/`; globally disabling FP16 arithmetic would change unrelated kernels and undo optimized CPU variant -performance. Patch 0005 changes only the non-SVE NEON F16 dot implementation, -without changing ISA flags, ABI, variants or cache defaults. Qualification, +performance. Patch 0005 changes only the non-SVE NEON F16 dot implementation: +compiler-advertised FP16 FML uses widening FMLAL/FMLAL2, with conversion/F32-FMA +otherwise. It changes no ISA flags, ABI, variants or cache defaults. Qualification, performance risk and retirement gates are in [native174_f16_dot_accumulation.md](../../docs/native174_f16_dot_accumulation.md). This exception does not extend eligibility to other patches. From f1f220d3265cf1ac3d204b2aae728ae22ba150ef Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Sat, 7 Nov 2026 01:54:23 -0500 Subject: [PATCH 4/6] Decode FHM instructions in Android ISA audit --- docs/native174_f16_dot_accumulation.md | 4 ++++ tests/test_android_cpu_isa.py | 21 +++++++++++++++++++++ tools/validate_android_cpu_isa.py | 2 +- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/docs/native174_f16_dot_accumulation.md b/docs/native174_f16_dot_accumulation.md index 0d93e8a4..b7352c18 100644 --- a/docs/native174_f16_dot_accumulation.md +++ b/docs/native174_f16_dot_accumulation.md @@ -68,6 +68,10 @@ negative-length guard carries the marker; its presence proves inclusion, not numerical correctness. Verify the marker in every actual optimized and baseline module, including Linux variants. +The Android ISA audit enables `+fp16fml` in objdump so FHM instructions decode +instead of appearing as unknown words. This changes decoder selection only; +source fingerprints and exact SVE/SME function-range checks stay unchanged. + Before merge or publication, ROOT must provide: - Paired original/candidate/reverted builds with identical source and flags, diff --git a/tests/test_android_cpu_isa.py b/tests/test_android_cpu_isa.py index fe18a0e9..8a2c7f5a 100644 --- a/tests/test_android_cpu_isa.py +++ b/tests/test_android_cpu_isa.py @@ -195,6 +195,27 @@ def test_cli_legacy_baseline_does_not_require_kleidiai_source(self): self.assertEqual(audit.main(), 0) validate_sources.assert_not_called() + def test_cli_enables_fhm_decoding_without_granting_scalable_exceptions(self): + args = ["audit", "--objdump", "objdump", "--readelf", "readelf", + "--llama-source", "absent", "--kleidiai-source", "absent", "test.so"] + + def decode(command, **kwargs): + if command[0] == "readelf": + return symbol("ggml_vec_dot_f16", 0x132500) + # NDK 28.2 emits these as without explicit +fp16fml, + # even with +v9.4a. These are the observed FHM instruction words. + enabled = any("+fp16fml" in argument for argument in command) + low = "fmlal v4.4s, v17.4h, v16.4h" if enabled else "" + high = "fmlal2 v7.4s, v17.4h, v16.4h" if enabled else "" + return disassembly(f"132500: 4e30ee24 {low}\n132504: 6e30ce27 {high}") + + with mock.patch("sys.argv", args), \ + mock.patch.object(audit.subprocess, "check_output", side_effect=decode), \ + mock.patch.object(audit, "validate_sources") as validate_sources, \ + contextlib.redirect_stdout(io.StringIO()): + self.assertEqual(audit.main(), 0) + validate_sources.assert_not_called() + def test_cli_scalable_artifact_requires_dispatch_source_audit(self): args = ["audit", "--objdump", "objdump", "--readelf", "readelf", "--llama-source", "absent", "--kleidiai-source", "absent", "test.so"] diff --git a/tools/validate_android_cpu_isa.py b/tools/validate_android_cpu_isa.py index 112cdb82..8f938924 100644 --- a/tools/validate_android_cpu_isa.py +++ b/tools/validate_android_cpu_isa.py @@ -218,7 +218,7 @@ def main(): symbols = subprocess.check_output([args.readelf, "--dyn-syms", "--wide", str(args.library)], text=True) # Decode extensions rather than letting objdump hide them as . disassembly = subprocess.check_output([ - args.objdump, "-d", "--mattr=+v9.4a,+sve,+sve2,+sme,+sme2,+mte", str(args.library) + args.objdump, "-d", "--mattr=+v9.4a,+sve,+sve2,+sme,+sme2,+mte,+fp16fml", str(args.library) ], text=True) has_scalable = any( is_scalable(int(match[2], 16), match[3].strip()) From 41ddb5a36bc676af1c15e332228bee64ebe5dd86 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Sat, 7 Nov 2026 02:55:49 -0500 Subject: [PATCH 5/6] Report every F16 dot check failure and tighten #174 doc The unpatched control now shows the inf results at magnitude 80/90/100 and NaN attention instead of stopping at the first rounding mismatch. The doc states the defect, repair and remaining publication checks. --- docs/native174_f16_dot_accumulation.md | 154 ++++++++++--------------- tests/f16_dot_accumulation_test.cpp | 17 ++- 2 files changed, 76 insertions(+), 95 deletions(-) diff --git a/docs/native174_f16_dot_accumulation.md b/docs/native174_f16_dot_accumulation.md index b7352c18..dd656d95 100644 --- a/docs/native174_f16_dot_accumulation.md +++ b/docs/native174_f16_dot_accumulation.md @@ -1,92 +1,62 @@ -# ARM F16 dot accumulation candidate (#174) - -This source candidate repairs non-SVE NEON F16 dot products that overflow in -F16 before being returned as F32. It changes only `ggml_vec_dot_f16` in a -build-tree copy of upstream `ggml/src/ggml-cpu/vec.cpp`. Multiplication, -accumulation and reduction use F32; four low/high accumulator pairs preserve -the 32-element unroll, with full eight-element and scalar tails. - -Tracking: [native #174](https://github.com/leehack/llamadart-native/issues/174), -[upstream #31734](https://github.com/ggml-org/llama.cpp/issues/31734). -The base is owner `05ef9a48a2bd1db2f4208a89c393794412e9cb74`, pinned upstream -`8642541b255bfb5dc39cd351a178be09013a55d6`. - -## Evidence and scope - -ROOT reproduced `inf` with success status for the magnitude 80/90/100 F16 -operator cases against actual public `v0.8.0-3` macOS ARM64 and Linux ARM64 -`linux_armv8.2_2`/`linux_armv8.6_1` modules. The Linux baseline passes all -11 cases. These are model-free operator results, not public-model/app -failures or proof of a new release regression. Severity remains P2. - -The carried branch requires NEON, FMA, IEEE F16, FP16 vector arithmetic and -no SVE. When the compiler defines `__ARM_FEATURE_FP16_FML`, it uses -FMLAL/FMLAL2 to accumulate the low/high F16 halves directly into F32. -Otherwise it retains the conversion/F32-FMA path. The fast path uses only -the existing compiler-advertised capability; it adds no ISA flags or runtime -dispatch. Global SIMD mappings, ABI, CPU variant selection and cache defaults -are unchanged. Other F16 kernels, including separate llamafile GEMM, are -outside the repair. - -Patch 0005 requests the explicit, issue-specific policy exception described -in [the patch policy](../patches/llama.cpp/README.md#proposed-exception-for-native-174). -Disabling optimized FP16 is a broad build workaround; this internal correctness -repair is more than a few lines. Neither original eligibility condition is -claimed satisfied. Acceptance requires explicit maintainer approval of this -exception in the PR; publication is a separate decision. - -## Durable checks and remaining gates - -`llamadart_f16_dot_accumulation_test` uses production ggml graph/backend APIs, -with one CPU thread and checks that remain active in Release. It covers -operator magnitudes, vector/tail boundaries and synthetic ordinary/flash -attention. Run it against each exact candidate/control platform before -claiming corrected behavior there. A candidate pass alone does not establish -causal attention failure/restoration. Zero-length kernel execution and -noncontiguous/strided tensor paths are not covered by this candidate test; -the width sweep begins at one. -The Linux compatibility smoke retains its original matrix shape and rejects -nonfinite results/errors explicitly. - -Local M4 Max CPU source builds pass the full numerical test for both the -conversion-only `5fcce7c` and FHM `acebd230` candidates; the original control -fails. With one hash-bound cached GGUF, the conversion-only build's median -decode throughput was 1.6–1.9% lower than the original, with FA off/on. This -does not measure FHM model performance, model quality or an affected public -model. - -Across 27 rotated direct-dot runs at lengths 64/128/256, the FHM build's median -latency was 27–46% lower than conversion-only, but still 19–25% higher than the -original. The first length-64 run had a broad outlier; retain the full ranges -and provenance in the PR evidence. These kernel measurements do not establish -FHM whole-model performance or other-platform qualification. - -Source-only Python patch checks cover exact application, markers, mismatch -skip/strict failure and pristine upstream preservation. Android and Apple -artifact markers retain the patch in release validation. The always-active -negative-length guard carries the marker; its presence proves inclusion, -not numerical correctness. Verify the marker in every actual optimized and -baseline module, including Linux variants. - -The Android ISA audit enables `+fp16fml` in objdump so FHM instructions decode -instead of appearing as unknown words. This changes decoder selection only; -source fingerprints and exact SVE/SME function-range checks stay unchanged. - -Before merge or publication, ROOT must provide: - -- Paired original/candidate/reverted builds with identical source and flags, - finite/reference checks and exact module identities for the frozen 11-case - probe and the durable numeric test. Preserve original failures as evidence. -- Actual selected Linux/Android variant correctness and ISA containment; - SVE, iOS and Windows remain separate platform gates. Existing ISA source - fingerprints cover pristine upstream, so audit compiled patched copies too. -- Paired timing for dot lengths 64/128/256 and CPU prefill/decode with F16 KV, - FA off/on, using identical available public model bytes, threads and inputs. - F32 widening can slow the hot loop; no zero-regression claim is made. -- An independent review of the exact candidate revision and explicit approval - of the narrow patch-policy exception. No owner release or core/Apple pin - adoption follows automatically. - -Remove this patch only when the pinned upstream and every compatibility lane -contain a verified upstream repair, or the defect no longer reproduces without -it. No `upstream_fix` string is invented before such a repair exists. +# ARM F16 dot accumulation (#174) + +Patch 0005 repairs non-SVE NEON F16 dot products that overflow in F16 before +being returned as F32. Tracking: +[native #174](https://github.com/leehack/llamadart-native/issues/174), +[upstream #31734](https://github.com/ggml-org/llama.cpp/issues/31734) +(open, unfixed in llama.cpp `v0.9.0` and `master` as of 2026-11-07). + +## Defect + +With `__ARM_FEATURE_FP16_VECTOR_ARITHMETIC` and no SVE, upstream +`ggml_vec_dot_f16` maps `GGML_F16_DOT_VEC` to `float16x8_t`: products, partial +sums and the first reduction steps stay in F16 and overflow past 65504. Only +AVX512-FP16 and SVE widen to F32. Shipped `v0.8.0-3` macOS ARM64 and Linux +`linux_armv8.2_2`/`linux_armv8.6_1` modules return `inf` for finite operator +inputs at magnitude 80/90/100; the Linux armv8.0 baseline does not. Ordinary +F16 K attention then produces NaN. Severity is P2: no public-model failure is +established. + +## Repair + +Only `ggml_vec_dot_f16` changes, in a build-tree copy of +`ggml/src/ggml-cpu/vec.cpp`. Under NEON, FMA, IEEE F16, FP16 vector arithmetic +and no SVE, it multiplies, accumulates and reduces in F32 with four low/high +accumulator pairs (the original 32-element unroll), an eight-element tail and +a scalar tail. When the compiler defines `__ARM_FEATURE_FP16_FML` it uses +FMLAL/FMLAL2; otherwise it converts and uses F32 FMA. ISA flags, runtime +dispatch, ABI, CPU variant selection and cache defaults are unchanged. Other +F16 kernels, including llamafile GEMM, are out of scope. + +The repair is longer than the patch policy's "few lines" and the alternative +(disabling FP16 vector arithmetic) is a build workaround that slows every F16 +kernel, so it needs the +[narrow exception](../patches/llama.cpp/README.md#proposed-exception-for-native-174) +approved by the maintainer. + +## Checks + +- `llamadart_f16_dot_accumulation_test` (CTest, `validate_wrapper.yml`) runs + production graph/backend calls on one thread: the magnitude sweep, widths + 1–129 around every unroll and tail boundary, cancellation, subnormal, + F16-max and product-overflow inputs, an F32 control, and ordinary and flash + attention. It reports every failing check. Without the patch it fails on + Apple silicon with `inf` at magnitude 80/90/100 and NaN attention. + Zero-length and strided tensors are not covered. +- `tools/linux_cpu_variant_smoke.c` runs the same magnitude sweep on each + selected Linux arm64 CPU module and rejects nonfinite matmul output. +- The always-active negative-length guard carries the artifact marker checked + for Android and Apple bundles; it proves inclusion, not correctness. +- The Android ISA audit decodes with `+fp16fml` so FMLAL is not reported as an + unknown word. Source fingerprints and SVE/SME range checks are unchanged; + they cover pristine upstream, not the patched copy. + +## Before publication + +Run the test against each published CPU module (Android variants on device, +Linux variants, Apple) and compare F16-KV prefill/decode throughput with the +previous release. The FHM kernel is slower than the original F16 one in +isolation; no zero-regression claim is made. + +Retire the patch when the pinned upstream and every compatibility lane carry a +verified upstream repair; then add its `upstream_fix` text. diff --git a/tests/f16_dot_accumulation_test.cpp b/tests/f16_dot_accumulation_test.cpp index 4d5c084a..86f5df1d 100644 --- a/tests/f16_dot_accumulation_test.cpp +++ b/tests/f16_dot_accumulation_test.cpp @@ -12,6 +12,8 @@ namespace { +int failures = 0; + void require(bool condition, const char *message) { if (!condition) { std::fprintf(stderr, "FAIL: %s\n", message); @@ -57,7 +59,7 @@ class Graph { ggml_backend_buffer_t buffer_ = nullptr; }; -void check_result(float actual, double expected, double tolerance, +bool check_result(float actual, double expected, double tolerance, const char *name, int width) { const double error = std::fabs(static_cast(actual) - expected); if (!std::isfinite(actual) || !std::isfinite(expected) || @@ -65,8 +67,10 @@ void check_result(float actual, double expected, double tolerance, std::fprintf(stderr, "FAIL: %s width=%d expected=%.17g actual=%.9g tolerance=%.9g\n", name, width, expected, actual, tolerance); - std::exit(1); + ++failures; + return false; } + return true; } enum class Pattern { positive, cancellation, large_product, maximum, subnormal }; @@ -172,7 +176,10 @@ void attention_case(ggml_backend_t backend, bool flash, float magnitude) { std::vector actual(values); ggml_backend_tensor_get(out, actual.data(), 0, actual.size() * sizeof(float)); for (int i = 0; i < values; ++i) { - check_result(actual[i], expected[i], 1e-3, flash ? "flash-attention" : "attention", width); + if (!check_result(actual[i], expected[i], 1e-3, + flash ? "flash-attention" : "attention", width)) { + break; + } } } @@ -229,6 +236,10 @@ int main() { #if defined(LLAMADART_TEST_CPU_BACKEND) ggml_backend_unload(reg); #endif + if (failures != 0) { + std::fprintf(stderr, "FAIL: %d checks\n", failures); + return 1; + } std::printf("PASS: finite F16 dot, tails, controls and ordinary/flash attention\n"); return 0; } From d57d2370b40181ea63c68a260ce0eebc0dcb8875 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Sat, 7 Nov 2026 05:36:32 -0500 Subject: [PATCH 6/6] Accumulate llamafile F16 GEMM in F32 on ARM and widen #174 tests Patch 0006 switches the FP16 llamafile tile, used for eight or more query columns on macOS arm64 and linux_armv8.2_2, to F32 accumulation. The test adds GEMM and hidden partial-sum overflow cases, NaN row padding and an unsaturated attention softmax, and CI also runs it on the conversion path. --- .github/workflows/validate_wrapper.yml | 15 ++ docs/linux_arm64_cpu_variants.md | 4 + docs/native174_f16_dot_accumulation.md | 119 +++++++++----- .../0006-arm-f16-gemm-f32-accumulation.patch | 18 +++ patches/llama.cpp/README.md | 29 ++-- patches/llama.cpp/series.json | 8 + tests/f16_dot_accumulation_test.cpp | 146 +++++++++++------- tests/test_llama_cpp_patches.py | 21 ++- 8 files changed, 246 insertions(+), 114 deletions(-) create mode 100644 patches/llama.cpp/0006-arm-f16-gemm-f32-accumulation.patch diff --git a/.github/workflows/validate_wrapper.yml b/.github/workflows/validate_wrapper.yml index b4ed2f7c..b2d99503 100644 --- a/.github/workflows/validate_wrapper.yml +++ b/.github/workflows/validate_wrapper.yml @@ -731,6 +731,21 @@ jobs: run: >- ctest --test-dir ${{ matrix.build_dir }} -R "owner_|exit_teardown|image_token_limit|build_identity|cancel_flag|f16_dot_accumulation" --timeout 300 --output-on-failure + # Apple CPUs have FHM, so the shipped build takes the FMLAL branch of + # patch 0005. ARMv8.2-A with FP16 compiles its conversion branch, as on + # the armv8.2_2 Linux and Android variants. + - name: Run the F16 accumulation test on the conversion path + if: matrix.build == 'release' + run: | + cmake -S . -B build/f16-conversion -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DGGML_NATIVE=OFF -DGGML_CPU_ARM_ARCH=armv8.2-a+fp16+dotprod \ + -DGGML_METAL=OFF -DGGML_OPENMP=OFF -DGGML_CCACHE=OFF -DLLAMADART_BUILD_TESTS=ON + cmake --build build/f16-conversion --target llamadart_f16_dot_accumulation_test + if objdump -d build/f16-conversion/llamadart_f16_dot_accumulation_test | grep -q fmlal; then + echo "The conversion-path build contains FMLAL" >&2 + exit 1 + fi + build/f16-conversion/llamadart_f16_dot_accumulation_test # A model that nothing tracks aborts at exit when Metal residency sets # are live. Whether a runner has them is outside this repository's # control, so their absence is reported instead of failing every native diff --git a/docs/linux_arm64_cpu_variants.md b/docs/linux_arm64_cpu_variants.md index 79ff96d7..feb189da 100644 --- a/docs/linux_arm64_cpu_variants.md +++ b/docs/linux_arm64_cpu_variants.md @@ -34,6 +34,10 @@ enables. The compiler also uses these where they apply: and 3 `stlur` (LRCPC2, ARMv8.4) instructions, plus the same inline LSE. Neither is a scored feature; ARMv8.6 guarantees both, and the I8MM that scores this variant is an ARMv8.6 feature. +- `linux_armv8.6_1` and `android_armv8.6_1` also use FMLAL/FMLAL2 (FHM) in the + F16 dot kernel of carried patch 0005: FP16 on ARMv8.4 or later implies FHM, + so the compiler defines `__ARM_FEATURE_FP16_FML`. The `armv8.2_2` variants + use the conversion path instead. - `libggml-cpu.so` (ARMv8.0) contains LSE only inside libgcc's outline-atomic helpers, each of which tests `__aarch64_have_lse_atomics` before reaching the LSE instruction. It contains no LRCPC, LRCPC2 or CRC. diff --git a/docs/native174_f16_dot_accumulation.md b/docs/native174_f16_dot_accumulation.md index dd656d95..4468a415 100644 --- a/docs/native174_f16_dot_accumulation.md +++ b/docs/native174_f16_dot_accumulation.md @@ -1,62 +1,105 @@ # ARM F16 dot accumulation (#174) -Patch 0005 repairs non-SVE NEON F16 dot products that overflow in F16 before -being returned as F32. Tracking: +Patches 0005 and 0006 repair non-SVE ARM F16 dot products that overflow in +F16 before being returned as F32. Tracking: [native #174](https://github.com/leehack/llamadart-native/issues/174), [upstream #31734](https://github.com/ggml-org/llama.cpp/issues/31734) (open, unfixed in llama.cpp `v0.9.0` and `master` as of 2026-11-07). +Published artifacts stay affected until a release carrying both patches +replaces them. ## Defect -With `__ARM_FEATURE_FP16_VECTOR_ARITHMETIC` and no SVE, upstream -`ggml_vec_dot_f16` maps `GGML_F16_DOT_VEC` to `float16x8_t`: products, partial -sums and the first reduction steps stay in F16 and overflow past 65504. Only -AVX512-FP16 and SVE widen to F32. Shipped `v0.8.0-3` macOS ARM64 and Linux -`linux_armv8.2_2`/`linux_armv8.6_1` modules return `inf` for finite operator -inputs at magnitude 80/90/100; the Linux armv8.0 baseline does not. Ordinary -F16 K attention then produces NaN. Severity is P2: no public-model failure is -established. +With `__ARM_FEATURE_FP16_VECTOR_ARITHMETIC` (macOS arm64 and the arm64 iOS +simulator by default, `+fp16` Linux and Android variants; not iOS devices, +whose default target lacks it), two CPU kernels multiply and sum F16 inputs in +F16 and overflow past 65504: + +- `ggml_vec_dot_f16` (one query column) maps `GGML_F16_DOT_VEC` to + `float16x8_t` unless the build has SVE. Only AVX512-FP16 and SVE widen. +- llamafile `tinyBLAS<8, float16x8_t, ...>` (eight or more query columns, + `llamafile_sgemm`) accumulates `float16x8_t` tiles. ggml builds it with + `GGML_LLAMAFILE`, which Android turns off and which ggml compiles out under + SVE or I8MM, so it reaches macOS arm64 and Linux `linux_armv8.2_2`. + +Shipped `v0.8.0-3` macOS ARM64 and Linux `linux_armv8.2_2`/`linux_armv8.6_1` +modules return `inf` for finite operator inputs at magnitude 80/90/100; the +Linux armv8.0 baseline does not. Ordinary F16 K attention then produces NaN, +for one query and, through GEMM, for eight or more. Severity is P2: no +public-model failure is established. ## Repair -Only `ggml_vec_dot_f16` changes, in a build-tree copy of -`ggml/src/ggml-cpu/vec.cpp`. Under NEON, FMA, IEEE F16, FP16 vector arithmetic -and no SVE, it multiplies, accumulates and reduces in F32 with four low/high -accumulator pairs (the original 32-element unroll), an eight-element tail and -a scalar tail. When the compiler defines `__ARM_FEATURE_FP16_FML` it uses -FMLAL/FMLAL2; otherwise it converts and uses F32 FMA. ISA flags, runtime -dispatch, ABI, CPU variant selection and cache defaults are unchanged. Other -F16 kernels, including llamafile GEMM, are out of scope. - -The repair is longer than the patch policy's "few lines" and the alternative -(disabling FP16 vector arithmetic) is a build workaround that slows every F16 -kernel, so it needs the -[narrow exception](../patches/llama.cpp/README.md#proposed-exception-for-native-174) -approved by the maintainer. +Both patches change build-tree copies only. + +- 0005: under NEON, FMA, IEEE F16, FP16 vector arithmetic and no SVE, + `ggml_vec_dot_f16` multiplies, accumulates and reduces in F32 with four + low/high accumulator pairs (the original 32-element unroll), an eight-element + tail and a scalar tail. With `__ARM_FEATURE_FP16_FML` it uses FMLAL/FMLAL2; + otherwise it converts and uses F32 FMA. +- 0006: the FP16 branch of `llamafile_sgemm` instantiates + `tinyBLAS<4, float32x4_t, float32x4_t, ggml_fp16_t, ggml_fp16_t, float>`, + which loads F16 and accumulates in F32, instead of the F16 tile. + +ISA flags, runtime dispatch, ABI, CPU variant selection and cache defaults are +unchanged. Both patches exceed the policy's "few lines" condition; the +maintainer approved the +[narrow exception](../patches/llama.cpp/README.md#exception-for-native-174). + +## Performance + +Apple M4 Max, CPU only, `GGML_NATIVE=OFF`, against the original kernels: + +| Case | Cost | +| --- | --- | +| F16 mat-vec 4096x4096, 1 thread: FMLAL / conversion path | +13% / +78% time | +| F16 GEMM 4096x4096, 32–512 columns, 1 or 8 threads (0006) | +125–160% time | +| Same with `GGML_LLAMAFILE=OFF` instead of 0006 | +201–248% time; Q4_0/Q8_0 GEMM +50–58% | +| Llama-3.2-1B Q4_K_M pp512, F16 KV, 8 threads, FA off / on | -4.7% / -1.5% tokens/s | +| Same, 1 thread, FA off | -4.0% tokens/s | +| LFM2-VL-450M Q4_0 pp512, F16 KV, 8 threads, FA off | -3.0% tokens/s | +| Same models with `GGML_LLAMAFILE=OFF` instead of 0006, FA off | -7.4% to -9.1% tokens/s | + +F16-weight models pay the GEMM cost on most of their prefill: the +`linux_armv8.2_2` F16 prefill gain over the armv8.0 baseline came from the F16 +tile and is expected to largely go away (not yet measured there). A widening FMLAL tile was slower than the +conversion tile (+270% time) because its accumulators exceed the register file. ## Checks - `llamadart_f16_dot_accumulation_test` (CTest, `validate_wrapper.yml`) runs production graph/backend calls on one thread: the magnitude sweep, widths 1–129 around every unroll and tail boundary, cancellation, subnormal, - F16-max and product-overflow inputs, an F32 control, and ordinary and flash - attention. It reports every failing check. Without the patch it fails on - Apple silicon with `inf` at magnitude 80/90/100 and NaN attention. - Zero-length and strided tensors are not covered. -- `tools/linux_cpu_variant_smoke.c` runs the same magnitude sweep on each - selected Linux arm64 CPU module and rejects nonfinite matmul output. -- The always-active negative-length guard carries the artifact marker checked - for Android and Apple bundles; it proves inclusion, not correctness. + F16-max and product-overflow inputs, a cancellation whose F16 partial sums + overflow, 8/16/32-column GEMM cases, F32 controls, and ordinary and flash + attention over 16 keys for one and eight queries with an unsaturated + softmax. Weight rows are followed by NaN padding, so a read past the row + fails. It reports every failing check. The macOS release lanes also run it + built for `armv8.2-a+fp16+dotprod` to cover the conversion branch. +- Without the patches it fails on Apple silicon: 30 checks with neither, and + the seven GEMM checks plus eight-query ordinary attention with 0005 alone. + A `n - n % 4` tail mutation of 0005 fails 15 checks through the padding. Zero-length and + strided query tensors are not covered. +- `tools/linux_cpu_variant_smoke.c` runs the single-column magnitude sweep on + each selected Linux arm64 CPU module and rejects nonfinite matmul output. +- Always-active guards (`n >= 0` in 0005, `k >= 0` in 0006) carry the + artifact markers: Android and Apple for 0005, Apple for 0006 (Android builds + no llamafile). They prove inclusion, not correctness. - The Android ISA audit decodes with `+fp16fml` so FMLAL is not reported as an unknown word. Source fingerprints and SVE/SME range checks are unchanged; - they cover pristine upstream, not the patched copy. + they cover pristine upstream, not the patched copies. ## Before publication -Run the test against each published CPU module (Android variants on device, -Linux variants, Apple) and compare F16-KV prefill/decode throughput with the -previous release. The FHM kernel is slower than the original F16 one in -isolation; no zero-regression claim is made. +These gates hold before any release carries the patches, including the +`v0.9.0` release that the daily stable detector publishes once its ISA audit +passes on `main`: + +- Run the test against each published CPU module: Android variants on a + device, Linux variants, Apple. +- Compare prefill/decode throughput on an Android device for each variant with + the previous release, F16 KV with FA off and on, and an F16-weight model on + `linux_armv8.2_2`. -Retire the patch when the pinned upstream and every compatibility lane carry a +Retire a patch when the pinned upstream and every compatibility lane carry a verified upstream repair; then add its `upstream_fix` text. diff --git a/patches/llama.cpp/0006-arm-f16-gemm-f32-accumulation.patch b/patches/llama.cpp/0006-arm-f16-gemm-f32-accumulation.patch new file mode 100644 index 00000000..9da7fc96 --- /dev/null +++ b/patches/llama.cpp/0006-arm-f16-gemm-f32-accumulation.patch @@ -0,0 +1,18 @@ +--- a/ggml/src/ggml-cpu/llamafile/sgemm.cpp ++++ b/ggml/src/ggml-cpu/llamafile/sgemm.cpp +@@ -3900,4 +3900,4 @@ + assert(m >= 0); + assert(n >= 0); +- assert(k >= 0); ++ GGML_ASSERT(k >= 0 && "llamadart F16 GEMM F32 accumulation"); + assert(lda >= k); +@@ -4065,6 +4065,7 @@ + #elif defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC) && !defined(_MSC_VER) + if (n < 8) + return false; + if (Btype == GGML_TYPE_F16) { +- tinyBLAS<8, float16x8_t, float16x8_t, ggml_fp16_t, ggml_fp16_t, float> tb{ params, ++ // F16 products and partial sums can overflow before the F32 result is stored. ++ tinyBLAS<4, float32x4_t, float32x4_t, ggml_fp16_t, ggml_fp16_t, float> tb{ params, + k, (const ggml_fp16_t *)A, lda, + (const ggml_fp16_t *)B, ldb, diff --git a/patches/llama.cpp/README.md b/patches/llama.cpp/README.md index 5aa9d05d..e22d44b2 100644 --- a/patches/llama.cpp/README.md +++ b/patches/llama.cpp/README.md @@ -17,21 +17,20 @@ these hold: The v0.7.0 embedding-mode reservation repair and its exact baseline/candidate evidence are documented in [v070_native_contracts.md](../../docs/v070_native_contracts.md). -## Proposed exception for native #174 - -Patch 0005 requests a narrow exception to the first two eligibility conditions -above; accepting this change requires explicit maintainer approval of that -exception. Disabling optimized FP16 arithmetic is a build workaround, and this -localized correctness branch is more than a few lines. The ordinary policy -therefore does not literally cover it. - -Published ARM64 artifacts return nonfinite results for finite F16 dot products. -The internal kernel cannot be repaired in wrapper `src/`; globally disabling -FP16 arithmetic would change unrelated kernels and undo optimized CPU variant -performance. Patch 0005 changes only the non-SVE NEON F16 dot implementation: -compiler-advertised FP16 FML uses widening FMLAL/FMLAL2, with conversion/F32-FMA -otherwise. It changes no ISA flags, ABI, variants or cache defaults. Qualification, -performance risk and retirement gates are in +## Exception for native #174 + +The maintainer approved a narrow exception to the first two eligibility +conditions above for patches 0005 and 0006 only. Disabling FP16 vector +arithmetic or llamafile is a build workaround that slows unrelated kernels +(llamafile off costs Q4_0/Q8_0 prefill too), and the F16 dot repair is more +than a few lines. + +Published ARM64 artifacts return nonfinite results for finite F16 dot +products. Patch 0005 changes only the non-SVE NEON `ggml_vec_dot_f16` +(FMLAL/FMLAL2 with FP16 FML, conversion and F32 FMA otherwise); patch 0006 +switches the FP16 llamafile GEMM tile to F32 accumulation. Neither changes ISA +flags, ABI, variants or cache defaults. Performance cost, checks and +publication gates are in [native174_f16_dot_accumulation.md](../../docs/native174_f16_dot_accumulation.md). This exception does not extend eligibility to other patches. diff --git a/patches/llama.cpp/series.json b/patches/llama.cpp/series.json index 82c4321c..2ee55adb 100644 --- a/patches/llama.cpp/series.json +++ b/patches/llama.cpp/series.json @@ -49,6 +49,14 @@ "apple_markers": [ {"library": "libllamadart.dylib", "text": "llamadart F16 dot F32 accumulation"} ] + }, + { + "file": "0006-arm-f16-gemm-f32-accumulation.patch", + "tracking": "https://github.com/leehack/llamadart-native/issues/174", + "upstream": "https://github.com/ggml-org/llama.cpp/issues/31734", + "apple_markers": [ + {"library": "libllamadart.dylib", "text": "llamadart F16 GEMM F32 accumulation"} + ] } ] } diff --git a/tests/f16_dot_accumulation_test.cpp b/tests/f16_dot_accumulation_test.cpp index 86f5df1d..f329c6c8 100644 --- a/tests/f16_dot_accumulation_test.cpp +++ b/tests/f16_dot_accumulation_test.cpp @@ -5,6 +5,7 @@ #include "ggml-cpu.h" #endif +#include #include #include #include @@ -60,13 +61,13 @@ class Graph { }; bool check_result(float actual, double expected, double tolerance, - const char *name, int width) { + const char *name, int width, int cols) { const double error = std::fabs(static_cast(actual) - expected); if (!std::isfinite(actual) || !std::isfinite(expected) || !std::isfinite(error) || error > tolerance) { std::fprintf(stderr, - "FAIL: %s width=%d expected=%.17g actual=%.9g tolerance=%.9g\n", - name, width, expected, actual, tolerance); + "FAIL: %s width=%d cols=%d expected=%.17g actual=%.9g tolerance=%.9g\n", + name, width, cols, expected, actual, tolerance); ++failures; return false; } @@ -75,17 +76,25 @@ bool check_result(float actual, double expected, double tolerance, enum class Pattern { positive, cancellation, large_product, maximum, subnormal }; +// Sixteen identical weight rows times `cols` identical query columns. One +// column takes the vector dot kernel; eight or more take llamafile GEMM where +// it is built. NaN padding after each weight row fails any read past `width`. void dot_case(ggml_backend_t backend, int width, float magnitude, - Pattern pattern, ggml_type weight_type, const char *name) { + Pattern pattern, ggml_type weight_type, const char *name, int cols = 1) { + constexpr int rows = 16; + constexpr int padding = 8; + const int stride = width + padding; Graph graph(backend); - auto *k = ggml_new_tensor_2d(graph.ctx, weight_type, width, 1); - auto *q = ggml_new_tensor_2d(graph.ctx, GGML_TYPE_F32, width, 1); + auto *padded = ggml_new_tensor_2d(graph.ctx, weight_type, stride, rows); + auto *k = ggml_view_2d(graph.ctx, padded, width, rows, padded->nb[1], 0); + auto *q = ggml_new_tensor_2d(graph.ctx, GGML_TYPE_F32, width, cols); auto *out = ggml_mul_mat(graph.ctx, k, q); ggml_mul_mat_set_prec(out, GGML_PREC_F32); graph.allocate(out); - std::vector keys(width), queries(width); - std::vector half_keys(width); + std::vector keys(static_cast(stride) * rows, NAN); + std::vector half_keys(keys.size(), ggml_fp32_to_fp16(NAN)); + std::vector queries(static_cast(width) * cols); double reference = 0.0; double absolute_sum = 0.0; for (int i = 0; i < width; ++i) { @@ -102,38 +111,47 @@ void dot_case(ggml_backend_t backend, int width, float magnitude, kv = ggml_fp16_to_fp32(static_cast(1 + i % 7)); qv = i % 2 == 0 ? 1.0f : -1.0f; } - half_keys[i] = ggml_fp32_to_fp16(kv); - keys[i] = kv; - queries[i] = qv; - const double actual_k = weight_type == GGML_TYPE_F16 - ? ggml_fp16_to_fp32(half_keys[i]) : keys[i]; + for (int r = 0; r < rows; ++r) { + keys[static_cast(r) * stride + i] = kv; + half_keys[static_cast(r) * stride + i] = ggml_fp32_to_fp16(kv); + } + for (int c = 0; c < cols; ++c) { + queries[static_cast(c) * width + i] = qv; + } + const double actual_k = weight_type == GGML_TYPE_F16 ? rounded_f16(kv) : kv; // The F16 CPU type trait rounds the F32 query before its dot product. - const double actual_q = weight_type == GGML_TYPE_F16 - ? rounded_f16(queries[i]) : queries[i]; + const double actual_q = weight_type == GGML_TYPE_F16 ? rounded_f16(qv) : qv; const double product = actual_k * actual_q; reference += product; absolute_sum += std::fabs(product); } if (weight_type == GGML_TYPE_F16) { - ggml_backend_tensor_set(k, half_keys.data(), 0, half_keys.size() * sizeof(ggml_fp16_t)); + ggml_backend_tensor_set(padded, half_keys.data(), 0, half_keys.size() * sizeof(ggml_fp16_t)); } else { - ggml_backend_tensor_set(k, keys.data(), 0, keys.size() * sizeof(float)); + ggml_backend_tensor_set(padded, keys.data(), 0, keys.size() * sizeof(float)); } ggml_backend_tensor_set(q, queries.data(), 0, queries.size() * sizeof(float)); graph.compute(); - float actual = 0.0f; - ggml_backend_tensor_get(out, &actual, 0, sizeof(actual)); - check_result(actual, reference, 1e-7 + 2e-6 * absolute_sum, name, width); + std::vector actual(static_cast(rows) * cols); + ggml_backend_tensor_get(out, actual.data(), 0, actual.size() * sizeof(float)); + for (float value : actual) { + if (!check_result(value, reference, 1e-7 + 2e-6 * absolute_sum, name, width, cols)) { + break; + } + } } -void attention_case(ggml_backend_t backend, bool flash, float magnitude) { - constexpr int width = 64; - constexpr int values = 64; +// Each key score is 128 * (128 + r / 8): the first half of its products sums +// to 2^21 and the second half cancels it, so F16 partial sums overflow while +// the softmax over the 16 keys stays far from saturated. +void attention_case(ggml_backend_t backend, bool flash, int queries_count) { + constexpr int width = 256; + constexpr int keys_count = 16; Graph graph(backend); - auto *q = ggml_new_tensor_2d(graph.ctx, GGML_TYPE_F32, width, 1); - auto *k = ggml_new_tensor_2d(graph.ctx, GGML_TYPE_F16, width, 2); + auto *q = ggml_new_tensor_2d(graph.ctx, GGML_TYPE_F32, width, queries_count); + auto *k = ggml_new_tensor_2d(graph.ctx, GGML_TYPE_F16, width, keys_count); auto *v = ggml_new_tensor_2d(graph.ctx, GGML_TYPE_F16, - flash ? values : 2, flash ? 2 : values); + flash ? width : keys_count, flash ? keys_count : width); const float scale = 1.0f / std::sqrt(static_cast(width)); ggml_tensor *out; if (flash) { @@ -147,37 +165,50 @@ void attention_case(ggml_backend_t backend, bool flash, float magnitude) { } graph.allocate(out); - std::vector queries(width); - std::vector keys(2 * width), value_data(2 * values); - double score = 0.0; - for (int i = 0; i < width; ++i) { - queries[i] = magnitude * (1.0f + 0.1f * ((i * 3) % 5)); - keys[i] = ggml_fp32_to_fp16(magnitude * (1.0f + 0.1f * (i % 5))); - keys[width + i] = ggml_fp32_to_fp16(0.0f); - score += static_cast(ggml_fp16_to_fp32(keys[i])) * rounded_f16(queries[i]); - } - const double probability0 = 1.0 / (1.0 + std::exp(-score * scale)); - const double probability1 = 1.0 - probability0; - std::vector expected(values); - for (int i = 0; i < values; ++i) { - const float v0 = 1.0f + (i % 7) * 0.125f; - const float v1 = 2.0f + (i % 5) * 0.25f; - value_data[flash ? i : 2 * i] = ggml_fp32_to_fp16(v0); - value_data[flash ? values + i : 2 * i + 1] = ggml_fp32_to_fp16(v1); + std::vector queries(static_cast(width) * queries_count, 128.0f); + std::vector keys(static_cast(width) * keys_count); + std::vector value_data(static_cast(width) * keys_count); + std::vector logits(keys_count); + double max_logit = -INFINITY; + for (int r = 0; r < keys_count; ++r) { + double score = 0.0; + for (int i = 0; i < width; ++i) { + const float kv = i < width / 2 ? 128.0f : i < width - 1 ? -128.0f : 0.125f * r; + keys[static_cast(r) * width + i] = ggml_fp32_to_fp16(kv); + score += static_cast(kv) * 128.0; + } + logits[r] = score * scale; + max_logit = std::max(max_logit, logits[r]); + } + std::vector probabilities(keys_count); + double denominator = 0.0; + for (int r = 0; r < keys_count; ++r) { + probabilities[r] = std::exp(logits[r] - max_logit); + denominator += probabilities[r]; + } + std::vector expected(width, 0.0); + for (int r = 0; r < keys_count; ++r) { + probabilities[r] /= denominator; // Ordinary F16 V matmul also rounds its probability input to F16. - const double p0 = flash ? probability0 : rounded_f16(static_cast(probability0)); - const double p1 = flash ? probability1 : rounded_f16(static_cast(probability1)); - expected[i] = v0 * p0 + v1 * p1; + const double p = flash ? probabilities[r] : rounded_f16(static_cast(probabilities[r])); + for (int i = 0; i < width; ++i) { + const float value = 1.0f + ((i + r) % 7) * 0.125f; + value_data[flash ? static_cast(r) * width + i + : static_cast(i) * keys_count + r] = ggml_fp32_to_fp16(value); + expected[i] += value * p; + } } ggml_backend_tensor_set(q, queries.data(), 0, queries.size() * sizeof(float)); ggml_backend_tensor_set(k, keys.data(), 0, keys.size() * sizeof(ggml_fp16_t)); ggml_backend_tensor_set(v, value_data.data(), 0, value_data.size() * sizeof(ggml_fp16_t)); graph.compute(); - std::vector actual(values); + std::vector actual(static_cast(width) * queries_count); ggml_backend_tensor_get(out, actual.data(), 0, actual.size() * sizeof(float)); - for (int i = 0; i < values; ++i) { - if (!check_result(actual[i], expected[i], 1e-3, - flash ? "flash-attention" : "attention", width)) { + // Flash attention accumulates V in F16 on one of its CPU paths. + const double tolerance = flash ? 4e-3 : 1e-3; + for (size_t j = 0; j < actual.size(); ++j) { + if (!check_result(actual[j], expected[j % width], tolerance, + flash ? "flash-attention" : "attention", width, queries_count)) { break; } } @@ -228,9 +259,16 @@ int main() { dot_case(backend, 32, 0.0f, Pattern::large_product, GGML_TYPE_F16, "large-product"); dot_case(backend, 64, 0.0f, Pattern::maximum, GGML_TYPE_F16, "maximum-finite"); dot_case(backend, 64, 100.0f, Pattern::positive, GGML_TYPE_F32, "f32-control"); - for (float magnitude : {0.0f, 1.0f, 80.0f, 100.0f}) { - attention_case(backend, false, magnitude); - attention_case(backend, true, magnitude); + dot_case(backend, 256, 128.0f, Pattern::cancellation, GGML_TYPE_F16, "hidden-overflow"); + for (int cols : {8, 16, 32}) { + dot_case(backend, 64, 100.0f, Pattern::positive, GGML_TYPE_F16, "gemm-positive", cols); + dot_case(backend, 256, 128.0f, Pattern::cancellation, GGML_TYPE_F16, "gemm-hidden-overflow", cols); + } + dot_case(backend, 32, 0.0f, Pattern::large_product, GGML_TYPE_F16, "gemm-large-product", 8); + dot_case(backend, 64, 100.0f, Pattern::positive, GGML_TYPE_F32, "gemm-f32-control", 8); + for (int queries_count : {1, 8}) { + attention_case(backend, false, queries_count); + attention_case(backend, true, queries_count); } ggml_backend_free(backend); #if defined(LLAMADART_TEST_CPU_BACKEND) @@ -240,6 +278,6 @@ int main() { std::fprintf(stderr, "FAIL: %d checks\n", failures); return 1; } - std::printf("PASS: finite F16 dot, tails, controls and ordinary/flash attention\n"); + std::printf("PASS: finite F16 dot and GEMM, tails, controls and ordinary/flash attention\n"); return 0; } diff --git a/tests/test_llama_cpp_patches.py b/tests/test_llama_cpp_patches.py index 7d7aa903..1c3f9f6f 100644 --- a/tests/test_llama_cpp_patches.py +++ b/tests/test_llama_cpp_patches.py @@ -383,12 +383,20 @@ def test_the_embedding_reserve_patch_is_retired_only_where_upstream_has_the_fix( @unittest.skipUnless((UPSTREAM / "CMakeLists.txt").is_file(), "third_party/llama.cpp is not checked out") - def test_f16_dot_patch_applies_only_to_the_exact_source_and_preserves_upstream(self) -> None: - name = "0005-arm-f16-dot-f32-accumulation.patch" + def test_f16_accumulation_patches_apply_only_to_the_exact_source_and_preserve_upstream( + self) -> None: + for name, marker, context in ( + ("0005-arm-f16-dot-f32-accumulation.patch", + "llamadart F16 dot F32 accumulation", "void ggml_vec_dot_f16("), + ("0006-arm-f16-gemm-f32-accumulation.patch", + "llamadart F16 GEMM F32 accumulation", "tinyBLAS<8, float16x8_t")): + with self.subTest(patch=name): + self.check_exact_source_patch(name, marker, context) + + def check_exact_source_patch(self, name: str, marker: str, context: str) -> None: entry = next(entry for entry in patches.load_series() if entry["file"] == name) patch_text = (patches.PATCHES_DIR / name).read_text(encoding="utf-8") parsed = patches.parse_patch(name, patch_text) - self.assertEqual("ggml/src/ggml-cpu/vec.cpp", parsed.path) original = (UPSTREAM / parsed.path).read_text(encoding="utf-8") with tempfile.TemporaryDirectory() as directory: fixture = Path(directory) @@ -402,12 +410,11 @@ def test_f16_dot_patch_applies_only_to_the_exact_source_and_preserves_upstream(s json.dumps({"patches": [entry]}), encoding="utf-8") result = patches.apply_series(fixture / "upstream", patch_dir) self.assertEqual([parsed.path], list(result)) - marker = "llamadart F16 dot F32 accumulation" self.assertNotIn(marker, original) self.assertIn(marker, result[parsed.path]) self.assertEqual(original, source.read_text(encoding="utf-8")) - source.write_text(original.replace("void ggml_vec_dot_f16(", - "void changed_vec_dot_f16("), encoding="utf-8") + source.write_text(original.replace(context, "changed_" + context), + encoding="utf-8") rejected = source.read_text(encoding="utf-8") applied, skipped = patches.apply_available(fixture / "upstream", patch_dir) self.assertEqual({}, applied) @@ -466,7 +473,7 @@ def test_the_manifest_command_reads_the_given_upstream_not_the_submodule(self) - [sys.executable, str(ROOT / "tools/llama_cpp_patches.py"), "manifest", "--upstream", directory], capture_output=True, text=True) self.assertEqual(0, result.returncode, result.stderr) - self.assertEqual(["0001", "0002", "0003", "0004", "0005"], + self.assertEqual(["0001", "0002", "0003", "0004", "0005", "0006"], [e["file"][:4] for e in json.loads(result.stdout)]) @unittest.skipUnless((UPSTREAM / "CMakeLists.txt").is_file(),