From 8545ca6ad92a95ce1d5a889ce1ab099c5933e6ff Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 08:51:16 -0400 Subject: [PATCH 1/5] build: carry llama.cpp patches as build-tree copies and record them in the manifest Two Android Vulkan driver crashes (#79, llamadart#782) need a change inside ggml-vulkan that no upstream release has. Until now a fix could only come from moving the submodule. patches/llama.cpp holds unified diffs of upstream sources and a series.json. While CMake configures, tools/llama_cpp_patches.py writes the patched copy of each source to the build tree and the upstream target compiles the copy; the submodule is not modified. A hunk applies only where its context and removed lines occur exactly once, and every configuration applies the whole series, so a patch that upstream has outgrown fails every build instead of being dropped. assets.json gains llama_cpp_patches (file, sha256, tracking; empty without patches), and the Android artifact validation fails a bundle whose library lacks the text a patch compiles into it. The series is empty in this commit. Refs #79 --- AGENTS.md | 6 + CMakeLists.txt | 2 + CONTRIBUTING.md | 4 +- cmake/llama_cpp_patches.cmake | 80 +++++++++ docs/release_version_policy.md | 11 ++ docs/v060_2_wrapper_rebuild.md | 51 ++++++ patches/llama.cpp/README.md | 63 +++++++ patches/llama.cpp/series.json | 3 + scripts/generate_assets_manifest.sh | 5 + scripts/verify_release_provenance.py | 17 ++ tests/test_llama_cpp_patches.py | 223 +++++++++++++++++++++++++ tools/llama_cpp_patches.py | 237 +++++++++++++++++++++++++++ tools/validate_android_artifacts.py | 3 + 13 files changed, 704 insertions(+), 1 deletion(-) create mode 100644 cmake/llama_cpp_patches.cmake create mode 100644 docs/v060_2_wrapper_rebuild.md create mode 100644 patches/llama.cpp/README.md create mode 100644 patches/llama.cpp/series.json create mode 100644 tests/test_llama_cpp_patches.py create mode 100644 tools/llama_cpp_patches.py diff --git a/AGENTS.md b/AGENTS.md index fbbb24b6..c5c7d4a5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,8 @@ See `docs/v060_qualification.md` for the v0.6.0 wrapper adapters, candidate lane and the Android ISA evidence required before publication or downstream adoption. See `docs/v060_1_wrapper_rebuild.md` for the `v0.6.0-1` header additions and what each export returns after a caught exception. +See `docs/v060_2_wrapper_rebuild.md` for the carried llama.cpp patches of +`v0.6.0-2` and the device runs they still need. - `.github/workflows/native_release.yml` - Exact native build + release workflow, used by manual dispatch and the @@ -62,6 +64,10 @@ what each export returns after a caught exception. ## Change Boundaries - Prefer updating submodule refs over patching vendored upstream code directly. + Never edit `third_party/` in place. A fix that no upstream release has and + that `src/` or the build configuration cannot provide is carried as a patch + under `patches/llama.cpp/`; its `README.md` has the conditions and the + procedure. - Keep wrapper/runtime integration changes under `src/` and top-level build config. - Keep release manifest logic in `scripts/`/`tools/`. diff --git a/CMakeLists.txt b/CMakeLists.txt index 700d4cec..76ee4d8e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -139,6 +139,8 @@ if (APPLE) endif() add_subdirectory(third_party/llama.cpp) +include(cmake/llama_cpp_patches.cmake) +llamadart_apply_llama_cpp_patches() include(cmake/kleidiai_windows.cmake) llamadart_configure_kleidiai_windows_assembly() diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 40ae89db..2db31eb4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -56,7 +56,9 @@ python3 tools/build.py windows --arch x64 --backend vulkan correlation identifier. 5. Verify release assets (`assets.json`, `SHA256SUMS`, per-target bundles) and confirm that the native tag, upstream ref/commit, and native commit are - distinct and correct in the manifest and release notes. Download the final + distinct and correct in the manifest and release notes, and that + `llama_cpp_patches` lists exactly the files of `patches/llama.cpp/` at the + native commit. Download the final release-result JSON and verify its workflow/release metadata, digests, checksum entries, bundle coverage, correlation, and smoke conclusion. diff --git a/cmake/llama_cpp_patches.cmake b/cmake/llama_cpp_patches.cmake new file mode 100644 index 00000000..ccd33bae --- /dev/null +++ b/cmake/llama_cpp_patches.cmake @@ -0,0 +1,80 @@ +# Carried llama.cpp patches (patches/llama.cpp/README.md). The submodule stays +# as upstream published it: each patched source is written to the build tree +# and the upstream target that compiles the original compiles the copy instead. + +function(llamadart_collect_targets directory out_var) + get_property(targets DIRECTORY "${directory}" PROPERTY BUILDSYSTEM_TARGETS) + get_property(subdirectories DIRECTORY "${directory}" PROPERTY SUBDIRECTORIES) + foreach(subdirectory IN LISTS subdirectories) + llamadart_collect_targets("${subdirectory}" nested) + list(APPEND targets ${nested}) + endforeach() + set(${out_var} "${targets}" PARENT_SCOPE) +endfunction() + +function(llamadart_apply_llama_cpp_patches) + set(patches_dir "${CMAKE_CURRENT_SOURCE_DIR}/patches/llama.cpp") + set(upstream_dir "${CMAKE_CURRENT_SOURCE_DIR}/third_party/llama.cpp") + set(output_dir "${CMAKE_CURRENT_BINARY_DIR}/llama.cpp-patched") + + file(GLOB patch_files "${patches_dir}/*.patch") + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS + "${patches_dir}/series.json" ${patch_files} + "${CMAKE_CURRENT_SOURCE_DIR}/tools/llama_cpp_patches.py") + + find_package(Python3 COMPONENTS Interpreter REQUIRED) + # Every configuration applies the whole series, also one that builds none + # of the patched sources, so a patch that no longer applies fails them all. + execute_process( + COMMAND "${Python3_EXECUTABLE}" + "${CMAKE_CURRENT_SOURCE_DIR}/tools/llama_cpp_patches.py" + --patches "${patches_dir}" + apply --upstream "${upstream_dir}" --output "${output_dir}" + RESULT_VARIABLE result + OUTPUT_VARIABLE patched_sources + ERROR_VARIABLE error + OUTPUT_STRIP_TRAILING_WHITESPACE) + if (NOT result EQUAL 0) + message(FATAL_ERROR "Could not apply patches/llama.cpp:\n${error}") + endif() + if (NOT patched_sources) + return() + endif() + + llamadart_collect_targets("${upstream_dir}" upstream_targets) + foreach(relative IN LISTS patched_sources) + set(original "${upstream_dir}/${relative}") + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${original}") + get_filename_component(original_dir "${original}" DIRECTORY) + foreach(target IN LISTS upstream_targets) + get_target_property(type ${target} TYPE) + if (type STREQUAL "INTERFACE_LIBRARY") + continue() + endif() + get_target_property(sources ${target} SOURCES) + get_target_property(source_dir ${target} SOURCE_DIR) + if (NOT sources) + continue() + endif() + set(replaced OFF) + set(new_sources "") + foreach(source IN LISTS sources) + if (NOT source MATCHES "^\\$<") + get_filename_component(absolute "${source}" ABSOLUTE BASE_DIR "${source_dir}") + if (absolute STREQUAL original) + set(source "${output_dir}/${relative}") + set(replaced ON) + endif() + endif() + list(APPEND new_sources "${source}") + endforeach() + if (replaced) + set_property(TARGET ${target} PROPERTY SOURCES "${new_sources}") + # The copy includes its neighbours by name, which resolved + # next to the original. + target_include_directories(${target} BEFORE PRIVATE "${original_dir}") + message(STATUS "llama.cpp patches: ${target} compiles patched ${relative}") + endif() + endforeach() + endforeach() +endfunction() diff --git a/docs/release_version_policy.md b/docs/release_version_policy.md index ed9461bd..c7c95834 100644 --- a/docs/release_version_policy.md +++ b/docs/release_version_policy.md @@ -119,6 +119,17 @@ The historical `tag` field remains as a compatibility alias for valid. New manifests and release notes also bind the caller correlation ID, smoke policy/conclusion, exact workflow run, and workflow head SHA. +Every release is built with the llama.cpp patches its native commit carries +(`patches/llama.cpp/README.md`): each build applies all of them or fails. +`llama_cpp_patches` in `assets.json` lists the `file`, `sha256` and `tracking` +issue of each one and is an empty list for unmodified upstream source. +`llama_cpp_commit` stays the upstream commit the patches apply to: with a +non-empty `llama_cpp_patches` the artifacts are that commit plus exactly those +patches, and a comparison against upstream `llama.cpp` at the same commit must +account for them. A rebuild that only adds, refreshes or drops a patch is a +wrapper-only rebuild for the tag grammar: the upstream ref is unchanged and +the rebuild counter increases. + Do not mutate, republish, or reuse a tag. For a wrapper-only fix, keep the same `llama_cpp_tag`, choose the next policy-compliant native rebuild tag, and run the full build matrix. Publication, downstream pin updates, and downstream releases diff --git a/docs/v060_2_wrapper_rebuild.md b/docs/v060_2_wrapper_rebuild.md new file mode 100644 index 00000000..787bca23 --- /dev/null +++ b/docs/v060_2_wrapper_rebuild.md @@ -0,0 +1,51 @@ +# v0.6.0-2 rebuild + +Changes on llama.cpp `v0.6.0` +(`d81235049384534c167caea52b85a694f6103d14`) for the native rebuild tag +`v0.6.0-2`. The exported header is unchanged from `v0.6.0-1`. + +## Carried llama.cpp patches + +This is the first release built with patches on top of the pinned upstream +source. `patches/llama.cpp/README.md` has the conditions, the file format and +the procedure. In short: + +- `third_party/llama.cpp` is not modified. While CMake configures, + `tools/llama_cpp_patches.py` writes a patched copy of each source that a + patch edits to `/llama.cpp-patched/`, and + `cmake/llama_cpp_patches.cmake` makes the upstream target compile the copy. + `cmake/kleidiai_windows.cmake` and the Android CPU backend score object + already add sources to upstream targets from this repository's CMake; this + replaces one. +- A hunk applies only where its context and removed lines occur exactly once. + Every configuration applies every patch, so a patch that upstream has + outgrown fails every lane, including the automatic stable release. +- `assets.json` gains `llama_cpp_patches`, the `file`, `sha256` and `tracking` + issue of each patch, and `[]` for a release without any. +- `tools/validate_android_artifacts.py` fails an Android bundle in which a + library lacks the text that a patch compiles into it. + +A consumer that compares against upstream `llama.cpp` at `llama_cpp_commit` +(`docs/parity_tools.md`) compares against unpatched source. The patches of +this rebuild change only `ggml-vulkan`, each for the condition its section +names. + +## Checks + +```bash +git submodule update --init --recursive +python3 -m unittest discover -s tests -p 'test_*.py' +python3 scripts/verify_release_provenance.py +cmake -S . -B build/v060 -G Ninja -DCMAKE_BUILD_TYPE=Debug \ + -DGGML_METAL=ON -DGGML_OPENMP=OFF -DGGML_CCACHE=OFF \ + -DGGML_CPU_KLEIDIAI=OFF -DLLAMADART_BUILD_TESTS=ON +cmake --build build/v060 --parallel 8 +ctest --test-dir build/v060 --output-on-failure +``` + +`tests/test_llama_cpp_patches.py` covers the patch tool on its own sources and, +with the submodule checked out, applies the carried series to it. The +`android-vulkan-shaders` lane of `validate_wrapper.yml` compiles the patched +`ggml-vulkan.cpp` with the release NDK against the pinned, `v0.5.0` and +`v0.6.0` upstreams and, on the pinned one, validates the bundle. No lane runs +ggml-vulkan on a device. diff --git a/patches/llama.cpp/README.md b/patches/llama.cpp/README.md new file mode 100644 index 00000000..f4aff8c4 --- /dev/null +++ b/patches/llama.cpp/README.md @@ -0,0 +1,63 @@ +# Carried llama.cpp patches + +Changes to llama.cpp sources that this repository's builds apply on top of the +pinned upstream commit. `third_party/llama.cpp` itself stays exactly as +upstream published it. + +Updating the submodule to an upstream release that has the fix is still the +preferred way to get a fix (`AGENTS.md`). A patch is carried only when all of +these hold: + +- A released artifact crashes or gives wrong results, and nothing in `src/` or + the build configuration can prevent it. +- No upstream release has the fix, and the fix is a few lines. +- The patch has an issue in `leehack/llamadart-native` or `leehack/llamadart` + and, where one exists, an upstream pull request or issue. + +## Files + +- `series.json` lists the patches in the order they apply. Each entry has the + patch `file`, the `tracking` issue, the `upstream` pull request or issue to + watch, and optional `android_markers`: a `library` of the Android bundle and + a `text` that only the patched source compiles into it. +- `NNNN-short-name.patch` is a unified diff (`git diff -U2` inside + `third_party/llama.cpp`) of one existing `.c`, `.cpp`, `.m` or `.mm` file. A + patch cannot add a file or edit a header: only a source that an upstream + target compiles can be replaced. + +## How they are applied + +`cmake/llama_cpp_patches.cmake` runs `tools/llama_cpp_patches.py` while CMake +configures. It writes the patched copy of each source to +`/llama.cpp-patched/` and makes the upstream target compile that copy +instead of the original. Every build of this repository does this, on every +platform, including one that compiles none of the patched sources. + +A hunk applies only where its context and removed lines occur exactly once in +the upstream file. There is no fuzz. When upstream changes those lines the +configure step fails and names the patch: check whether upstream fixed the +defect, then refresh the patch against the new source or delete it. The +automatic stable release fails the same way until that is done, which is +intended: a release must not silently lose a fix. + +## What a release records + +`assets.json` has `llama_cpp_patches`: the `file`, `sha256` and `tracking` of +every patch, an empty list when there is none. `llama_cpp_commit` remains the +upstream commit the patches apply to. `tools/validate_android_artifacts.py` +fails an Android bundle whose library lacks the text of an `android_markers` +entry. + +## Adding, refreshing or removing a patch + +1. Edit the source inside `third_party/llama.cpp`, write + `git -C third_party/llama.cpp diff -U2 > patches/llama.cpp/NNNN-name.patch`, + then restore the submodule with `git -C third_party/llama.cpp checkout -- .`. +2. Add or remove the `series.json` entry. +3. Run `python3 -m unittest tests.test_llama_cpp_patches` with the submodule + checked out, and build a target that compiles the patched source. +4. Describe the patch, its evidence and what removes it in the document of the + rebuild that introduces it under `docs/`. + +Remove a patch when the pinned upstream contains the fix or the defect no +longer reproduces without it. diff --git a/patches/llama.cpp/series.json b/patches/llama.cpp/series.json new file mode 100644 index 00000000..7fdf07f8 --- /dev/null +++ b/patches/llama.cpp/series.json @@ -0,0 +1,3 @@ +{ + "patches": [] +} diff --git a/scripts/generate_assets_manifest.sh b/scripts/generate_assets_manifest.sh index dbad582a..bcfa1a89 100755 --- a/scripts/generate_assets_manifest.sh +++ b/scripts/generate_assets_manifest.sh @@ -76,6 +76,10 @@ timestamp="$(date -u +"%Y-%m-%dT%H:%M:%SZ")" llama_cpp_tag="${LLAMADART_LLAMA_CPP_TAG:-$tag}" llama_cpp_commit="${LLAMADART_LLAMA_CPP_COMMIT:-}" native_commit="${LLAMADART_NATIVE_COMMIT:-}" +# The llama.cpp patches this checkout carries: every build of it applies all of +# them or fails, so the release carries exactly these. +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +llama_cpp_patches="$(python3 "$repo_root/tools/llama_cpp_patches.py" manifest)" correlation_id="${LLAMADART_CORRELATION_ID:-}" smoke_policy="${LLAMADART_SMOKE_POLICY:-}" smoke_conclusion="${LLAMADART_SMOKE_CONCLUSION:-}" @@ -103,6 +107,7 @@ EOF_FILES if [ -n "$llama_cpp_commit" ]; then printf ' "llama_cpp_commit": %s,\n' "$(json_string "$llama_cpp_commit")" fi + printf ' "llama_cpp_patches": %s,\n' "$llama_cpp_patches" if [ -n "$native_commit" ]; then printf ' "native_commit": %s,\n' "$(json_string "$native_commit")" fi diff --git a/scripts/verify_release_provenance.py b/scripts/verify_release_provenance.py index be1395c7..f7de577f 100755 --- a/scripts/verify_release_provenance.py +++ b/scripts/verify_release_provenance.py @@ -616,9 +616,24 @@ def verify_documentation_contract(errors: list[str]) -> None: "maintainer docs must explain exact-transaction partial-publication recovery", errors, ) + require( + "llama_cpp_patches" in documentation and "patches/llama.cpp" in documentation, + "maintainer docs must say that a release may carry llama.cpp patches and where " + "the manifest records them", + errors, + ) def verify_manifest_contract(errors: list[str]) -> None: + patches_dir = ROOT / "patches/llama.cpp" + carried_patches = [ + { + "file": entry["file"], + "sha256": hashlib.sha256((patches_dir / entry["file"]).read_bytes()).hexdigest(), + "tracking": entry["tracking"], + } + for entry in json.loads((patches_dir / "series.json").read_text())["patches"] + ] with tempfile.TemporaryDirectory() as directory: root = Path(directory) fixtures = ( @@ -678,12 +693,14 @@ def verify_manifest_contract(errors: list[str]) -> None: "native_release_tag", "llama_cpp_tag", "llama_cpp_commit", + "llama_cpp_patches", "native_commit", "generated_at", "hook_contract_version", "artifacts", } and manifest.get("hook_contract_version") == 1 + and manifest.get("llama_cpp_patches") == carried_patches and re.fullmatch( r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z", manifest.get("generated_at", ""), diff --git a/tests/test_llama_cpp_patches.py b/tests/test_llama_cpp_patches.py new file mode 100644 index 00000000..9034dfff --- /dev/null +++ b/tests/test_llama_cpp_patches.py @@ -0,0 +1,223 @@ +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) + +import llama_cpp_patches as patches # noqa: E402 + +UPSTREAM = ROOT / "third_party/llama.cpp" +SOURCE = "src/thing.cpp" +ORIGINAL = "int a = 1;\nint b = 2;\nint c = 3;\nint d = 4;\n" +EDIT_B = f"""\ +diff --git a/{SOURCE} b/{SOURCE} +index 1111111..2222222 100644 +--- a/{SOURCE} ++++ b/{SOURCE} +@@ -1,3 +1,4 @@ + int a = 1; +-int b = 2; ++int b = 20; ++int b2 = 21; + int c = 3; +""" +EDIT_D = f"""\ +--- a/{SOURCE} ++++ b/{SOURCE} +@@ -3,2 +3,2 @@ context that is not compared + int c = 3; +-int d = 4; ++int d = 40; +""" + + +class Fixture: + """An upstream tree and a patches directory holding the given patches.""" + + def __init__(self, directory: str, named_patches: dict[str, str]) -> None: + self.upstream = Path(directory) / "upstream" + self.patches = Path(directory) / "patches" + self.output = Path(directory) / "output" + self.patches.mkdir() + (self.upstream / SOURCE).parent.mkdir(parents=True) + (self.upstream / SOURCE).write_text(ORIGINAL, encoding="utf-8") + self.series = [] + for file, text in named_patches.items(): + (self.patches / file).write_text(text, encoding="utf-8") + self.series.append({ + "file": file, + "tracking": "https://example.invalid/issue", + "upstream": "https://example.invalid/pull", + }) + self.write_series() + + def write_series(self) -> None: + (self.patches / "series.json").write_text( + json.dumps({"patches": self.series}), encoding="utf-8") + + def apply(self) -> dict[str, str]: + return patches.apply_series(self.upstream, self.patches) + + +class ApplyTests(unittest.TestCase): + def fixture(self, **named_patches: str) -> Fixture: + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + return Fixture(directory.name, { + name.replace("_", "-") + ".patch": text for name, text in named_patches.items() + }) + + def assert_rejected(self, fixture: Fixture, message: str) -> None: + with self.assertRaises(patches.PatchError) as raised: + fixture.apply() + self.assertIn(message, str(raised.exception)) + + def test_patches_of_one_file_apply_in_series_order(self) -> None: + fixture = self.fixture(**{"0001_edit_b": EDIT_B, "0002_edit_d": EDIT_D}) + self.assertEqual( + {SOURCE: "int a = 1;\nint b = 20;\nint b2 = 21;\nint c = 3;\nint d = 40;\n"}, + fixture.apply()) + self.assertEqual(ORIGINAL, (fixture.upstream / SOURCE).read_text(encoding="utf-8")) + + def test_a_crlf_checkout_applies_like_an_lf_one(self) -> None: + fixture = self.fixture(**{"0001_edit_b": EDIT_B}) + (fixture.upstream / SOURCE).write_bytes(ORIGINAL.replace("\n", "\r\n").encode()) + patch = fixture.patches / "0001-edit-b.patch" + patch.write_bytes(EDIT_B.replace("\n", "\r\n").encode()) + self.assertEqual("int a = 1;\nint b = 20;\nint b2 = 21;\nint c = 3;\nint d = 4;\n", + fixture.apply()[SOURCE]) + + def test_upstream_drift_fails_instead_of_applying_elsewhere(self) -> None: + fixture = self.fixture(**{"0001_edit_b": EDIT_B}) + (fixture.upstream / SOURCE).write_text( + ORIGINAL.replace("int c = 3;", "int c = 30;"), encoding="utf-8") + self.assert_rejected(fixture, "matches src/thing.cpp 0 times, expected 1") + + def test_an_ambiguous_hunk_fails(self) -> None: + fixture = self.fixture(**{"0001_edit_b": EDIT_B}) + (fixture.upstream / SOURCE).write_text(ORIGINAL + ORIGINAL, encoding="utf-8") + self.assert_rejected(fixture, "matches src/thing.cpp 2 times, expected 1") + + def test_only_an_existing_compiled_source_can_be_patched(self) -> None: + header = EDIT_B.replace(SOURCE, "src/thing.h") + self.assert_rejected(self.fixture(**{"0001_header": header}), + "src/thing.h is not a compiled source") + outside = EDIT_B.replace(SOURCE, "../outside.cpp") + self.assert_rejected(self.fixture(**{"0001_outside": outside}), + "is not a compiled source inside llama.cpp") + created = EDIT_B.replace("index 1111111..2222222 100644", "new file mode 100644") + self.assert_rejected(self.fixture(**{"0001_created": created}), + "only edits of an existing text source") + two_files = EDIT_B + EDIT_B.replace(SOURCE, "src/other.cpp") + self.assert_rejected(self.fixture(**{"0001_two_files": two_files}), "unsupported line") + fixture = self.fixture(**{"0001_edit_b": EDIT_B}) + (fixture.upstream / SOURCE).unlink() + self.assert_rejected(fixture, "does not exist") + + def test_the_series_and_the_directory_must_agree(self) -> None: + fixture = self.fixture(**{"0001_edit_b": EDIT_B}) + (fixture.patches / "0002-unlisted.patch").write_text(EDIT_D, encoding="utf-8") + self.assert_rejected(fixture, "0002-unlisted.patch") + (fixture.patches / "0002-unlisted.patch").unlink() + fixture.series.append(dict(fixture.series[0], file="0002-missing.patch")) + fixture.write_series() + self.assert_rejected(fixture, "0002-missing.patch") + fixture.series = [dict(fixture.series[0], upstream="none")] + fixture.write_series() + self.assert_rejected(fixture, '"upstream" must be an https URL') + fixture.series = [dict(fixture.series[0], upstream="https://example.invalid", note="x")] + fixture.write_series() + self.assert_rejected(fixture, "unknown keys ['note']") + + def test_an_unchanged_copy_keeps_its_timestamp(self) -> None: + fixture = self.fixture(**{"0001_edit_b": EDIT_B}) + self.assertEqual([SOURCE], + patches.write_patched(fixture.upstream, fixture.output, fixture.patches)) + copy = fixture.output / SOURCE + os.utime(copy, (1, 1)) + patches.write_patched(fixture.upstream, fixture.output, fixture.patches) + self.assertEqual(1, copy.stat().st_mtime) + (fixture.patches / "0001-edit-b.patch").write_text( + EDIT_B.replace("int b2 = 21;", "int b2 = 22;"), encoding="utf-8") + patches.write_patched(fixture.upstream, fixture.output, fixture.patches) + self.assertNotEqual(1, copy.stat().st_mtime) + self.assertIn("int b2 = 22;", copy.read_text(encoding="utf-8")) + + def test_the_tool_prints_what_cmake_reads_and_fails_with_the_reason(self) -> None: + fixture = self.fixture(**{"0001_edit_b": EDIT_B}) + command = [sys.executable, str(ROOT / "tools/llama_cpp_patches.py"), + "--patches", str(fixture.patches), "apply", + "--upstream", str(fixture.upstream), "--output", str(fixture.output)] + result = subprocess.run(command, capture_output=True, text=True) + self.assertEqual((0, SOURCE + "\n"), (result.returncode, result.stdout)) + (fixture.upstream / SOURCE).write_text("int z;\n", encoding="utf-8") + result = subprocess.run(command, capture_output=True, text=True) + self.assertEqual(1, result.returncode) + self.assertIn("0001-edit-b.patch", result.stderr) + self.assertIn("re-qualify the patch", result.stderr) + + def test_a_bundle_library_without_its_marker_is_reported(self) -> None: + fixture = self.fixture(**{"0001_edit_b": EDIT_B}) + fixture.series[0]["android_markers"] = [{"library": "libthing.so", "text": "b2 marker"}] + fixture.write_series() + bundle = fixture.output + bundle.mkdir() + self.assertEqual([], patches.android_marker_errors(bundle, fixture.patches)) + (bundle / "libthing.so").write_bytes(b"\x7fELF without it") + self.assertEqual( + ["libthing.so: built without 0001-edit-b.patch (no 'b2 marker')"], + patches.android_marker_errors(bundle, fixture.patches)) + (bundle / "libthing.so").write_bytes(b"\x7fELF b2 marker\x00") + self.assertEqual([], patches.android_marker_errors(bundle, fixture.patches)) + + def test_the_manifest_names_each_patch_and_its_digest(self) -> None: + fixture = self.fixture(**{"0001_edit_b": EDIT_B}) + self.assertEqual( + [{"file": "0001-edit-b.patch", + "sha256": hashlib.sha256(EDIT_B.encode()).hexdigest(), + "tracking": "https://example.invalid/issue"}], + patches.manifest_entries(fixture.patches)) + + +class CarriedSeriesTests(unittest.TestCase): + def test_the_series_is_well_formed(self) -> None: + for entry in patches.load_series(): + patches.parse_patch(entry["file"], (patches.PATCHES_DIR / entry["file"]).read_text( + encoding="utf-8")) + + def test_the_build_applies_the_series_after_adding_llama_cpp(self) -> None: + cmake = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8") + added = cmake.index("add_subdirectory(third_party/llama.cpp)") + applied = cmake.index("llamadart_apply_llama_cpp_patches()") + self.assertLess(added, applied) + self.assertLess(applied, cmake.index("add_library(llamadart_lib SHARED")) + + @unittest.skipUnless((UPSTREAM / "CMakeLists.txt").is_file(), + "third_party/llama.cpp is not checked out") + def test_the_series_applies_to_the_checked_out_llama_cpp(self) -> None: + patched = patches.apply_series(UPSTREAM) + for entry in patches.load_series(): + path = patches.parse_patch(entry["file"], (patches.PATCHES_DIR / entry["file"]) + .read_text(encoding="utf-8")).path + original = (UPSTREAM / path).read_text(encoding="utf-8") + for marker in entry.get("android_markers", []): + # A marker tells a patched library from an unpatched one only + # if the patch is what introduces it. + self.assertNotIn(marker["text"], original, entry["file"]) + self.assertIn(marker["text"], patched[path], entry["file"]) + status = subprocess.run( + ["git", "-C", str(UPSTREAM), "status", "--porcelain"], + capture_output=True, text=True, check=True) + self.assertEqual("", status.stdout, "applying must not modify the submodule") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/llama_cpp_patches.py b/tools/llama_cpp_patches.py new file mode 100644 index 00000000..2d5fea67 --- /dev/null +++ b/tools/llama_cpp_patches.py @@ -0,0 +1,237 @@ +#!/usr/bin/env python3 +"""Applies patches/llama.cpp to copies of upstream sources; see its README.md.""" +from __future__ import annotations + +import argparse +import hashlib +import json +import re +import sys +from dataclasses import dataclass +from pathlib import Path, PurePosixPath + +ROOT = Path(__file__).resolve().parents[1] +PATCHES_DIR = ROOT / "patches" / "llama.cpp" +SERIES_NAME = "series.json" +# A patched file replaces a source of an upstream target, so it must be one: +# a header is included from the submodule by sources this does not see. +SOURCE_SUFFIXES = frozenset({".c", ".cc", ".cpp", ".cxx", ".m", ".mm"}) +PATCH_NAME = re.compile(r"\d{4}-[a-z0-9]+(?:-[a-z0-9]+)*\.patch") +HUNK_HEADER = re.compile(r"@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@") +SERIES_KEYS = frozenset({"file", "tracking", "upstream", "android_markers"}) +MARKER_KEYS = frozenset({"library", "text"}) + + +class PatchError(Exception): + pass + + +@dataclass(frozen=True) +class Hunk: + header: str + before: str + after: str + + +@dataclass(frozen=True) +class Patch: + name: str + path: str + hunks: tuple[Hunk, ...] + + +def _read_text(path: Path) -> str: + # Universal newlines: a Windows checkout may hold either side as CRLF. + with path.open(encoding="utf-8", newline=None) as handle: + return handle.read() + + +def load_series(patches_dir: Path = PATCHES_DIR) -> list[dict]: + """Returns the entries of series.json, in the order they are applied.""" + series_path = patches_dir / SERIES_NAME + try: + entries = json.loads(series_path.read_text(encoding="utf-8"))["patches"] + except (OSError, ValueError, KeyError, TypeError) as error: + raise PatchError(f"{series_path}: expected {{\"patches\": [...]}}: {error}") from error + if not isinstance(entries, list): + raise PatchError(f"{series_path}: \"patches\" must be a list") + names: list[str] = [] + for entry in entries: + if not isinstance(entry, dict) or not isinstance(entry.get("file"), str): + raise PatchError(f"{series_path}: every patch needs a \"file\"") + name = entry["file"] + unknown = sorted(set(entry) - SERIES_KEYS) + if unknown: + raise PatchError(f"{series_path}: {name}: unknown keys {unknown}") + if PATCH_NAME.fullmatch(name) is None: + raise PatchError(f"{series_path}: {name}: expected NNNN-lower-case-words.patch") + for key in ("tracking", "upstream"): + if not str(entry.get(key, "")).startswith("https://"): + raise PatchError(f"{series_path}: {name}: \"{key}\" must be an https URL") + markers = entry.get("android_markers", []) + if not isinstance(markers, list) or not all( + isinstance(marker, dict) + and set(marker) == MARKER_KEYS + and all(isinstance(value, str) and value for value in marker.values()) + for marker in markers + ): + raise PatchError( + f"{series_path}: {name}: \"android_markers\" must list {{library, text}}" + ) + names.append(name) + if names != sorted(set(names)): + raise PatchError(f"{series_path}: patches must be unique and in name order") + on_disk = sorted(path.name for path in patches_dir.glob("*.patch")) + if on_disk != names: + raise PatchError( + f"{series_path}: lists {names} but {patches_dir} holds {on_disk}" + ) + return entries + + +def parse_patch(name: str, text: str) -> Patch: + """Parses a unified diff of one existing source file.""" + lines = text.split("\n") + if lines and lines[-1] == "": + lines.pop() + paths: list[str] = [] + hunks: list[Hunk] = [] + header = "" + before: list[str] = [] + after: list[str] = [] + + def close_hunk() -> None: + if header: + if before == after: + raise PatchError(f"{name}: {header}: hunk changes nothing") + hunks.append(Hunk(header, "".join(before), "".join(after))) + + for line in lines: + if not header: + if line.startswith(("new file mode", "deleted file mode", "rename ", "Binary files")): + raise PatchError(f"{name}: only edits of an existing text source are supported") + if line.startswith("diff --git ") and paths: + raise PatchError(f"{name}: a patch edits exactly one file") + if line.startswith(("--- ", "+++ ")): + prefix = "a/" if line.startswith("--- ") else "b/" + if not line[4:].startswith(prefix): + raise PatchError(f"{name}: expected a -p1 path in {line!r}") + paths.append(line[4 + len(prefix):]) + continue + if HUNK_HEADER.match(line): + close_hunk() + header, before, after = line, [], [] + elif header: + if line.startswith(" ") or line == "": + before.append(line[1:] + "\n") + after.append(line[1:] + "\n") + elif line.startswith("-"): + before.append(line[1:] + "\n") + elif line.startswith("+"): + after.append(line[1:] + "\n") + else: + raise PatchError(f"{name}: unsupported line {line!r}") + close_hunk() + if len(paths) != 2 or paths[0] != paths[1]: + raise PatchError(f"{name}: expected one '--- a/PATH' and '+++ b/PATH' pair") + path = PurePosixPath(paths[0]) + if path.is_absolute() or ".." in path.parts or path.suffix not in SOURCE_SUFFIXES: + raise PatchError( + f"{name}: {paths[0]} is not a compiled source inside llama.cpp " + f"({', '.join(sorted(SOURCE_SUFFIXES))})" + ) + if not hunks: + raise PatchError(f"{name}: no hunks") + return Patch(name, paths[0], tuple(hunks)) + + +def apply_series(upstream: Path, patches_dir: Path = PATCHES_DIR) -> dict[str, str]: + """Returns the patched text of every upstream source the series edits. + + A hunk applies only where its context and removed lines occur exactly + once: there is no fuzz and no offset search, so upstream drift fails. + """ + patched: dict[str, str] = {} + for entry in load_series(patches_dir): + name = entry["file"] + patch = parse_patch(name, _read_text(patches_dir / name)) + if patch.path not in patched: + source = upstream / patch.path + if not source.is_file(): + raise PatchError(f"{name}: {source} does not exist") + patched[patch.path] = _read_text(source) + text = patched[patch.path] + for hunk in patch.hunks: + count = text.count(hunk.before) + if count != 1: + raise PatchError( + f"{name}: {hunk.header} matches {patch.path} {count} times, expected 1. " + "Upstream changed these lines: re-qualify the patch for this llama.cpp " + "or remove it (patches/llama.cpp/README.md)." + ) + text = text.replace(hunk.before, hunk.after) + patched[patch.path] = text + return patched + + +def manifest_entries(patches_dir: Path = PATCHES_DIR) -> list[dict[str, str]]: + """What a release manifest records of the carried patches.""" + return [ + { + "file": entry["file"], + "sha256": hashlib.sha256((patches_dir / entry["file"]).read_bytes()).hexdigest(), + "tracking": entry["tracking"], + } + for entry in load_series(patches_dir) + ] + + +def android_marker_errors(out_dir: Path, patches_dir: Path = PATCHES_DIR) -> list[str]: + """Names each bundled library that lacks the text a carried patch compiles in.""" + errors: list[str] = [] + for entry in load_series(patches_dir): + for marker in entry.get("android_markers", []): + library = out_dir / marker["library"] + if library.is_file() and marker["text"].encode() not in library.read_bytes(): + errors.append( + f"{marker['library']}: built without {entry['file']} " + f"(no {marker['text']!r})" + ) + return errors + + +def write_patched(upstream: Path, output: Path, patches_dir: Path) -> list[str]: + patched = apply_series(upstream, patches_dir) + for relative, text in patched.items(): + target = output / relative + # Keep the timestamp of an unchanged copy so reconfiguring rebuilds nothing. + if target.is_file() and _read_text(target) == text: + continue + target.parent.mkdir(parents=True, exist_ok=True) + with target.open("w", encoding="utf-8", newline="\n") as handle: + handle.write(text) + return sorted(patched) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--patches", type=Path, default=PATCHES_DIR) + commands = parser.add_subparsers(dest="command", required=True) + apply = commands.add_parser("apply", help="write patched copies and print their paths") + apply.add_argument("--upstream", type=Path, required=True) + apply.add_argument("--output", type=Path, required=True) + commands.add_parser("manifest", help="print the carried patches as JSON") + args = parser.parse_args() + try: + if args.command == "apply": + print(";".join(write_patched(args.upstream, args.output, args.patches))) + else: + print(json.dumps(manifest_entries(args.patches))) + except PatchError as error: + print(f"llama.cpp patches: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/validate_android_artifacts.py b/tools/validate_android_artifacts.py index d30b94da..a0805b84 100644 --- a/tools/validate_android_artifacts.py +++ b/tools/validate_android_artifacts.py @@ -5,6 +5,8 @@ import subprocess from pathlib import Path +import llama_cpp_patches + def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() @@ -113,6 +115,7 @@ def main() -> None: errors: list[str] = [] symbols = {library.name: read_dynamic_symbols(args.readelf, library) for library in libraries} errors.extend(exception_runtime_errors(symbols)) + errors.extend(llama_cpp_patches.android_marker_errors(args.out_dir)) for symbol in EXCEPTION_RUNTIME_SYMBOLS: for name, (defined, _) in sorted(symbols.items()): if symbol in defined: From 22a7828be378de66d52a7b6b4bb5ec67a85c1f5a Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 08:55:06 -0400 Subject: [PATCH 2/5] fix: use the shared-memory matvec reduction on the Adreno 750 driver that crashes On a Galaxy S24 (Adreno 750, driver version 2150604839) the first prompt decode on Vulkan ended the process with SIGSEGV in the driver's shader compiler: ggml-vulkan builds the dequantize matrix-vector pipelines in the subgroup reduction mode with required full subgroups of size 64 (ggml_vk_load_shaders, ggml-vulkan.cpp:2899 at d81235049), and this compiler crashes on them once the batch has two to five columns, depending on the weight type. Patch 0001 sets use_subgroups to false for that block on exactly this driver, in Android builds only, which is the source change of the draft ggml-org/llama.cpp#29165. The issue records stories15M F32 and Qwen3.5-0.8B Q4_0 generating 32 of 32 tokens equal to CPU with that change on llama.cpp b11256. It has not run on v0.6.0, and Q8_0, K-quant, IQ4_XS and IQ3_S weights remain wrong on this driver with or without it. Refs #79 --- docs/v060_2_wrapper_rebuild.md | 58 +++++++++++++++++++ ...o-750-matvec-shared-memory-reduction.patch | 22 +++++++ patches/llama.cpp/series.json | 11 +++- 3 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 patches/llama.cpp/0001-vulkan-adreno-750-matvec-shared-memory-reduction.patch diff --git a/docs/v060_2_wrapper_rebuild.md b/docs/v060_2_wrapper_rebuild.md index 787bca23..64bab7da 100644 --- a/docs/v060_2_wrapper_rebuild.md +++ b/docs/v060_2_wrapper_rebuild.md @@ -30,6 +30,64 @@ A consumer that compares against upstream `llama.cpp` at `llama_cpp_commit` this rebuild change only `ggml-vulkan`, each for the condition its section names. +## Adreno 750 shader compiler crash + +Issue: [llamadart-native#79](https://github.com/leehack/llamadart-native/issues/79). +Patch: `0001-vulkan-adreno-750-matvec-shared-memory-reduction.patch`. + +On a Galaxy S24 (`SC-51E`, Adreno 750, driver version `2150604839`, build +`c81b28e1a5`) the first prompt decode on Vulkan ends the process: `SIGSEGV` at +`0x2d0` in the driver's shader compiler (`CreateQGLCProgram`), under +`vkCreateComputePipelines`. A crash inside the driver cannot be caught. + +Root cause at `d81235049`, `ggml/src/ggml-vulkan/ggml-vulkan.cpp`: +`ggml_vk_load_shaders` sets `use_subgroups = device->subgroup_arithmetic` +(line 2899) and with it builds every dequantize matrix-vector pipeline in the +subgroup or hybrid reduction mode (lines 2927 to 2929), requiring full +subgroups of the device's subgroup size, 64 here (lines 2910 and 2936; +`eRequireFullSubgroupsEXT` and `requiredSubgroupSize` at lines 731 and 742). +The pipelines are compiled on first use, from `ggml_vk_mul_mat_vec_q_f16` +(line 6638). This driver's compiler crashes on those shaders once the batch +has enough columns: 5 for F32, 3 for F16, BF16, Q4_0, Q4_1, Q5_0 and Q5_1, 2 +for IQ4_NL. A single-token decode compiles, so the crash comes with the first +prompt. Upstream `master` at `609290be6` (2026-10-09) has the same code. + +The patch sets `use_subgroups = false` for that block when the device is +exactly this driver (vendor `0x5143`, `VK_DRIVER_ID_QUALCOMM_PROPRIETARY`, +driver version `2150604839`, name `Adreno (TM) 750`), in Android builds only. +The pipelines then use the shared-memory reduction and no required subgroup +size, which is what ggml already does for a device without subgroup +arithmetic and, for part of the block, for the Imagination driver. It is the +source change of the draft +[ggml-org/llama.cpp#29165](https://github.com/ggml-org/llama.cpp/pull/29165) +(`8640bb336`), without its build option. + +Evidence, from the issue: Galaxy S24 `SC-51E`, Android 16, Firebase Test Lab, +a JNI app on the llama.cpp C API, context 1024, batch 1024, micro-batch 512, +flash attention off, every layer on the GPU, greedy decoding, 32 tokens, +compared with the CPU in the same app. llama.cpp was `b11256` (`c85b92c69`), +not `v0.6.0`. + +| Build | stories15M F32 | Qwen3.5-0.8B Q4_0 | +| --- | --- | --- | +| `b11256` | crash | crash | +| `b11256` with this change | 32 of 32 tokens equal to CPU | 32 of 32 tokens equal to CPU | + +What the patch does not fix, on this driver: + +- Matrix-vector products of Q8_0, Q2_K to Q6_K, IQ4_XS and IQ3_S weights give + wrong results (relative error 0.06 to 0.31) with and without the patch, and + Q4_K with one column fails pipeline creation with `VK_ERROR_UNKNOWN`. A + model in one of these types, which includes the common `Q4_K_M`, does not + work on Vulkan on this driver. +- Batches above 8 columns, flash attention, `mul_mat_vec_id` and F16 + activations were not run on the device. +- Another driver version or another Adreno is not matched and behaves as + before. + +Remove the patch when the pinned upstream has an equivalent change, or when +the S24 run passes without it. + ## Checks ```bash diff --git a/patches/llama.cpp/0001-vulkan-adreno-750-matvec-shared-memory-reduction.patch b/patches/llama.cpp/0001-vulkan-adreno-750-matvec-shared-memory-reduction.patch new file mode 100644 index 00000000..828a0043 --- /dev/null +++ b/patches/llama.cpp/0001-vulkan-adreno-750-matvec-shared-memory-reduction.patch @@ -0,0 +1,22 @@ +diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp +index 5587dfc..b7074ad 100644 +--- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp ++++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp +@@ -2897,5 +2897,16 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) { + uint32_t rm_iq = 2 * rm_kq; + +- const bool use_subgroups = device->subgroup_arithmetic; ++ bool use_subgroups = device->subgroup_arithmetic; ++#if defined(__ANDROID__) ++ // Carried by llamadart-native (leehack/llamadart-native#79, ggml-org/llama.cpp#29165): ++ // this Adreno 750 driver's shader compiler crashes in vkCreateComputePipelines on the ++ // subgroup-reduction dequant mul_mat_vec shaders; fall back to shared-memory reduction. ++ if (device->properties.vendorID == 0x5143u && ++ device->driver_id == vk::DriverId::eQualcommProprietary && ++ device->properties.driverVersion == 2150604839u && ++ strcmp(device->properties.deviceName.data(), "Adreno (TM) 750") == 0) { ++ use_subgroups = false; ++ } ++#endif + // The Imagination proprietary compiler rejects the subgroup-only dequant mul_mat_vec + // shaders that require a subgroup size >= 16; fall back to shared-memory reduction. diff --git a/patches/llama.cpp/series.json b/patches/llama.cpp/series.json index 7fdf07f8..9569a9be 100644 --- a/patches/llama.cpp/series.json +++ b/patches/llama.cpp/series.json @@ -1,3 +1,12 @@ { - "patches": [] + "patches": [ + { + "file": "0001-vulkan-adreno-750-matvec-shared-memory-reduction.patch", + "tracking": "https://github.com/leehack/llamadart-native/issues/79", + "upstream": "https://github.com/ggml-org/llama.cpp/pull/29165", + "android_markers": [ + {"library": "libggml-vulkan.so", "text": "Adreno (TM) 750"} + ] + } + ] } From 1342194125857d4856568fa542a9eefb2538be54 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 09:01:19 -0400 Subject: [PATCH 3/5] fix: skip buffer device addresses on a Vulkan device without vkGetBufferDeviceAddress On a Galaxy A53 (Mali-G68) loading a model on Vulkan ended the process with a call of a null pointer from ggml_vk_create_buffer. ggml-vulkan requires Vulkan 1.2 of the loader only, reads bufferDeviceAddress from a VkPhysicalDeviceVulkan12Features that it does not initialize and that a driver below 1.2 does not fill in (ggml-vulkan.cpp:4313 and 4518 at d81235049), and then calls the core 1.2 function through a dispatcher that was never initialized from the device (ggml-vulkan-buffers.cpp:177). Patch 0002 asks the created device for vkGetBufferDeviceAddress and clears buffer_device_address when it has none, so ggml takes the path of a device without the feature. Whether the A53's driver is below 1.2 is not known, and no device has run the patch. Refs leehack/llamadart#782 --- docs/v060_2_wrapper_rebuild.md | 57 +++++++++++++++++++ ...an-buffer-device-address-entry-point.patch | 18 ++++++ patches/llama.cpp/README.md | 5 +- patches/llama.cpp/series.json | 8 +++ 4 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 patches/llama.cpp/0002-vulkan-buffer-device-address-entry-point.patch diff --git a/docs/v060_2_wrapper_rebuild.md b/docs/v060_2_wrapper_rebuild.md index 64bab7da..07a15351 100644 --- a/docs/v060_2_wrapper_rebuild.md +++ b/docs/v060_2_wrapper_rebuild.md @@ -88,6 +88,63 @@ What the patch does not fix, on this driver: Remove the patch when the pinned upstream has an equivalent change, or when the S24 run passes without it. +## Null `vkGetBufferDeviceAddress` + +Issue: [llamadart#782](https://github.com/leehack/llamadart/issues/782). +Patch: `0002-vulkan-buffer-device-address-entry-point.patch`. + +On a Galaxy A53 5G (`SC-53C`, Mali-G68, Android 16) loading a model on Vulkan +ends the process: `SIGSEGV` at `pc 0` called from `libggml-vulkan.so`, under +`ggml_backend_alloc_ctx_tensors_from_buft` and +`llama_model_base::load_tensors`, with native `v0.5.0-2`. + +Root cause at `d81235049`, `ggml/src/ggml-vulkan/`: + +- `ggml_vk_instance_init` requires Vulkan 1.2 only of the loader + (`vk::enumerateInstanceVersion`, `ggml-vulkan.cpp` lines 5192 to 5197). + Nothing compares the `apiVersion` of the device. +- `ggml_vk_get_device` declares `VkPhysicalDeviceVulkan11Features` and + `VkPhysicalDeviceVulkan12Features` without initializing their members (lines + 4308 to 4316), passes them to `vkGetPhysicalDeviceFeatures2` (line 4475) and + takes `buffer_device_address` from `vk12_features.bufferDeviceAddress` (line + 4518). A driver below Vulkan 1.2 does not know these structures and writes + nothing, so the value is what the stack held. +- `ggml_vk_create_buffer` then calls `getBufferAddress`, the core 1.2 + `vkGetBufferDeviceAddress` (`ggml-vulkan-buffers.cpp` lines 175 to 177), + through a Vulkan-Hpp dispatcher that is initialized from the instance (lines + 5190 and 5270 of `ggml-vulkan.cpp`) and never from the device. A device + without the function makes that a call of a null pointer. + +Upstream `master` at `609290be6` (2026-10-09) has the same code, and no +upstream issue or pull request names it. + +The patch asks the created device for the function +(`vkGetDeviceProcAddr(device, "vkGetBufferDeviceAddress")`, after +`createDevice` at line 4769) and clears `buffer_device_address`, with a +warning, when there is none. ggml then creates buffers without +`eShaderDeviceAddress` and uses the im2col shaders without device addresses, +as on any device that lacks the feature. + +Not known: whether the A53's driver reports itself below Vulkan 1.2. The run +that crashed recorded no Vulkan version. A driver at 1.2 or later that +reports the feature without the function would crash the same way, and the +patch covers both because it tests the function and not the version. + +What the patch does not fix: on a device below Vulkan 1.2 the other members +read from the two structures stay indeterminate (`shaderFloat16`, +`storageBuffer16BitAccess`, `vulkanMemoryModel`), so ggml-vulkan still needs +Vulkan 1.2 from the driver. `llamadart` refuses such a device before a load +from the `api_version` of the `v0.6.0-1` device facts, and then never reaches +this code. The patch is for a driver at 1.2 or later without the function and +for a caller that does not check. + +No device has run the patch. That the device answers null follows from the +trace and from the issue's note that initializing the dispatcher from the +device did not help in stable-diffusion.cpp's copy of this code. + +Remove the patch when the pinned upstream checks the device's API version or +the function before it uses buffer device addresses. + ## Checks ```bash diff --git a/patches/llama.cpp/0002-vulkan-buffer-device-address-entry-point.patch b/patches/llama.cpp/0002-vulkan-buffer-device-address-entry-point.patch new file mode 100644 index 00000000..ed627fb5 --- /dev/null +++ b/patches/llama.cpp/0002-vulkan-buffer-device-address-entry-point.patch @@ -0,0 +1,18 @@ +diff --git a/ggml/src/ggml-vulkan/ggml-vulkan.cpp b/ggml/src/ggml-vulkan/ggml-vulkan.cpp +index 5587dfc..bca8a3c 100644 +--- a/ggml/src/ggml-vulkan/ggml-vulkan.cpp ++++ b/ggml/src/ggml-vulkan/ggml-vulkan.cpp +@@ -4769,4 +4769,13 @@ vk_device ggml_vk_get_device(size_t idx) { + device->device = device->physical_device.createDevice(device_create_info); + ++ // Carried by llamadart-native (leehack/llamadart#782): a driver below Vulkan 1.2 has no ++ // core vkGetBufferDeviceAddress, whatever VkPhysicalDeviceVulkan12Features reads as. ++ if (device->buffer_device_address && ++ vkGetDeviceProcAddr(device->device, "vkGetBufferDeviceAddress") == nullptr) { ++ GGML_LOG_WARN("ggml_vulkan: %s has no vkGetBufferDeviceAddress, not using buffer device addresses\n", ++ device->properties.deviceName.data()); ++ device->buffer_device_address = false; ++ } ++ + if (device->device_fault) { + device->pfn_vkGetDeviceFaultInfoEXT = (PFN_vkGetDeviceFaultInfoEXT) diff --git a/patches/llama.cpp/README.md b/patches/llama.cpp/README.md index f4aff8c4..2defcd43 100644 --- a/patches/llama.cpp/README.md +++ b/patches/llama.cpp/README.md @@ -18,8 +18,9 @@ these hold: - `series.json` lists the patches in the order they apply. Each entry has the patch `file`, the `tracking` issue, the `upstream` pull request or issue to - watch, and optional `android_markers`: a `library` of the Android bundle and - a `text` that only the patched source compiles into it. + watch (a permalink to the upstream lines when there is none), and optional + `android_markers`: a `library` of the Android bundle and a `text` that only + the patched source compiles into it. - `NNNN-short-name.patch` is a unified diff (`git diff -U2` inside `third_party/llama.cpp`) of one existing `.c`, `.cpp`, `.m` or `.mm` file. A patch cannot add a file or edit a header: only a source that an upstream diff --git a/patches/llama.cpp/series.json b/patches/llama.cpp/series.json index 9569a9be..d6f12681 100644 --- a/patches/llama.cpp/series.json +++ b/patches/llama.cpp/series.json @@ -7,6 +7,14 @@ "android_markers": [ {"library": "libggml-vulkan.so", "text": "Adreno (TM) 750"} ] + }, + { + "file": "0002-vulkan-buffer-device-address-entry-point.patch", + "tracking": "https://github.com/leehack/llamadart/issues/782", + "upstream": "https://github.com/ggml-org/llama.cpp/blob/d81235049384534c167caea52b85a694f6103d14/ggml/src/ggml-vulkan/ggml-vulkan-buffers.cpp#L175-L177", + "android_markers": [ + {"library": "libggml-vulkan.so", "text": "has no vkGetBufferDeviceAddress"} + ] } ] } From bf07bc1eb1aaa6af0415be51884e460c5ce813e0 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 09:02:27 -0400 Subject: [PATCH 4/5] docs: list the device runs the v0.6.0-2 patches still need Refs #79, leehack/llamadart#782 --- docs/v060_2_wrapper_rebuild.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/v060_2_wrapper_rebuild.md b/docs/v060_2_wrapper_rebuild.md index 07a15351..a365e944 100644 --- a/docs/v060_2_wrapper_rebuild.md +++ b/docs/v060_2_wrapper_rebuild.md @@ -145,6 +145,19 @@ device did not help in stable-diffusion.cpp's copy of this code. Remove the patch when the pinned upstream checks the device's API version or the function before it uses buffer device addresses. +## Device runs owed before release + +No lane runs ggml-vulkan on a device, and both patches change behavior only on +the affected drivers. Before `llamadart` ships with `v0.6.0-2`, on the bundle +of that tag or of a non-publishing run of the release workflow, Vulkan load +and generation compared with CPU output on the same device: + +| Device | Shows | +| --- | --- | +| Galaxy S24 `SC-51E`, Adreno 750, API 36 | stories15M F32 and Qwen3.5-0.8B Q4_0 generate without the crash and equal CPU, this time on llama.cpp `v0.6.0` and through `llamadart` | +| Galaxy A53 `SC-53C`, Mali-G68, API 36 | the device's Vulkan API version; then a typed refusal or CPU fallback from `llamadart` (below 1.2), or Vulkan output equal to CPU with the warning of patch 0002 in the log (1.2 or later) | +| Pixel 9 Pro `caiman`, Mali-G715 ([llamadart#948](https://github.com/leehack/llamadart/issues/948)) | no change from `v0.6.0-1`: neither patch applies to this driver | + ## Checks ```bash From 11807b76a335909565a5d684e7a7476e65474ffb Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Fri, 9 Oct 2026 09:11:44 -0400 Subject: [PATCH 5/5] build: skip a patch that does not fit the llama.cpp being built validate_wrapper.yml builds older upstream commits for qualification, and patch 0001 does not fit the post-v0.4.0 one, so applying the whole series or failing broke every lane on that commit. A patch that does not fit is now skipped with a CMake warning. What keeps a release from losing a patch is the check on the built Android bundle, which does not depend on how the build went, so every patch must name a marker. apply --strict fails where the build skips. Refs #79 --- cmake/llama_cpp_patches.cmake | 8 ++- docs/release_version_policy.md | 7 ++- docs/v060_2_wrapper_rebuild.md | 17 +++--- patches/llama.cpp/README.md | 36 ++++++++---- scripts/generate_assets_manifest.sh | 4 +- tests/test_llama_cpp_patches.py | 40 +++++++++++--- tools/llama_cpp_patches.py | 85 ++++++++++++++++++++--------- 7 files changed, 137 insertions(+), 60 deletions(-) diff --git a/cmake/llama_cpp_patches.cmake b/cmake/llama_cpp_patches.cmake index ccd33bae..fcc1835f 100644 --- a/cmake/llama_cpp_patches.cmake +++ b/cmake/llama_cpp_patches.cmake @@ -23,8 +23,9 @@ function(llamadart_apply_llama_cpp_patches) "${CMAKE_CURRENT_SOURCE_DIR}/tools/llama_cpp_patches.py") find_package(Python3 COMPONENTS Interpreter REQUIRED) - # Every configuration applies the whole series, also one that builds none - # of the patched sources, so a patch that no longer applies fails them all. + # A patch that does not fit this llama.cpp is skipped: lanes here build + # other upstream commits than the pinned one. What keeps a release from + # losing a patch is tools/validate_android_artifacts.py on the bundle. execute_process( COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tools/llama_cpp_patches.py" @@ -37,6 +38,9 @@ function(llamadart_apply_llama_cpp_patches) if (NOT result EQUAL 0) message(FATAL_ERROR "Could not apply patches/llama.cpp:\n${error}") endif() + if (error) + message(WARNING "patches/llama.cpp does not fit this llama.cpp:\n${error}") + endif() if (NOT patched_sources) return() endif() diff --git a/docs/release_version_policy.md b/docs/release_version_policy.md index c7c95834..3e3dc002 100644 --- a/docs/release_version_policy.md +++ b/docs/release_version_policy.md @@ -120,9 +120,10 @@ valid. New manifests and release notes also bind the caller correlation ID, smoke policy/conclusion, exact workflow run, and workflow head SHA. Every release is built with the llama.cpp patches its native commit carries -(`patches/llama.cpp/README.md`): each build applies all of them or fails. -`llama_cpp_patches` in `assets.json` lists the `file`, `sha256` and `tracking` -issue of each one and is an empty list for unmodified upstream source. +(`patches/llama.cpp/README.md`): the Android artifact validation fails a +release whose bundle lacks one. `llama_cpp_patches` in `assets.json` lists the +`file`, `sha256` and `tracking` issue of each one and is an empty list for +unmodified upstream source. `llama_cpp_commit` stays the upstream commit the patches apply to: with a non-empty `llama_cpp_patches` the artifacts are that commit plus exactly those patches, and a comparison against upstream `llama.cpp` at the same commit must diff --git a/docs/v060_2_wrapper_rebuild.md b/docs/v060_2_wrapper_rebuild.md index a365e944..c31573d9 100644 --- a/docs/v060_2_wrapper_rebuild.md +++ b/docs/v060_2_wrapper_rebuild.md @@ -18,12 +18,15 @@ the procedure. In short: already add sources to upstream targets from this repository's CMake; this replaces one. - A hunk applies only where its context and removed lines occur exactly once. - Every configuration applies every patch, so a patch that upstream has - outgrown fails every lane, including the automatic stable release. + A patch that does not fit the llama.cpp being built is skipped with a CMake + warning, because the qualification lanes build older upstream commits: + patch 0001 does not fit the `post-v0.4.0` commit. +- `tools/validate_android_artifacts.py` fails an Android bundle in which a + library lacks the text that a patch compiles into it. The release runs it, + so a release, the automatic stable one included, cannot lose a patch that + upstream has outgrown: it fails until the patch is refreshed or deleted. - `assets.json` gains `llama_cpp_patches`, the `file`, `sha256` and `tracking` issue of each patch, and `[]` for a release without any. -- `tools/validate_android_artifacts.py` fails an Android bundle in which a - library lacks the text that a patch compiles into it. A consumer that compares against upstream `llama.cpp` at `llama_cpp_commit` (`docs/parity_tools.md`) compares against unpatched source. The patches of @@ -172,8 +175,8 @@ ctest --test-dir build/v060 --output-on-failure ``` `tests/test_llama_cpp_patches.py` covers the patch tool on its own sources and, -with the submodule checked out, applies the carried series to it. The +with the submodule checked out, requires the carried series to fit it. The `android-vulkan-shaders` lane of `validate_wrapper.yml` compiles the patched `ggml-vulkan.cpp` with the release NDK against the pinned, `v0.5.0` and -`v0.6.0` upstreams and, on the pinned one, validates the bundle. No lane runs -ggml-vulkan on a device. +`v0.6.0` upstreams, which both patches fit, and on the pinned one validates +the bundle, markers included. No lane runs ggml-vulkan on a device. diff --git a/patches/llama.cpp/README.md b/patches/llama.cpp/README.md index 2defcd43..40c0550d 100644 --- a/patches/llama.cpp/README.md +++ b/patches/llama.cpp/README.md @@ -18,7 +18,7 @@ these hold: - `series.json` lists the patches in the order they apply. Each entry has the patch `file`, the `tracking` issue, the `upstream` pull request or issue to - watch (a permalink to the upstream lines when there is none), and optional + watch (a permalink to the upstream lines when there is none), and `android_markers`: a `library` of the Android bundle and a `text` that only the patched source compiles into it. - `NNNN-short-name.patch` is a unified diff (`git diff -U2` inside @@ -31,23 +31,37 @@ these hold: `cmake/llama_cpp_patches.cmake` runs `tools/llama_cpp_patches.py` while CMake configures. It writes the patched copy of each source to `/llama.cpp-patched/` and makes the upstream target compile that copy -instead of the original. Every build of this repository does this, on every -platform, including one that compiles none of the patched sources. +instead of the original. A hunk applies only where its context and removed lines occur exactly once in -the upstream file. There is no fuzz. When upstream changes those lines the -configure step fails and names the patch: check whether upstream fixed the -defect, then refresh the patch against the new source or delete it. The -automatic stable release fails the same way until that is done, which is -intended: a release must not silently lose a fix. +the upstream file. There is no fuzz. A patch that does not fit the llama.cpp +being built is skipped whole with a CMake warning that names it, and the build +goes on: `validate_wrapper.yml` builds older upstream commits for +qualification, and those must keep building. + +## What keeps a release from losing a patch + +`tools/validate_android_artifacts.py` fails an Android bundle in which a +library lacks the `text` of an `android_markers` entry. It reads the built +library, so it does not matter why the patch is missing. The release runs it +on every Android bundle and `validate_wrapper.yml` on the pinned upstream, so +a patch that upstream has outgrown fails the pull request that moves the +upstream, or the release, the automatic stable release included. Check then +whether upstream fixed the defect, and refresh the patch or delete it. + +For that reason every patch must have at least one marker, and so must change +a source that an Android library is built from. A patch fits the same +upstream source on every platform or on none, so a release whose Android +bundle has every marker has every patch on its other platforms too. + +`python3 tools/llama_cpp_patches.py apply --strict --upstream +third_party/llama.cpp --output ` fails where the build would skip. ## What a release records `assets.json` has `llama_cpp_patches`: the `file`, `sha256` and `tracking` of every patch, an empty list when there is none. `llama_cpp_commit` remains the -upstream commit the patches apply to. `tools/validate_android_artifacts.py` -fails an Android bundle whose library lacks the text of an `android_markers` -entry. +upstream commit the patches apply to. ## Adding, refreshing or removing a patch diff --git a/scripts/generate_assets_manifest.sh b/scripts/generate_assets_manifest.sh index bcfa1a89..313e732e 100755 --- a/scripts/generate_assets_manifest.sh +++ b/scripts/generate_assets_manifest.sh @@ -76,8 +76,8 @@ timestamp="$(date -u +"%Y-%m-%dT%H:%M:%SZ")" llama_cpp_tag="${LLAMADART_LLAMA_CPP_TAG:-$tag}" llama_cpp_commit="${LLAMADART_LLAMA_CPP_COMMIT:-}" native_commit="${LLAMADART_NATIVE_COMMIT:-}" -# The llama.cpp patches this checkout carries: every build of it applies all of -# them or fails, so the release carries exactly these. +# The llama.cpp patches this checkout carries. The Android artifact validation +# fails a release whose bundle lacks one of them. repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" llama_cpp_patches="$(python3 "$repo_root/tools/llama_cpp_patches.py" manifest)" correlation_id="${LLAMADART_CORRELATION_ID:-}" diff --git a/tests/test_llama_cpp_patches.py b/tests/test_llama_cpp_patches.py index 9034dfff..0e4527be 100644 --- a/tests/test_llama_cpp_patches.py +++ b/tests/test_llama_cpp_patches.py @@ -56,6 +56,7 @@ def __init__(self, directory: str, named_patches: dict[str, str]) -> None: "file": file, "tracking": "https://example.invalid/issue", "upstream": "https://example.invalid/pull", + "android_markers": [{"library": "libthing.so", "text": "marker " + file}], }) self.write_series() @@ -95,15 +96,22 @@ def test_a_crlf_checkout_applies_like_an_lf_one(self) -> None: self.assertEqual("int a = 1;\nint b = 20;\nint b2 = 21;\nint c = 3;\nint d = 4;\n", fixture.apply()[SOURCE]) - def test_upstream_drift_fails_instead_of_applying_elsewhere(self) -> None: - fixture = self.fixture(**{"0001_edit_b": EDIT_B}) + def test_a_patch_that_does_not_fit_is_skipped_whole_and_never_applied_elsewhere(self) -> None: + fixture = self.fixture(**{"0001_edit_b": EDIT_B, "0002_edit_d": EDIT_D}) (fixture.upstream / SOURCE).write_text( - ORIGINAL.replace("int c = 3;", "int c = 30;"), encoding="utf-8") + ORIGINAL.replace("int a = 1;", "int a = 10;"), encoding="utf-8") + patched, skipped = patches.apply_available(fixture.upstream, fixture.patches) + self.assertEqual({SOURCE: "int a = 10;\nint b = 2;\nint c = 3;\nint d = 40;\n"}, patched) + self.assertEqual(1, len(skipped), skipped) + self.assertIn("0001-edit-b.patch", skipped[0]) + self.assertIn("matches src/thing.cpp 0 times, expected 1", skipped[0]) self.assert_rejected(fixture, "matches src/thing.cpp 0 times, expected 1") - def test_an_ambiguous_hunk_fails(self) -> None: + def test_an_ambiguous_hunk_does_not_fit(self) -> None: fixture = self.fixture(**{"0001_edit_b": EDIT_B}) (fixture.upstream / SOURCE).write_text(ORIGINAL + ORIGINAL, encoding="utf-8") + self.assertEqual(({}, 1), (lambda result: (result[0], len(result[1])))( + patches.apply_available(fixture.upstream, fixture.patches))) self.assert_rejected(fixture, "matches src/thing.cpp 2 times, expected 1") def test_only_an_existing_compiled_source_can_be_patched(self) -> None: @@ -136,10 +144,15 @@ def test_the_series_and_the_directory_must_agree(self) -> None: fixture.series = [dict(fixture.series[0], upstream="https://example.invalid", note="x")] fixture.write_series() self.assert_rejected(fixture, "unknown keys ['note']") + fixture.series = [dict(fixture.series[0], upstream="https://example.invalid")] + del fixture.series[0]["note"] + del fixture.series[0]["android_markers"] + fixture.write_series() + self.assert_rejected(fixture, '"android_markers" must list at least one') def test_an_unchanged_copy_keeps_its_timestamp(self) -> None: fixture = self.fixture(**{"0001_edit_b": EDIT_B}) - self.assertEqual([SOURCE], + self.assertEqual(([SOURCE], []), patches.write_patched(fixture.upstream, fixture.output, fixture.patches)) copy = fixture.output / SOURCE os.utime(copy, (1, 1)) @@ -151,23 +164,32 @@ def test_an_unchanged_copy_keeps_its_timestamp(self) -> None: self.assertNotEqual(1, copy.stat().st_mtime) self.assertIn("int b2 = 22;", copy.read_text(encoding="utf-8")) - def test_the_tool_prints_what_cmake_reads_and_fails_with_the_reason(self) -> None: + def test_the_tool_prints_what_cmake_reads_and_names_a_skipped_patch(self) -> None: fixture = self.fixture(**{"0001_edit_b": EDIT_B}) command = [sys.executable, str(ROOT / "tools/llama_cpp_patches.py"), "--patches", str(fixture.patches), "apply", "--upstream", str(fixture.upstream), "--output", str(fixture.output)] result = subprocess.run(command, capture_output=True, text=True) - self.assertEqual((0, SOURCE + "\n"), (result.returncode, result.stdout)) + self.assertEqual((0, SOURCE + "\n", ""), + (result.returncode, result.stdout, result.stderr)) (fixture.upstream / SOURCE).write_text("int z;\n", encoding="utf-8") result = subprocess.run(command, capture_output=True, text=True) + self.assertEqual((0, "\n"), (result.returncode, result.stdout)) + self.assertIn("skipped 0001-edit-b.patch", result.stderr) + result = subprocess.run(command + ["--strict"], capture_output=True, text=True) self.assertEqual(1, result.returncode) self.assertIn("0001-edit-b.patch", result.stderr) - self.assertIn("re-qualify the patch", result.stderr) + fixture.series[0]["tracking"] = "none" + fixture.write_series() + result = subprocess.run(command, capture_output=True, text=True) + self.assertEqual(1, result.returncode, "a malformed series is never skipped") def test_a_bundle_library_without_its_marker_is_reported(self) -> None: fixture = self.fixture(**{"0001_edit_b": EDIT_B}) fixture.series[0]["android_markers"] = [{"library": "libthing.so", "text": "b2 marker"}] fixture.write_series() + # The check reads the bundle only, so it also catches a patch that the + # build skipped. bundle = fixture.output bundle.mkdir() self.assertEqual([], patches.android_marker_errors(bundle, fixture.patches)) @@ -208,7 +230,7 @@ def test_the_series_applies_to_the_checked_out_llama_cpp(self) -> None: path = patches.parse_patch(entry["file"], (patches.PATCHES_DIR / entry["file"]) .read_text(encoding="utf-8")).path original = (UPSTREAM / path).read_text(encoding="utf-8") - for marker in entry.get("android_markers", []): + for marker in entry["android_markers"]: # A marker tells a patched library from an unpatched one only # if the patch is what introduces it. self.assertNotIn(marker["text"], original, entry["file"]) diff --git a/tools/llama_cpp_patches.py b/tools/llama_cpp_patches.py index 2d5fea67..247c11a5 100644 --- a/tools/llama_cpp_patches.py +++ b/tools/llama_cpp_patches.py @@ -26,6 +26,10 @@ class PatchError(Exception): pass +class NotApplicable(PatchError): + """The patch is well formed but does not fit this upstream source.""" + + @dataclass(frozen=True) class Hunk: header: str @@ -68,15 +72,18 @@ def load_series(patches_dir: Path = PATCHES_DIR) -> list[dict]: for key in ("tracking", "upstream"): if not str(entry.get(key, "")).startswith("https://"): raise PatchError(f"{series_path}: {name}: \"{key}\" must be an https URL") - markers = entry.get("android_markers", []) - if not isinstance(markers, list) or not all( + # The artifact check is what keeps a release from losing a patch, so + # every patch must give it something to find. + markers = entry.get("android_markers") + if not isinstance(markers, list) or not markers or not all( isinstance(marker, dict) and set(marker) == MARKER_KEYS and all(isinstance(value, str) and value for value in marker.values()) for marker in markers ): raise PatchError( - f"{series_path}: {name}: \"android_markers\" must list {{library, text}}" + f"{series_path}: {name}: \"android_markers\" must list at least one " + "{library, text}" ) names.append(name) if names != sorted(set(names)): @@ -145,32 +152,46 @@ def close_hunk() -> None: return Patch(name, paths[0], tuple(hunks)) -def apply_series(upstream: Path, patches_dir: Path = PATCHES_DIR) -> dict[str, str]: - """Returns the patched text of every upstream source the series edits. +def apply_available( + upstream: Path, patches_dir: Path = PATCHES_DIR +) -> tuple[dict[str, str], list[str]]: + """Returns the patched text of each edited source, and why a patch was skipped. A hunk applies only where its context and removed lines occur exactly - once: there is no fuzz and no offset search, so upstream drift fails. + once: there is no fuzz and no offset search. A patch that does not fit + this upstream is skipped whole. """ patched: dict[str, str] = {} + skipped: list[str] = [] for entry in load_series(patches_dir): name = entry["file"] patch = parse_patch(name, _read_text(patches_dir / name)) - if patch.path not in patched: - source = upstream / patch.path - if not source.is_file(): - raise PatchError(f"{name}: {source} does not exist") - patched[patch.path] = _read_text(source) - text = patched[patch.path] - for hunk in patch.hunks: - count = text.count(hunk.before) - if count != 1: - raise PatchError( - f"{name}: {hunk.header} matches {patch.path} {count} times, expected 1. " - "Upstream changed these lines: re-qualify the patch for this llama.cpp " - "or remove it (patches/llama.cpp/README.md)." - ) - text = text.replace(hunk.before, hunk.after) + try: + text = patched.get(patch.path) + if text is None: + source = upstream / patch.path + if not source.is_file(): + raise NotApplicable(f"{name}: {source} does not exist") + text = _read_text(source) + for hunk in patch.hunks: + count = text.count(hunk.before) + if count != 1: + raise NotApplicable( + f"{name}: {hunk.header} matches {patch.path} {count} times, expected 1" + ) + text = text.replace(hunk.before, hunk.after) + except NotApplicable as error: + skipped.append(str(error)) + continue patched[patch.path] = text + return patched, skipped + + +def apply_series(upstream: Path, patches_dir: Path = PATCHES_DIR) -> dict[str, str]: + """Like apply_available, but a patch that does not fit is an error.""" + patched, skipped = apply_available(upstream, patches_dir) + if skipped: + raise NotApplicable("\n".join(skipped)) return patched @@ -190,7 +211,7 @@ def android_marker_errors(out_dir: Path, patches_dir: Path = PATCHES_DIR) -> lis """Names each bundled library that lacks the text a carried patch compiles in.""" errors: list[str] = [] for entry in load_series(patches_dir): - for marker in entry.get("android_markers", []): + for marker in entry["android_markers"]: library = out_dir / marker["library"] if library.is_file() and marker["text"].encode() not in library.read_bytes(): errors.append( @@ -200,8 +221,14 @@ def android_marker_errors(out_dir: Path, patches_dir: Path = PATCHES_DIR) -> lis return errors -def write_patched(upstream: Path, output: Path, patches_dir: Path) -> list[str]: - patched = apply_series(upstream, patches_dir) +def write_patched( + upstream: Path, output: Path, patches_dir: Path, strict: bool = False +) -> tuple[list[str], list[str]]: + """Writes the patched copies; returns their paths and the skipped patches.""" + if strict: + patched, skipped = apply_series(upstream, patches_dir), [] + else: + patched, skipped = apply_available(upstream, patches_dir) for relative, text in patched.items(): target = output / relative # Keep the timestamp of an unchanged copy so reconfiguring rebuilds nothing. @@ -210,7 +237,7 @@ def write_patched(upstream: Path, output: Path, patches_dir: Path) -> list[str]: target.parent.mkdir(parents=True, exist_ok=True) with target.open("w", encoding="utf-8", newline="\n") as handle: handle.write(text) - return sorted(patched) + return sorted(patched), skipped def main() -> int: @@ -220,11 +247,17 @@ def main() -> int: apply = commands.add_parser("apply", help="write patched copies and print their paths") apply.add_argument("--upstream", type=Path, required=True) apply.add_argument("--output", type=Path, required=True) + apply.add_argument("--strict", action="store_true", + help="fail when a patch does not apply instead of skipping it") commands.add_parser("manifest", help="print the carried patches as JSON") args = parser.parse_args() try: if args.command == "apply": - print(";".join(write_patched(args.upstream, args.output, args.patches))) + paths, skipped = write_patched( + args.upstream, args.output, args.patches, args.strict) + for reason in skipped: + print(f"skipped {reason}", file=sys.stderr) + print(";".join(paths)) else: print(json.dumps(manifest_entries(args.patches))) except PatchError as error: