diff --git a/.github/workflows/validate_wrapper.yml b/.github/workflows/validate_wrapper.yml index dffe9149..e5e3f3a6 100644 --- a/.github/workflows/validate_wrapper.yml +++ b/.github/workflows/validate_wrapper.yml @@ -386,6 +386,7 @@ jobs: llamadart_tts_api_test llamadart_tts_eval_test llamadart_mtmd_compat_test + llamadart_image_token_limit_test llamadart_barrier_test llamadart_vulkan_device_info_test llamadart_exit_teardown_test @@ -406,6 +407,14 @@ jobs: --format nm --tool nm build/wrapper-contract/libllamadart.so + # The release archives get the same check from + # validate_linux_artifact.py. + - name: Check that no library registers static destructors with the C library + run: | + for library in build/wrapper-contract/libllamadart.so build/wrapper-contract/bin/*.so; do + python3 tools/validate_exports.py --format readelf --tool readelf \ + --imports-only --forbid-import __cxa_atexit "$library" + done msvc-mtmd-link-contract: needs: changes @@ -465,13 +474,14 @@ jobs: llamadart_exit_teardown_test llamadart_vulkan_device_info_test llamadart_tts_api_test + llamadart_image_token_limit_test - name: Run the barrier and Vulkan probe tests shell: pwsh run: | $wrapperDir = (Resolve-Path build/wx64).Path $upstreamDir = (Resolve-Path build/wx64/bin).Path $env:PATH = "$wrapperDir;$upstreamDir;$env:PATH" - ctest --test-dir build/wx64 -R "barrier|vocabulary|vulkan_device_info|tts_api" --timeout 120 --output-on-failure + ctest --test-dir build/wx64 -R "barrier|vocabulary|vulkan_device_info|tts_api|image_token_limit" --timeout 120 --output-on-failure - name: Validate wrapper exports shell: pwsh run: | @@ -525,7 +535,9 @@ jobs: -DGGML_CCACHE=OFF -DLLAMADART_BUILD_TESTS=ON - name: Build the exit teardown test - run: cmake --build ${{ matrix.build_dir }} --target llamadart_exit_teardown_test + run: >- + cmake --build ${{ matrix.build_dir }} --target + llamadart_exit_teardown_test llamadart_image_token_limit_test - name: Validate wrapper exports and the static destructor binding run: >- python3 tools/validate_exports.py --format nm --tool nm @@ -536,7 +548,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 exit_teardown + ctest --test-dir ${{ matrix.build_dir }} -R "exit_teardown|image_token_limit" --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/AGENTS.md b/AGENTS.md index fbbb24b6..44b9a82d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,11 @@ 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. +See its Linux host shutdown section for what C `exit()` does from +`v0.6.0-2`, and why the llama.cpp libraries register no static destructors +there. - `.github/workflows/native_release.yml` - Exact native build + release workflow, used by manual dispatch and the @@ -62,6 +67,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..059edee5 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() @@ -188,9 +190,42 @@ endif() llamadart_attach_android_cpu_backend_score(ggml-cpu) +# Adds src/llama_dart_static_destructors.c to every shared library and backend +# module that llama.cpp builds, whatever backends are enabled. libllamadart +# gets it below. +function(llamadart_drop_static_destructors directory) + get_property(target_names DIRECTORY "${directory}" PROPERTY BUILDSYSTEM_TARGETS) + foreach(target_name IN LISTS target_names) + get_target_property(target_type ${target_name} TYPE) + if (target_type STREQUAL "SHARED_LIBRARY" OR target_type STREQUAL "MODULE_LIBRARY") + target_sources(${target_name} PRIVATE + $) + endif() + endforeach() + get_property(subdirectories DIRECTORY "${directory}" PROPERTY SUBDIRECTORIES) + foreach(subdirectory IN LISTS subdirectories) + llamadart_drop_static_destructors("${subdirectory}") + endforeach() +endfunction() + +if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_library(llamadart_static_destructors OBJECT + "src/llama_dart_static_destructors.c") + llamadart_drop_static_destructors( + "${CMAKE_CURRENT_SOURCE_DIR}/third_party/llama.cpp") +endif() + add_library(llamadart_lib SHARED "src/llama_dart_wrapper.cpp" + "src/llama_dart_image_token_limit.cpp" "src/llama_dart_vulkan_device_info.cpp") +if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + target_sources(llamadart_lib PRIVATE + $) + # Held objects and native finalizer callbacks may outlive a dlclose. + # Retain the wrapper together with the owned statics. + target_link_options(llamadart_lib PRIVATE -Wl,-z,nodelete) +endif() # The Vulkan device facts need only the Vulkan types: the loader is opened at # run time, so libllamadart links no Vulkan library and loads without one. set(LLAMADART_VULKAN_HEADERS_INCLUDE @@ -267,6 +302,13 @@ if (LLAMADART_BUILD_TESTS) RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin") add_test(NAME llamadart_tts_eval_test COMMAND llamadart_tts_eval_test) + add_executable(llamadart_image_token_limit_test tests/image_token_limit_test.cpp) + target_compile_features(llamadart_image_token_limit_test PRIVATE cxx_std_17) + target_include_directories(llamadart_image_token_limit_test PRIVATE + src third_party/llama.cpp/include third_party/llama.cpp/tools/mtmd) + target_link_libraries(llamadart_image_token_limit_test PRIVATE llamadart_lib ggml-base) + add_test(NAME llamadart_image_token_limit_test COMMAND llamadart_image_token_limit_test) + add_executable(llamadart_mtmd_compat_test tests/mtmd_compat_test.cpp) target_compile_features(llamadart_mtmd_compat_test PRIVATE cxx_std_17) target_include_directories(llamadart_mtmd_compat_test PRIVATE src) @@ -306,8 +348,8 @@ if (LLAMADART_BUILD_TESTS) src ) foreach(scenario dispose order repeat in-flight nested settle timeout - idle-wait own-call blocked exit late-static free-in-flight - free-timeout barrier-free barrier-free-idle) + idle-wait own-call blocked exit exit-in-flight late-static + free-in-flight free-timeout barrier-free barrier-free-idle) add_test(NAME llamadart_exit_teardown_${scenario} COMMAND llamadart_exit_teardown_test ${scenario}) endforeach() @@ -325,14 +367,19 @@ if (LLAMADART_BUILD_TESTS) "${exit_teardown_vocabulary_model}") set_tests_properties(llamadart_exit_teardown_barrier-grammar PROPERTIES FIXTURES_REQUIRED llamadart_exit_teardown_vocabulary_model) - # Teardown runs at exit on Apple only, and only there are the backends part - # of libllamadart, so the scenarios that load a model run there. They use a - # model the test writes itself unless one is given. + # Apple automatic teardown and Linux retained statics are exercised + # with CPU models. They use a model the test writes itself unless one is + # given. On Linux the backends are modules, of which the test loads the + # CPU one. set(LLAMADART_EXIT_TEARDOWN_TEST_MODEL "" CACHE FILEPATH "GGUF model for the exit teardown tests instead of the generated one") set(LLAMADART_EXIT_TEARDOWN_TEST_MMPROJ "" CACHE FILEPATH "GGUF multimodal projector of that model for the mtmd exit teardown tests") - if (APPLE) + if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + target_compile_definitions(llamadart_exit_teardown_test PRIVATE + LLAMADART_TEST_CPU_BACKEND="$") + endif() + if (APPLE OR CMAKE_SYSTEM_NAME STREQUAL "Linux") add_test(NAME llamadart_exit_teardown_graph COMMAND llamadart_exit_teardown_test graph) set(exit_teardown_model "${LLAMADART_EXIT_TEARDOWN_TEST_MODEL}") @@ -356,6 +403,25 @@ if (LLAMADART_BUILD_TESTS) set_tests_properties(llamadart_exit_teardown_${scenario} PROPERTIES FIXTURES_REQUIRED llamadart_exit_teardown_model) endforeach() + # Linux preserves host callbacks and libc flushing. Live-worker raw + # exit cases are diagnostic CPU controls, not the host contract. + if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + foreach(scenario exit-late-calls exit-status) + add_test(NAME llamadart_exit_teardown_${scenario} + COMMAND llamadart_exit_teardown_test ${scenario}) + endforeach() + set_tests_properties(llamadart_exit_teardown_exit-status + PROPERTIES TIMEOUT 10) + foreach(scenario model-unguarded-decode model-exit-idle + model-exit-join-idle model-exit-join-generating) + add_test(NAME llamadart_exit_teardown_${scenario} + COMMAND llamadart_exit_teardown_test ${scenario} + "${exit_teardown_model}") + set_tests_properties(llamadart_exit_teardown_${scenario} + PROPERTIES + FIXTURES_REQUIRED llamadart_exit_teardown_model) + endforeach() + endif() if (LLAMADART_EXIT_TEARDOWN_TEST_MODEL) add_test(NAME llamadart_exit_teardown_model-speculative-process COMMAND llamadart_exit_teardown_test model-speculative-process @@ -393,10 +459,20 @@ if (LLAMADART_BUILD_TESTS) endif() endif() + # The Linux presets give every binary the run path $ORIGIN, which the + # bundle needs, while the build tree keeps the llama.cpp libraries in a + # directory of their own. + if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + get_property(llamadart_tests DIRECTORY PROPERTY TESTS) + set_tests_properties(${llamadart_tests} PROPERTIES + ENVIRONMENT_MODIFICATION + "LD_LIBRARY_PATH=path_list_prepend:$;LD_LIBRARY_PATH=path_list_prepend:$") + endif() + # Contract assertions must execute against optimized Release libraries too. foreach(test_target llamadart_speculative_api_test llamadart_tts_api_test llamadart_tts_eval_test llamadart_exit_teardown_test llamadart_mtmd_compat_test - llamadart_vulkan_device_info_test llamadart_barrier_test) + llamadart_vulkan_device_info_test llamadart_barrier_test llamadart_image_token_limit_test) if (MSVC) target_compile_options(${test_target} PRIVATE /UNDEBUG) else() 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/README.md b/README.md index db72b11b..5673e10e 100644 --- a/README.md +++ b/README.md @@ -175,7 +175,8 @@ Assets are suffixed with platform/arch, for example: - `tools/package_linux_artifact.py`: preserves Linux ELF version files and SONAME symlinks while transporting split CI artifacts. - `tools/validate_linux_artifact.py`: checks Linux archive members, symlinks, - SONAMEs, and local `DT_NEEDED` dependencies. + SONAMEs, and local `DT_NEEDED` dependencies, that no library built here + imports `__cxa_atexit`, and that `libllamadart.so` cannot be unloaded. - `tools/package_apple_xcframework.py`: packages Apple `libllamadart` slices as an SPM-compatible XCFramework zip. - `tools/apple/PrivacyInfo.xcprivacy`: privacy manifest embedded in every @@ -286,15 +287,30 @@ left of it at exit: upstream function is tracked but not freed at exit, so a caller that has not switched to the tracked functions keeps its previous exit behavior. -On other platforms nothing runs at exit; `llama_dart_exit_teardown` runs the -same teardown on request and must be followed directly by `exit`. It is for -native hosts: like `llama_dart_exit_call_begin` and `llama_dart_exit_call_end`, -it is not meant to be bound from Dart. +On Linux, Android excepted, owned bundle statics are retained until the +process is gone (`src/llama_dart_static_destructors.c`). C `exit` runs no +wrapper teardown or forced termination: earlier host callbacks, dependency +destructors and normal libc stream flushing proceed. `-z nodelete` keeps +held native objects and finalizer callbacks valid across `dlclose`. + +Before C exit, the host must stop and join workers and shut down its Dart +isolates or Flutter engine. Await their exit and native finalizers; a kill +request alone is insufficient. Direct C exit with live Dart isolates can +abort the VM even without llama.cpp ([#977](https://github.com/leehack/llamadart/issues/977)). +Owned static retention does not protect GPU-driver or BLAS destructors. + +[`docs/v060_2_wrapper_rebuild.md`](docs/v060_2_wrapper_rebuild.md) describes +the host protocol, preservation regression tests and remaining qualification. + +On other platforms nothing runs at exit. `llama_dart_exit_teardown` runs +teardown on request on every platform, frees included, and must be followed +directly by `exit`. It is for native hosts: like `llama_dart_exit_call_begin` +and `llama_dart_exit_call_end`, it is not meant to be bound from Dart. `src/llama_dart_wrapper.h` documents each function. `llamadart_exit_teardown_test` covers the registry on every platform. On macOS -it also writes a small decoder and a small encoder model and runs the -scenarios that load one, so ctest needs no model file: +and Linux it also writes a small decoder and a small encoder model and runs +the scenarios that load one, so ctest needs no model file: ```bash cmake -S . -B build/exit-teardown -G Ninja -DLLAMADART_BUILD_TESTS=ON diff --git a/cmake/llama_cpp_patches.cmake b/cmake/llama_cpp_patches.cmake new file mode 100644 index 00000000..fcc1835f --- /dev/null +++ b/cmake/llama_cpp_patches.cmake @@ -0,0 +1,84 @@ +# 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) + # 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" + --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 (error) + message(WARNING "patches/llama.cpp does not fit this 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/image_token_limit.md b/docs/image_token_limit.md new file mode 100644 index 00000000..bf5b1610 --- /dev/null +++ b/docs/image_token_limit.md @@ -0,0 +1,61 @@ +# Opt-in image-token limit + +The next wrapper rebuild adds `llama_dart_mtmd_supports_image_token_limit`. +It reads GGUF projector metadata without weights or GPU initialization and +returns 1 only for `gemma4v`/`gemma4uv` and limits 70 through 1120. Both the +legacy `clip.projector_type` and mixed-modality `clip.vision.projector_type` +keys follow upstream precedence. Missing, unknown and wrongly typed keys +return unsupported; read/argument errors return -1 through the exception +barrier. The call is guarded against exit teardown. + +After a successful probe, callers explicitly set +`mtmd_context_params.image_max_tokens` before the existing guarded projector +initialization. Omitted options retain upstream metadata defaults. The option +reduces vision-patch detail and may change answers; it does not automatically +track a context microbatch or bound prompt/marker tokens. Existing decode +size checks remain necessary. Gemma 3 and other projector families are +unsupported rather than silently ignoring the request. + +The 70-token lower bound preserves the default minimum-pixel threshold; +the 1120-token upper bound prevents expanding the model's default budget. +Primary implementation: upstream v0.6.0 clip.cpp Gemma 4 projector setup and +clip-model.h `set_limit_image_tokens`/`set_warmup_n_tokens`. + +`llamadart_image_token_limit_test` reads real metadata fixtures and covers +supported ranges, unsupported types, mixed metadata, type mismatch and +exception-barrier recovery. Real Gemma 4 image encoding remains a separate +qualification gate before publication or downstream pin adoption. + +Local verification (2026-10-09, macOS arm64, upstream v0.6.0): all 46 native +CTest cases pass and the export validator finds all 86 required exports. +A real cached Gemma 4 E2B Q4_K_S model with its F16 projector and a 1600x1600 +RGB image produces 1089 image tokens by default and 484 with an explicit +512-token limit. The same maintained test optionally takes a model and +projector path and checks preprocessing. A fourth argument selects a limit and additionally +encodes the capped image: + +```sh +build/v060-2/llamadart_image_token_limit_test /path/to/model.gguf /path/to/mmproj.gguf +build/v060-2/llamadart_image_token_limit_test /path/to/model.gguf /path/to/mmproj.gguf 70 +``` + +A full default-image CPU encode was stopped at the bounded limit while still +computing. The smaller capped encoding smoke is recorded separately; neither +preprocessing nor encoding alone establishes answer quality. + +The upstream resize budget is not a strict ceiling on arbitrary input. A +source-path control using the exact vendored `mtmd-image.cpp` resize helper +produced 81 patches for a tiny square at 70 and 715 for a 48x48000 image at 512. +Minimum-size and patch alignment can overshoot the target. Consumers that +promise a ceiling must reject oversized image chunks before encoding. The +prepared Dart consumer does so, on both causal and noncausal projectors, and +rejects runtimes lacking chunk inspection. Default inputs are unchanged. + +Real noncausal Gemma 4 (`gemma4v`) projectors remain unqualified: no matching +cached projector is available. Gemma 3 remains explicitly unsupported. No +runtime release, device run or downstream pin change was performed. + +The bounded real CPU encode with an explicit limit of 70 passed: default +preprocessing 1089 patches, capped 64 patches, encoded output shape +[1536,64,1]. This is real Gemma 4 E2B vision-encoding evidence. It does not +qualify noncausal Gemma 4v, GPU inference, full text decode or answer quality. diff --git a/docs/release_version_policy.md b/docs/release_version_policy.md index ed9461bd..3e3dc002 100644 --- a/docs/release_version_policy.md +++ b/docs/release_version_policy.md @@ -119,6 +119,18 @@ 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`): 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 +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_1_wrapper_rebuild.md b/docs/v060_1_wrapper_rebuild.md index 11409b73..405ac284 100644 --- a/docs/v060_1_wrapper_rebuild.md +++ b/docs/v060_1_wrapper_rebuild.md @@ -338,6 +338,9 @@ Why the Apple mechanism does not carry over: measure either effect, and the Linux lanes here load no backend, so they run no model scenario. +`v0.6.0-2` fixes it, with the wait and without the frees as recommended below +but without the gate: see [`v060_2_wrapper_rebuild.md`](v060_2_wrapper_rebuild.md). + Recommended design, for a later rebuild: 1. Compile a small object into every shared library of the bundle that holds diff --git a/docs/v060_2_wrapper_rebuild.md b/docs/v060_2_wrapper_rebuild.md new file mode 100644 index 00000000..ae235f93 --- /dev/null +++ b/docs/v060_2_wrapper_rebuild.md @@ -0,0 +1,270 @@ +# v0.6.0-2 rebuild + +Changes on llama.cpp `v0.6.0` +(`d81235049384534c167caea52b85a694f6103d14`) for the native rebuild tag +`v0.6.0-2`. The opt-in image-token capability adds the export documented in +[`image_token_limit.md`](image_token_limit.md). + +## 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. + 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. + +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. + +## 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. + +## 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. + +## 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 +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, 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, which both patches fit, and on the pinned one validates +the bundle, markers included. No lane runs ggml-vulkan on a device. + +## Linux host shutdown + +### Contract + +Before a native host calls C `exit()`, it stops new work, stops and joins its +native workers, and shuts down its Dart isolates or Flutter engine. A kill +request is not completion: await each isolate's exit notification and native +finalizers before exiting. Free contexts before projectors / models. A native +call already in progress completes before its isolate can shut down. + +Linux, Android excepted, retains the statics owned by the runtime bundle. +`src/llama_dart_static_destructors.c` supplies a hidden `__cxa_atexit` that drops +owned static destructors; external libraries keep their ordinary exit behavior. +The wrapper remains linked with `-z nodelete` so held objects and finalizer +callbacks remain valid across `dlclose`. Artifact validators reject missing +retention and owned imports of `__cxa_atexit`. + +C exit registers no automatic Linux wrapper teardown or exit handler. It does +not set a late-call refusal state, flush streams early, wait, free live objects +or call `_exit`. Normal host callbacks, dependency destructors and libc stdio +flushing run in their normal order. An earlier native-host callback can still +join a worker and free its tracked objects; the wrapper does not park that +worker merely because libc exit began. + +Apple automatic teardown and explicit `llama_dart_exit_teardown` are unchanged. +Do not invoke explicit teardown before joining workers: it parks later guarded +calls, so a subsequent host join can hang. Android is unchanged. Windows / musl +hardware qualification is not established by these Linux glibc measurements. + +### Why exit must follow host shutdown + +A direct C exit with live Dart isolates is unsafe independently of llama.cpp. +With an allocating isolate and an earlier300ms host callback, the VM aborts at +`handles_impl.h:39` without loading any native model (llamadart#977). Retaining +owned statics cannot protect a GPU driver's or BLAS library's destructors either. +Direct C exit while Dart isolates or dependency-using native workers are alive +is outside this contract, including calls from an evaluation callback or an +incomplete model load. CPU raw-exit controls remain diagnostics, not support +claims. A hung native call cannot be called quiescent after a timeout; the host +must withhold normal C exit until it completes or explicitly choose its own +abrupt process-termination policy. + +The rejected candidate flushed streams and called `_exit` when a call was in +flight. It skipped earlier host callbacks, and its `fflush(NULL)` deadlocked if +a worker held a FILE lock whose earlier host callback would release it. Removing +only the flush lost buffered output. Both alternatives violate the accepted +preservation contract and are absent from this revision. + +### Validation and replay + +`llamadart_exit_teardown_exit-status` verifies exit37, the earlier callback, +buffered output, and a host callback joining a marked native worker that holds a +FILE lock. Its10s CTest timeout makes the old unconditional-flush deadlock fail. +`exit-late-calls` verifies the host callback can create and free tracked objects +without an automatic Linux refusal state. These are native compatibility +controls, without a running Dart VM. Apple teardown tests retain their contract. + +The maintained manual `tests/manual/dart_host_shutdown_probe.dart` uses worker +NativeFinalizers, per-worker onExit notifications, an allocating isolate, a +slow native call and a slow earlier host callback. Build the adjacent shim as +in `dart_exit_probe.dart`; set `PROBE_STEP_DELAY_MS=300`, then run: + +```bash +dart tests/manual/dart_host_shutdown_probe.dart libshim.so \ + cooperative-finalizer-slow-native +``` + +Success requires exit0, `NATIVE_ACTIVE_BEFORE_KILL`, `NATIVE_CALLS_AFTER_EXIT 0`, +`NATIVE_FREE_COUNT_AFTER_EXIT 1`, `HOST_HANDLER_COMPLETED`, and `C_BUFFERED_PAYLOAD`. +`raw-control` reproduces the VM defect; `cooperative-control` verifies allocator +shutdown without loading a native bundle. Neither case requires model downloads. + +Pre-implementation prototype evidence (not qualification of this revised head): +Linuxarm64 GCC14/glibc2.41, Dart3.13.1, stories15M CPU, five repeats per case / +build, released baseline vs rejected head vs preservation prototype.60/60 +cooperative model cases and15/15 no-model cases retained callbacks / output. +30/30 active native-call cases waited314–339ms before onExit;15/15 finalizers +completed first.15/15 raw no-model controls aborted. The protocol also passed +on the released baseline, so it establishes the lifecycle boundary, not a new +native feature. The GCC13 dependencies were reused read-only; this differs +from Ubuntu24.04/GCC13 release qualification. + +Current-head CI, independent audit and exact-runtime replay are required anew. +Remaining release gates include real GPU / OpenBLAS driver shutdown, image +runtime, Flutter Linux host ordering, final published artifacts and device +qualification. No earlier raw-exit result establishes those gates. 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/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 new file mode 100644 index 00000000..40c0550d --- /dev/null +++ b/patches/llama.cpp/README.md @@ -0,0 +1,78 @@ +# 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 (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 + `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. + +A hunk applies only where its context and removed lines occur exactly once in +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. + +## 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..d6f12681 --- /dev/null +++ b/patches/llama.cpp/series.json @@ -0,0 +1,20 @@ +{ + "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"} + ] + }, + { + "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"} + ] + } + ] +} diff --git a/scripts/generate_assets_manifest.sh b/scripts/generate_assets_manifest.sh index dbad582a..313e732e 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. 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:-}" 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/src/llama_dart_image_token_limit.cpp b/src/llama_dart_image_token_limit.cpp new file mode 100644 index 00000000..6b48cb23 --- /dev/null +++ b/src/llama_dart_image_token_limit.cpp @@ -0,0 +1,39 @@ +#include "llama_dart_image_token_limit_internal.h" +#include "clip-impl.h" +#include "gguf.h" + +#include +#include +#include + +int32_t llama_dart_image_token_limit_supported(const char *mmproj_fname, + int32_t max_tokens) { + const gguf_init_params params{true, nullptr}; + std::unique_ptr metadata( + gguf_init_from_file(mmproj_fname, params), gguf_free); + if (!metadata) { + throw std::runtime_error("could not read projector GGUF metadata"); + } + auto key = gguf_find_key(metadata.get(), "clip.projector_type"); + if (key >= 0 && gguf_get_kv_type(metadata.get(), key) != GGUF_TYPE_STRING) { + return 0; + } + if (key < 0 || std::strlen(gguf_get_val_str(metadata.get(), key)) == 0) { + key = gguf_find_key(metadata.get(), "clip.vision.projector_type"); + } + if (key < 0 || gguf_get_kv_type(metadata.get(), key) != GGUF_TYPE_STRING) { + return 0; + } + const char *type = gguf_get_val_str(metadata.get(), key); + if (clip_projector_type_from_string(type) == PROJECTOR_TYPE_UNKNOWN) { + return 0; + } + // v0.6.0 applies custom_image_max_tokens for these dynamic projectors + // through set_limit_image_tokens(70, 1120). Never raise their metadata + // budget or set a maximum below the default minimum-pixel threshold. + return (std::strcmp(type, "gemma4v") == 0 || + std::strcmp(type, "gemma4uv") == 0) && + max_tokens >= 70 && max_tokens <= 1120 + ? 1 + : 0; +} diff --git a/src/llama_dart_image_token_limit_internal.h b/src/llama_dart_image_token_limit_internal.h new file mode 100644 index 00000000..9c7065cb --- /dev/null +++ b/src/llama_dart_image_token_limit_internal.h @@ -0,0 +1,6 @@ +#pragma once +#include + +// Reads upstream projector metadata; the public wrapper guards the call and +// translates exceptions into llama_dart_last_error. +int32_t llama_dart_image_token_limit_supported(const char *path, int32_t max_tokens); diff --git a/src/llama_dart_static_destructors.c b/src/llama_dart_static_destructors.c new file mode 100644 index 00000000..cd54473d --- /dev/null +++ b/src/llama_dart_static_destructors.c @@ -0,0 +1,26 @@ +// Linked into every shared library of the Linux bundle: libllamadart and the +// llama.cpp libraries next to it (CMakeLists.txt). +// +// The C++ runtime registers the destructor of each static of a library +// through __cxa_atexit. The linker binds those calls to this definition, +// which registers nothing, so the statics of the library are never destroyed. +// +// C exit() destroys statics while other threads are still inside llama.cpp, +// which then read freed memory (https://github.com/leehack/llamadart/issues/949). +// On Apple platforms llama.cpp is part of libllamadart, whose exit teardown +// runs before the first of those statics is destroyed. Here the libraries are +// separate, and exit handlers run in reverse order of registration: no handler +// of libllamadart precedes the destructor of a static that another library +// creates later, in the middle of a model load for one. The handler that +// libllamadart does register ends the process for a call in flight that it +// counts; a static that is never destroyed stays valid for the calls that it +// does not. +#if defined(__linux__) && !defined(__ANDROID__) +__attribute__((visibility("hidden"), used)) int +__cxa_atexit(void (*destroy)(void *), void *object, void *dso_handle) { + (void)destroy; + (void)object; + (void)dso_handle; + return 0; +} +#endif diff --git a/src/llama_dart_wrapper.cpp b/src/llama_dart_wrapper.cpp index b2d4314f..5199ded1 100644 --- a/src/llama_dart_wrapper.cpp +++ b/src/llama_dart_wrapper.cpp @@ -1,4 +1,5 @@ #include "llama_dart_wrapper.h" +#include "llama_dart_image_token_limit_internal.h" #include "llama_dart_barrier_internal.h" #include "llama_dart_mtp_internal.h" #include "llama_dart_mtmd_compat.h" @@ -28,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -727,6 +729,7 @@ static thread_local bool llama_dart_exit_teardown_thread = false; // Calls in flight on this thread. The registry counts the outermost one. static thread_local int32_t llama_dart_exit_call_depth = 0; + // Called with the registry locked. Returns whether the calling thread may go // on to use tracked objects. Once teardown has begun, teardown waits for a // thread that is in a call in flight, and the teardown thread gets false. Any @@ -749,6 +752,7 @@ static bool llama_dart_exit_admit(llama_dart_exit_registry ®istry, } } + #if defined(__APPLE__) struct llama_dart_exit_static_destructor { void (*destroy)(void *); @@ -805,6 +809,7 @@ __cxa_atexit(void (*destroy)(void *), void *object, void *dso_handle) { } #endif + // Registers teardown to run at exit once something is tracked, so that it // does not wait for the first static of this image to be destroyed. atexit // handlers run in reverse order of registration, so this one runs after the @@ -817,6 +822,8 @@ static void llama_dart_exit_arm() { #endif } + + static bool llama_dart_exit_insert(void *object, void (*free_fn)(void *), int32_t stage, void *uses_first = nullptr, void *uses_second = nullptr) { @@ -914,7 +921,9 @@ static void llama_dart_exit_begin_call(bool creating) { } struct llama_dart_exit_call { - llama_dart_exit_call() { llama_dart_exit_call_begin(); } + llama_dart_exit_call() { + llama_dart_exit_call_begin(); + } ~llama_dart_exit_call() { llama_dart_exit_call_end(); } llama_dart_exit_call(const llama_dart_exit_call &) = delete; llama_dart_exit_call &operator=(const llama_dart_exit_call &) = delete; @@ -923,7 +932,9 @@ struct llama_dart_exit_call { // A call in flight that tracks what it creates. Teardown waits for it even // when nothing is tracked yet. struct llama_dart_exit_creating_call { - llama_dart_exit_creating_call() { llama_dart_exit_begin_call(true); } + llama_dart_exit_creating_call() { + llama_dart_exit_begin_call(true); + } ~llama_dart_exit_creating_call() { { auto ®istry = llama_dart_exit_state(); @@ -1163,6 +1174,17 @@ llama_dart_init_from_model(struct llama_model *model, }); } +LLAMADART_API int32_t llama_dart_mtmd_supports_image_token_limit( + const char *mmproj_fname, int32_t max_tokens) { + return llama_dart_barrier(-1, [mmproj_fname, max_tokens] { + if (mmproj_fname == nullptr || max_tokens <= 0) { + throw std::invalid_argument("image token limit needs a projector and a positive limit"); + } + llama_dart_exit_creating_call call; + return llama_dart_image_token_limit_supported(mmproj_fname, max_tokens); + }); +} + LLAMADART_API struct mtmd_context *llama_dart_mtmd_init_from_file( const char *mmproj_fname, const struct llama_model *text_model, const struct mtmd_context_params *ctx_params) { diff --git a/src/llama_dart_wrapper.h b/src/llama_dart_wrapper.h index 563d4078..69983c16 100644 --- a/src/llama_dart_wrapper.h +++ b/src/llama_dart_wrapper.h @@ -352,8 +352,25 @@ LLAMADART_API int32_t llama_dart_vulkan_get_device_info( // or hot restart does. ggml-metal aborts in its static destructor while any // Metal buffer is still allocated, so teardown has to run before that // destructor. On Apple platforms it runs during exit, before the first static -// of libllamadart is destroyed. Elsewhere it runs only when -// llama_dart_exit_teardown is called. +// of libllamadart is destroyed. +// +// On Linux, Android excepted, owned bundle statics are retained until the +// process is gone. C exit() runs no wrapper handler: normal host callbacks, +// dependency destructors and libc stream flushing proceed without a forced +// _exit, an automatic free, a wait or late-call refusal. +// +// Before a native host calls C exit(), it must stop and join its workers and +// shut down its Dart isolates / Flutter engine. Await isolate exit and native +// finalizer completion, not just a kill request. A direct C exit() with live +// Dart isolates can abort the VM even without llama.cpp (llamadart#977). +// Retaining owned statics does not protect a GPU driver's or BLAS library's +// destructors. Do not call explicit teardown before joining workers: teardown +// parks later guarded calls and can deadlock a host join. +// +// libllamadart remains loaded across dlclose so held native objects and their +// finalizer callbacks stay valid. quick_exit and _exit run no cleanup. +// Elsewhere nothing changes. llama_dart_exit_teardown explicitly frees on +// every platform; automatic Apple exit teardown remains as described above. // // Objects are tracked, before the creating call returns, by // llama_dart_model_load_from_file, llama_dart_init_from_model, @@ -454,6 +471,19 @@ LLAMADART_API struct llama_context * llama_dart_init_from_model( struct llama_model * model, struct llama_context_params params); +// Capability probe for an explicit mtmd_context_params.image_max_tokens. +// Reads projector metadata only; does not load weights or initialize a GPU. +// Returns 1 for a Gemma 4 vision projector (gemma4v/gemma4uv) and a limit +// in [70, 1120], 0 for an unsupported projector/limit, -1 for a read error +// or invalid arguments (llama_dart_last_error describes the error). +// It is an upstream resize budget: minimum-size/patch alignment can exceed +// it, especially for extreme aspect ratios. Callers enforcing a ceiling must +// inspect image-chunk token counts before encoding. It does not limit prompt +// or marker tokens. Defaults +// are unchanged unless the caller explicitly sets image_max_tokens. +LLAMADART_API int32_t llama_dart_mtmd_supports_image_token_limit( + const char * mmproj_fname, int32_t max_tokens); + // mtmd_init_from_file that tracks the context in the MODEL_USER stage. Free it // with llama_dart_exit_free. Blocks after teardown. LLAMADART_API struct mtmd_context * llama_dart_mtmd_init_from_file( diff --git a/tests/exit_teardown_test.cpp b/tests/exit_teardown_test.cpp index 75a8387c..0e0785f5 100644 --- a/tests/exit_teardown_test.cpp +++ b/tests/exit_teardown_test.cpp @@ -30,6 +30,11 @@ #define LLAMADART_TEST_ADDRESS_SANITIZER 1 #endif +#if defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) +#include +#include +#endif + #if defined(LLAMADART_TEST_ADDRESS_SANITIZER) #include #elif defined(__APPLE__) @@ -464,15 +469,65 @@ int test_blocked() { return 0; } +// C exit() runs teardown on Apple platforms: it waits for the calls in +// flight, frees, and blocks the threads that reach libllamadart afterwards. +// Linux retains owned statics and leaves normal libc exit untouched. +// Hosts stop workers and the managed runtime before C exit. #if defined(__APPLE__) -const bool kTeardownRunsAtExit = true; +const bool kExitFreesObjects = true; +const bool kExitWaitsForCalls = true; +const bool kExitEndsProcess = false; +const bool kExitRefusesLateCalls = false; +#elif defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) +const bool kExitFreesObjects = false; +const bool kExitWaitsForCalls = false; +const bool kExitEndsProcess = false; +const bool kExitRefusesLateCalls = false; #else -const bool kTeardownRunsAtExit = false; +const bool kExitFreesObjects = false; +const bool kExitWaitsForCalls = false; +const bool kExitEndsProcess = false; +const bool kExitRefusesLateCalls = false; +#endif + +// Set by a scenario before the exit that a call may run into. +std::atomic g_exit_expected{false}; + +// Whether the calling thread's last call was refused because C exit() had +// passed libllamadart already. +bool refused_by_exit() { + const char *error = llama_dart_last_error(); + return kExitRefusesLateCalls && g_exit_expected.load() && error != nullptr && + strcmp(error, "the process is exiting") == 0; +} + +// For an exit handler that a scenario registers before libllamadart registers +// its own, so that it runs after it. Where the exit ends the process for a +// call in flight, the exit never gets this far in such a scenario. +void expect_process_ended(const char *what) { + if (kExitEndsProcess) { + fprintf(stderr, "the exit went on under %s\n", what); + _Exit(EXIT_FAILURE); + } +} + +// Where the backends are modules next to the llama.cpp libraries and not part +// of libllamadart, a scenario that computes has to load one. The CPU backend +// alone keeps the scenarios the same whatever other modules the build has. +void load_backend_modules() { +#if defined(LLAMADART_TEST_CPU_BACKEND) + assert(ggml_backend_load(LLAMADART_TEST_CPU_BACKEND) != nullptr); #endif +} + +void init_backends() { + llama_backend_init(); + load_backend_modules(); +} void expect_freed_at_exit() { const std::vector expected = - kTeardownRunsAtExit ? kStageOrder : std::vector(); + kExitFreesObjects ? kStageOrder : std::vector(); if (recorded() != expected) { fprintf(stderr, "exit teardown freed %zu objects, expected %zu\n", recorded().size(), expected.size()); @@ -487,6 +542,119 @@ int test_exit() { return 0; } +std::atomic g_call_ended{false}; + +void expect_call_ended_at_exit() { + expect_process_ended("a call in flight"); + if (kExitWaitsForCalls && !g_call_ended.load()) { + fprintf(stderr, "the exit did not wait for the call in flight\n"); + _Exit(EXIT_FAILURE); + } +} + +// The exit sees a call in flight when objects were only tracked, with no +// creating call: it waits for the call, or on Linux ends the process. +int test_exit_in_flight() { + // Registered first, so it runs after the teardown registered by tracking. + assert(atexit(expect_call_ended_at_exit) == 0); + static char object[] = "object"; + assert(llama_dart_exit_track(object, free_named, + LLAMA_DART_EXIT_STAGE_MODEL)); + static std::atomic started{false}; + std::thread([] { + llama_dart_exit_call_begin(); + started.store(true); + sleep_ms(400); + g_call_ended.store(true); + llama_dart_exit_call_end(); + }).detach(); + while (!started.load()) { + sleep_ms(1); + } + return 0; +} + +char kLateObject[] = "late-object"; +llama_dart_ngram *g_created_at_exit = nullptr; + +// An earlier host callback still owns normal wrapper cleanup. No Dart VM +// is active here, and no wrapper teardown has begun. +void make_late_calls() { + assert(llama_dart_exit_tracked_count() == 1); + g_created_at_exit = llama_dart_ngram_simple_init(4, 8); + assert(g_created_at_exit != nullptr); + assert(llama_dart_last_error() == nullptr); + assert(llama_dart_exit_tracked_count() == 2); + llama_dart_exit_free(g_created_at_exit); + llama_dart_exit_free(kLateObject); + assert(llama_dart_exit_tracked_count() == 0); + assert(recorded() == std::vector{"late-object"}); +} + +int test_exit_late_calls() { + assert(atexit(make_late_calls) == 0); + assert(llama_dart_exit_track(kLateObject, free_named, + LLAMA_DART_EXIT_STAGE_MODEL)); + return 0; +} + +#if defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) +std::atomic status_worker_stop{false}; +std::thread *status_worker = nullptr; +FILE *status_locked_stream = nullptr; +void status_host_callback() { + status_worker_stop.store(true); + status_worker->join(); + printf(";host handler ran"); +} +#endif + +// Normal C exit preserves its status, earlier callbacks and buffered output. +// A host callback releases a FILE lock held by a marked native worker: an +// unconditional fflush before that callback would hang. This native-only +// compatibility control does not authorize live-Dart-isolate C exit. +int test_exit_status() { +#if defined(__linux__) && defined(__GLIBC__) && !defined(__ANDROID__) + int output[2]; + assert(pipe(output) == 0); + const pid_t child = fork(); + assert(child >= 0); + if (child == 0) { + close(output[0]); + assert(dup2(output[1], STDOUT_FILENO) >= 0); + assert(atexit(status_host_callback) == 0); + static char object[] = "object"; + assert(llama_dart_exit_track(object, free_named, + LLAMA_DART_EXIT_STAGE_MODEL)); + status_locked_stream = tmpfile(); + assert(status_locked_stream != nullptr); + static std::atomic started{false}; + status_worker = new std::thread([] { + llama_dart_exit_call_begin(); + flockfile(status_locked_stream); + started.store(true); + while (!status_worker_stop.load()) sleep_ms(1); + funlockfile(status_locked_stream); + llama_dart_exit_call_end(); + }); + while (!started.load()) sleep_ms(1); + printf("flushed at exit"); + exit(37); + } + close(output[1]); + std::string text; + char buffer[64]; + for (ssize_t count; (count = read(output[0], buffer, sizeof(buffer))) > 0;) { + text.append(buffer, static_cast(count)); + } + int status = 0; + assert(waitpid(child, &status, 0) == child); + assert(WIFEXITED(status) && WEXITSTATUS(status) == 37); + assert(text == "flushed at exit;host handler ran"); +#endif + return 0; +} + std::string g_system_info; // Uses the static behind llama_print_system_info, which teardown must find @@ -511,7 +679,7 @@ int test_late_static() { g_system_info = llama_print_system_info(); // The reader needs text that lives on the heap for a sanitizer to see a use // after the static is gone. There is none where no backend is loaded. - assert(!kTeardownRunsAtExit || g_system_info.size() > 64); + assert(!kExitFreesObjects || g_system_info.size() > 64); return 0; } @@ -670,7 +838,7 @@ struct model_fixture { }; model_fixture load_model(const char *path, model_options options = {}) { - llama_backend_init(); + init_backends(); model_fixture fixture; auto model_params = llama_model_default_params(); static ggml_backend_dev_t no_devices[] = {nullptr}; @@ -703,7 +871,8 @@ llama_batch prompt(model_fixture &fixture) { } void clear_memory(model_fixture &fixture) { - assert(llama_dart_memory_clear(llama_get_memory(fixture.context), true)); + assert(llama_dart_memory_clear(llama_get_memory(fixture.context), true) || + refused_by_exit()); } llama_sampler *greedy_sampler() { @@ -716,8 +885,11 @@ llama_sampler *greedy_sampler() { // One generation step as the Dart side runs it: decode, then sample. llama_token decode_and_sample(model_fixture &fixture, llama_sampler *sampler) { clear_memory(fixture); - assert(llama_dart_decode(fixture.context, prompt(fixture)) == 0); - return llama_dart_sampler_sample(sampler, fixture.context, -1); + const int32_t status = llama_dart_decode(fixture.context, prompt(fixture)); + assert(status == 0 || refused_by_exit()); + // A decode that was refused has left nothing to sample. + return status == 0 ? llama_dart_sampler_sample(sampler, fixture.context, -1) + : 0; } // Exits with a loaded model and context that nothing frees. @@ -838,7 +1010,7 @@ int test_model_wrappers(const char *path) { } int test_graph() { - llama_backend_init(); + init_backends(); ggml_backend_t backend = llama_dart_ggml_backend_dev_init( ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU), nullptr); assert(backend != nullptr); @@ -1221,6 +1393,7 @@ int exit_while_generating(model_fixture &fixture) { while (steps.load() < 4) { sleep_ms(1); } + g_exit_expected.store(true); g_exiting.store(true); return 0; } @@ -1232,6 +1405,149 @@ int test_model_decode(const char *path) { return exit_while_generating(fixture); } +std::atomic g_computed_after_release{0}; + +// Holds the evaluation and, once it is released, has each tensor computed on +// its own so that the ones computed from then on can be counted. +bool hold_then_count_evaluation(ggml_tensor *tensor, bool ask, void *data) { + if (!ask) { + g_computed_after_release.fetch_add(1); + return true; + } + hold_evaluation(tensor, ask, data); + return g_release_evaluation.load(); +} + +void finish_held_evaluation_at_exit() { + g_release_evaluation.store(true); + const int64_t started = now_ms(); + while (g_computed_after_release.load() < 16) { + if (now_ms() - started > 10000) { + fprintf(stderr, "the held decode did not go on during the exit\n"); + _Exit(EXIT_FAILURE); + } + sleep_ms(1); + } +} + +// Exits while another thread is inside a decode that is not a call in +// flight, so that the exit goes on under it. On Linux no library of the +// bundle registers static destructors, so the decode computes on, with the +// statics the model load created, after the exit has run its handlers. +int test_model_unguarded_decode(const char *path) { + // Registered first, so it runs after the handler of libllamadart and after + // the destructors of the statics that the load creates, where those are + // registered. + assert(atexit(finish_held_evaluation_at_exit) == 0); + static model_fixture fixture; + model_options options; + options.eval_callback = hold_then_count_evaluation; + fixture = load_model(path, options); + decode_prompt(fixture); + clear_memory(fixture); + g_hold_evaluation.store(true); + std::thread([] { + assert(llama_decode(fixture.context, prompt(fixture)) == 0); + }).detach(); + while (!g_evaluation_held.load()) { + sleep_ms(1); + } + return 0; +} + +std::atomic g_returned_from_main_ms{0}; + +void expect_exit_took_no_time() { + const int64_t took = now_ms() - g_returned_from_main_ms.load(); + if (took > 100) { + fprintf(stderr, "the exit took %lld ms with no call in flight\n", + static_cast(took)); + _Exit(EXIT_FAILURE); + } +} + +// On Linux an exit with no call in flight takes no time in libllamadart, +// also right after a guarded call returned: a Dart VM aborts when its +// isolates run while exit() takes its time. +int test_model_exit_idle(const char *path) { + // Registered first, so it runs after the handler of libllamadart. + assert(atexit(expect_exit_took_no_time) == 0); + static model_fixture fixture; + fixture = load_model(path); + llama_sampler *sampler = greedy_sampler(); + assert(decode_and_sample(fixture, sampler) >= 0); + llama_sampler_free(sampler); + g_returned_from_main_ms.store(now_ms()); + return 0; +} + +std::atomic g_worker_stop{false}; +std::atomic g_worker_done{false}; + +// What a host does that stops its worker at exit: the worker must come back. +void stop_and_join_worker() { + g_worker_stop.store(true); + const int64_t started = now_ms(); + while (!g_worker_done.load()) { + if (now_ms() - started > 10000) { + fprintf(stderr, "the worker did not come back during the exit\n"); + _Exit(EXIT_FAILURE); + } + sleep_ms(1); + } +} + +// On Linux the exit blocks no thread: a worker that frees its model when the +// host's own exit handler tells it to returns from the frees, which free +// nothing any more. +int test_model_exit_join_idle(const char *path) { + // Registered first, so it runs after the handler of libllamadart. + assert(atexit(stop_and_join_worker) == 0); + static model_fixture fixture; + fixture = load_model(path); + std::thread([] { + while (!g_worker_stop.load()) { + sleep_ms(1); + } + llama_dart_exit_free(fixture.context); + llama_dart_exit_free(fixture.model); + if (llama_dart_exit_tracked_count() != 0) { + fprintf(stderr, "host worker cleanup left tracked objects\n"); + _Exit(EXIT_FAILURE); + } + g_worker_done.store(true); + }).detach(); + return 0; +} + +// The same with a worker that generates until it is told to stop. An exit +// that finds its decode in flight ends the process; one that falls between +// two calls goes on, every call the worker begins afterwards is refused, and +// the worker comes back. +int test_model_exit_join_generating(const char *path) { + assert(atexit(stop_and_join_worker) == 0); + static model_fixture fixture; + static std::atomic steps{0}; + fixture = load_model(path); + std::thread([] { + llama_sampler *sampler = greedy_sampler(); + while (!g_worker_stop.load()) { + assert(decode_and_sample(fixture, sampler) >= 0); + steps.fetch_add(1); + if (refused_by_exit()) { + sleep_ms(1); + } + } + llama_sampler_free(sampler); + g_worker_done.store(true); + }).detach(); + while (steps.load() < 3) { + sleep_ms(1); + } + g_exit_expected.store(true); + return 0; +} + // Exits while another thread generates on a model whose load created statics // in libllamadart that an earlier, different load had not: a CPU-only load, // then one that maps the file into GPU memory. @@ -1248,9 +1564,22 @@ int test_model_late_load(const char *path) { return exit_while_generating(second); } +std::atomic g_load_resumed{false}; + +void expect_exit_waited_for_load() { + expect_process_ended("a load in flight"); + if (kExitWaitsForCalls && !g_load_resumed.load()) { + fprintf(stderr, "the exit did not wait for the load in flight\n"); + _Exit(EXIT_FAILURE); + } +} + // Exits while another thread is loading the model. int test_model_load(const char *path) { - llama_backend_init(); + // Registered first, so it runs after the handler of libllamadart, which + // nothing but the load in flight makes run: nothing is tracked. + assert(atexit(expect_exit_waited_for_load) == 0); + init_backends(); static std::atomic loading{false}; static const char *model_path = nullptr; model_path = path; @@ -1269,6 +1598,7 @@ int test_model_load(const char *path) { sleep_ms(1); } sleep_ms(500); + g_load_resumed.store(true); return true; }; std::thread([params] { @@ -1285,7 +1615,7 @@ int test_model_load(const char *path) { // Teardown waits for a load in flight although nothing is tracked yet. int test_model_load_wait(const char *path) { - llama_backend_init(); + init_backends(); static std::atomic loading{false}; static std::atomic held{false}; static const char *model_path = nullptr; @@ -1377,6 +1707,7 @@ void free_model_when_teardown_waits(void *object) { } void expect_free_finished_at_exit() { + expect_process_ended("a free in flight"); if (!g_free_finished.load() || g_released_before_teardown.load()) { fprintf(stderr, "the exit did not wait for the free in flight\n"); _Exit(EXIT_FAILURE); @@ -1387,6 +1718,24 @@ void expect_free_finished_at_exit() { // Metal aborts in its static destructor when the exit does not wait for the // free; without Metal the check at exit shows it. int test_model_free_in_flight(const char *path) { +#if defined(__linux__) && !defined(__ANDROID__) + // Linux waits in the host, before libc exit / dependency destructors. + assert(atexit([] { assert(g_free_finished.load()); }) == 0); + auto fixture = load_model(path); + llama_dart_exit_free(fixture.context); + assert(llama_dart_exit_track(fixture.model, [](void *object) { + g_free_started.store(true); + sleep_ms(300); + llama_model_free(static_cast(object)); + g_free_finished.store(true); + }, LLAMA_DART_EXIT_STAGE_MODEL)); + std::thread worker([fixture] { llama_dart_exit_free(fixture.model); }); + while (!g_free_started.load()) sleep_ms(1); + worker.join(); + assert(g_free_finished.load()); + assert(llama_dart_exit_tracked_count() == 0); + return 0; +#else // Registered first, so it runs after teardown and after the Metal device, // which the load creates, is destroyed. assert(atexit(expect_free_finished_at_exit) == 0); @@ -1407,6 +1756,7 @@ int test_model_free_in_flight(const char *path) { } assert(llama_dart_exit_tracked_count() == 0); return 0; +#endif } // Evaluates an image prompt chunk by chunk, as the Dart side does. @@ -2137,7 +2487,7 @@ using tokens = std::vector; // and stops at an end-of-generation token that the draft predicted, as // llama.cpp's common_sampler_sample_and_accept_n does. int test_model_sample_accept(const char *path) { - llama_backend_init(); + init_backends(); auto model_params = llama_model_default_params(); // On the CPU, where every device can run the backend sampler's argmax: the // Metal device of a virtual machine cannot. @@ -2253,6 +2603,10 @@ int main(int argc, char **argv) { const std::string scenario = argc > 1 ? argv[1] : ""; const char *first = argc > 2 ? argv[2] : nullptr; const char *second = argc > 3 ? argv[3] : nullptr; + // Forks, so it runs before anything starts a thread. + if (scenario == "exit-status") { + return test_exit_status(); + } // Keeps llama.cpp's device, load and decode logs out of the test output. llama_dart_set_log_level(3); if (scenario == "dispose") { @@ -2288,6 +2642,12 @@ int main(int argc, char **argv) { if (scenario == "exit") { return test_exit(); } + if (scenario == "exit-in-flight") { + return test_exit_in_flight(); + } + if (scenario == "exit-late-calls") { + return test_exit_late_calls(); + } if (scenario == "late-static") { return test_late_static(); } @@ -2367,6 +2727,18 @@ int main(int argc, char **argv) { if (scenario == "model-decode") { return test_model_decode(first); } + if (scenario == "model-exit-idle") { + return test_model_exit_idle(first); + } + if (scenario == "model-exit-join-idle") { + return test_model_exit_join_idle(first); + } + if (scenario == "model-exit-join-generating") { + return test_model_exit_join_generating(first); + } + if (scenario == "model-unguarded-decode") { + return test_model_unguarded_decode(first); + } if (scenario == "model-late-load") { return test_model_late_load(first); } diff --git a/tests/image_token_limit_test.cpp b/tests/image_token_limit_test.cpp new file mode 100644 index 00000000..b07f585b --- /dev/null +++ b/tests/image_token_limit_test.cpp @@ -0,0 +1,109 @@ +#include "llama_dart_wrapper.h" +#include "gguf.h" + +#include +#include +#include +#include +#include +#include +#include "mtmd.h" + +#ifdef NDEBUG +#error "Wrapper contract tests require active assertions" +#endif + +static void real_image_limit(const char *model_path, const char *projector_path, + int limit, bool encode) { + assert(llama_dart_mtmd_supports_image_token_limit(projector_path, limit) == 1); + llama_model_params model_params = llama_model_default_params(); + model_params.n_gpu_layers = 0; + model_params.vocab_only = true; + llama_model *model = llama_dart_model_load_from_file(model_path, model_params); + assert(model != nullptr); + std::vector pixels(1600 * 1600 * 3, 127); + mtmd_bitmap *bitmap = mtmd_bitmap_init(1600, 1600, pixels.data()); + const mtmd_bitmap *bitmaps[] = {bitmap}; + size_t counts[2] = {}; + for (int run = 0; run < 2; ++run) { + auto params = mtmd_context_params_default(); + params.use_gpu = false; + params.warmup = false; + params.n_threads = 4; + if (run == 1) params.image_max_tokens = limit; + mtmd_context *projector = llama_dart_mtmd_init_from_file(projector_path, model, ¶ms); + assert(projector != nullptr); + auto *chunks = mtmd_input_chunks_init(); + const char *marker = mtmd_get_marker(projector); + const mtmd_input_text text{marker, std::strlen(marker), true, true}; + assert(llama_dart_mtmd_tokenize(projector, chunks, &text, bitmaps, 1) == 0); + for (size_t i = 0; i < mtmd_input_chunks_size(chunks); ++i) { + const auto *chunk = mtmd_input_chunks_get(chunks, i); + if (mtmd_input_chunk_get_type(chunk) == MTMD_INPUT_CHUNK_TYPE_IMAGE) { + counts[run] += mtmd_input_chunk_get_n_tokens(chunk); + if (encode && run == 1) { + assert(llama_dart_mtmd_encode_chunk(projector, chunk) == 0); + } + } + } + mtmd_input_chunks_free(chunks); + llama_dart_exit_free(projector); + } + std::printf("real image tokens: default=%zu capped=%zu\n", counts[0], counts[1]); + assert(counts[0] > static_cast(limit) && counts[1] > 0 && + counts[1] <= static_cast(limit)); + mtmd_bitmap_free(bitmap); + llama_dart_exit_free(model); +} + +int main(int argc, char **argv) { + if (argc == 3 || argc == 4) { + const int limit = argc == 4 ? std::atoi(argv[3]) : 512; + real_image_limit(argv[1], argv[2], limit, argc == 4); + return 0; + } + const char *path = "image_token_limit_metadata.gguf"; + const auto check = [path](const char *key, const char *type, int limit, int expected) { + gguf_context *metadata = gguf_init_empty(); + if (type != nullptr) gguf_set_val_str(metadata, key, type); + assert(gguf_write_to_file(metadata, path, true)); + gguf_free(metadata); + assert(llama_dart_mtmd_supports_image_token_limit(path, limit) == expected); + }; + for (const char *type : {"gemma4v", "gemma4uv"}) { + for (int limit : {70, 256, 512, 1120}) { + check("clip.projector_type", type, limit, 1); + check("clip.vision.projector_type", type, limit, 1); + } + check("clip.projector_type", type, 69, 0); + check("clip.projector_type", type, 1121, 0); + } + for (const char *type : {"gemma3", "mlp", "gemma4a", "unknown"}) { + check("clip.projector_type", type, 512, 0); + } + check("clip.projector_type", nullptr, 512, 0); + gguf_context *mixed = gguf_init_empty(); + gguf_set_val_str(mixed, "clip.projector_type", "gemma3"); + gguf_set_val_str(mixed, "clip.vision.projector_type", "gemma4v"); + assert(gguf_write_to_file(mixed, path, true)); + assert(llama_dart_mtmd_supports_image_token_limit(path, 512) == 0); + gguf_set_val_str(mixed, "clip.projector_type", ""); + assert(gguf_write_to_file(mixed, path, true)); + assert(llama_dart_mtmd_supports_image_token_limit(path, 512) == 1); + gguf_free(mixed); + gguf_context *metadata = gguf_init_empty(); + gguf_set_val_u32(metadata, "clip.projector_type", 7); + assert(gguf_write_to_file(metadata, path, true)); + gguf_free(metadata); + assert(llama_dart_mtmd_supports_image_token_limit(path, 512) == 0); + assert(llama_dart_mtmd_supports_image_token_limit(path, 0) == -1); + assert(std::strstr(llama_dart_last_error(), "positive limit") != nullptr); + assert(llama_dart_mtmd_supports_image_token_limit(nullptr, 512) == -1); + std::remove(path); + assert(llama_dart_mtmd_supports_image_token_limit(path, 512) == -1); + assert(std::strstr(llama_dart_last_error(), "GGUF metadata") != nullptr); + // A later successful probe clears the caught-error slot. + check("clip.projector_type", "gemma4v", 512, 1); + assert(llama_dart_last_error() == nullptr || llama_dart_last_error()[0] == 0); + std::remove(path); +} diff --git a/tests/manual/dart_exit_probe.dart b/tests/manual/dart_exit_probe.dart new file mode 100644 index 00000000..3d649301 --- /dev/null +++ b/tests/manual/dart_exit_probe.dart @@ -0,0 +1,233 @@ +// Manual probe, not run by CI: C exit() through FFI from the main isolate of +// a Dart program while its isolates use libllamadart. It shows what the exit +// handler of libllamadart costs a Dart VM, which aborts when its isolates run +// while exit() takes its time (docs/v060_2_wrapper_rebuild.md). +// +// g++ -std=c++17 -shared -fPIC -Ithird_party/llama.cpp/include \ +// -Ithird_party/llama.cpp/ggml/include \ +// tests/manual/dart_exit_probe_shim.cpp -o libshim.so +// dart tests/manual/dart_exit_probe.dart libshim.so \ +// +// +// holds libllamadart.so and the backend modules. A run is clean +// when it prints EXIT_PROBE_REACHED and exits with code 0. Append -slow-exit +// to a scenario for a host whose own exit handler takes 300 ms, or +// -late-slow-exit to a generating one for a handler that was registered after +// the one of libllamadart. +import 'dart:async'; +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:isolate'; + +typedef _OpenLibN = Int32 Function(Pointer); +typedef _OpenLibD = int Function(Pointer); +typedef _OpenSesN = Pointer Function(Pointer, Int32); +typedef _OpenSesD = Pointer Function(Pointer, int); +typedef _StepN = Int32 Function(Pointer); +typedef _StepD = int Function(Pointer); + +final _malloc = DynamicLibrary.process() + .lookupFunction< + Pointer Function(IntPtr), + Pointer Function(int) + >('malloc'); + +Pointer _cstr(String s) { + final bytes = utf8.encode(s); + final p = _malloc(bytes.length + 1); + for (var i = 0; i < bytes.length; i++) { + p[i] = bytes[i]; + } + p[bytes.length] = 0; + return p; +} + +Never _cExit() { + stdout.writeln('EXIT_PROBE_REACHED'); + DynamicLibrary.process() + .lookupFunction('exit')(0); + throw StateError('C exit returned'); +} + +void _spin(SendPort ready) { + var rounds = 0; + final bytes = utf8.encode('some text to decode, again and again'); + while (true) { + if (utf8.decode(bytes).isEmpty) throw StateError('unreachable'); + if (++rounds == 100) ready.send(null); + } +} + +// An isolate that wakes every 5 ms and allocates a little, as an app with a +// heartbeat or an animation does. +void _tick(SendPort ready) { + var ticks = 0; + final bytes = utf8.encode('tick'); + Timer.periodic(const Duration(milliseconds: 5), (_) { + final junk = List.generate(2000, (i) => utf8.decode(bytes)); + if (junk.isEmpty) throw StateError('unreachable'); + if (++ticks == 3) ready.send(null); + }); +} + +// Generates as llamadart does: one guarded native step, then Dart work. +void _generate((SendPort, String, String, String, int) a) { + final (ready, shimPath, bundle, model, tokens) = a; + final shim = DynamicLibrary.open(shimPath); + shim.lookupFunction<_OpenLibN, _OpenLibD>('shim_open_library')(_cstr(bundle)); + final session = shim.lookupFunction<_OpenSesN, _OpenSesD>( + 'shim_open_session', + )(_cstr(model), tokens); + final step = shim.lookupFunction<_StepN, _StepD>('shim_step'); + final bytes = utf8.encode('token text'); + var steps = 0; + while (true) { + final status = step(session); + if (status != 0) { + stderr.writeln('PROBE_STEP_STATUS $status'); + } + for (var i = 0; i < 200; i++) { + if (utf8.decode(bytes).isEmpty) throw StateError('unreachable'); + } + if (++steps == 3) ready.send(null); + } +} + +// Runs four steps, reports, then stays idle: llamadart's worker after a +// generation that finished. +void _generateThenIdle((SendPort, String, String, String, int) a) { + final (ready, shimPath, bundle, model, tokens) = a; + final shim = DynamicLibrary.open(shimPath); + shim.lookupFunction<_OpenLibN, _OpenLibD>('shim_open_library')(_cstr(bundle)); + final session = shim.lookupFunction<_OpenSesN, _OpenSesD>( + 'shim_open_session', + )(_cstr(model), tokens); + final step = shim.lookupFunction<_StepN, _StepD>('shim_step'); + for (var i = 0; i < 4; i++) { + step(session); + } + final keepAlive = ReceivePort(); + ready.send(keepAlive.sendPort); +} + +Future main(List args) async { + final [shimPath, bundle, requested, model] = args; + final shim = DynamicLibrary.open(shimPath); + final openLib = shim.lookupFunction<_OpenLibN, _OpenLibD>( + 'shim_open_library', + ); + final openSession = shim.lookupFunction<_OpenSesN, _OpenSesD>( + 'shim_open_session', + ); + final step = shim.lookupFunction<_StepN, _StepD>('shim_step'); + final sleepingAtexit = shim + .lookupFunction( + 'shim_sleeping_atexit', + ); + Future spin() async { + final ready = ReceivePort(); + await Isolate.spawn(_spin, ready.sendPort); + await ready.first; + } + + // A scenario with -slow-exit appended has an exit handler that takes 300 ms. + // It is registered before libllamadart is opened, and so runs after the + // handler of libllamadart. + // With -late-slow-exit the handler is registered right before the exit + // instead, and so runs before the handler of libllamadart. + const slowExit = '-slow-exit'; + const lateSlowExit = '-late-slow-exit'; + final late = requested.endsWith(lateSlowExit); + final scenario = late + ? requested.substring(0, requested.length - lateSlowExit.length) + : requested.endsWith(slowExit) + ? requested.substring(0, requested.length - slowExit.length) + : requested; + if (!late && scenario != requested) sleepingAtexit(300); + + switch (scenario) { + case 'control-spin': // no native library at all + await spin(); + _cExit(); + case 'idle-spin': // model idle for longer than the settle time + openLib(_cstr(bundle)); + final s = openSession(_cstr(model), 8); + step(s); + await spin(); + sleep(const Duration(milliseconds: 400)); + _cExit(); + case 'settle-spin': // exit right after a guarded call ended + openLib(_cstr(bundle)); + final s = openSession(_cstr(model), 8); + await spin(); + step(s); + _cExit(); + case 'generating': // worker isolate alternates guarded calls and Dart + case 'generating-spin': + case 'long-decode-spin': + final ready = ReceivePort(); + await Isolate.spawn(_generate, ( + ready.sendPort, + shimPath, + bundle, + model, + scenario == 'long-decode-spin' ? 1500 : 8, + )); + if (scenario == 'long-decode-spin') { + await spin(); + sleep(const Duration(milliseconds: 300)); + } else { + await ready.first; + if (scenario == 'generating-spin') await spin(); + } + if (late) sleepingAtexit(300); + _cExit(); + case 'loaded-worker-idle': // llamadart's quit-loaded shape + case 'loaded-worker-idle-timer': // the same with a periodic timer in main's group + case 'loaded-worker-idle-spin': + final ready = ReceivePort(); + await Isolate.spawn(_generateThenIdle, ( + ready.sendPort, + shimPath, + bundle, + model, + 8, + )); + if (scenario == 'loaded-worker-idle-spin') await spin(); + if (scenario == 'loaded-worker-idle-timer') { + final ticking = ReceivePort(); + await Isolate.spawn(_tick, ticking.sendPort); + await ticking.first; + } + await ready.first; + _cExit(); + case 'dart-io-exit-generating': // dart:io exit() + final ready = ReceivePort(); + await Isolate.spawn(_generate, ( + ready.sendPort, + shimPath, + bundle, + model, + 8, + )); + await ready.first; + stdout.writeln('EXIT_PROBE_REACHED'); + exit(0); + case 'return-generating': // main returns while a worker generates + final ready = ReceivePort(); + final iso = await Isolate.spawn(_generate, ( + ready.sendPort, + shimPath, + bundle, + model, + 8, + )); + await ready.first; + stdout.writeln('EXIT_PROBE_REACHED'); + ready.close(); + iso.kill(priority: Isolate.immediate); + default: + throw ArgumentError.value(scenario); + } +} diff --git a/tests/manual/dart_exit_probe_shim.cpp b/tests/manual/dart_exit_probe_shim.cpp new file mode 100644 index 00000000..481623dc --- /dev/null +++ b/tests/manual/dart_exit_probe_shim.cpp @@ -0,0 +1,103 @@ +// libllamadart behind functions that tests/manual/dart_exit_probe.dart can +// bind without the structures of llama.h. +#include "llama.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +extern "C" { +llama_model *llama_dart_model_load_from_file(const char *, llama_model_params); +llama_context *llama_dart_init_from_model(llama_model *, llama_context_params); +int32_t llama_dart_decode(llama_context *, llama_batch); +llama_token llama_dart_sampler_sample(llama_sampler *, llama_context *, int32_t); +void llama_dart_set_log_level(int); +void llama_dart_exit_free(void *); +} +static void *g_lib; +static std::atomic active_calls{0}; +static std::atomic free_count{0}; +template static F *sym(const char *n) { + void *s = dlsym(g_lib, n); + if (!s) { fprintf(stderr, "missing %s\n", n); _Exit(3); } + return reinterpret_cast(s); +} +#define BIND(name) auto *name##_ = sym(#name) +struct shim_session { llama_model *model; llama_context *ctx; llama_sampler *sampler; std::vector tokens; }; +extern "C" { +int shim_open_library(const char *bundle) { + if (g_lib) return 0; + g_lib = dlopen((std::string(bundle) + "/libllamadart.so").c_str(), RTLD_LAZY); + if (!g_lib) { fprintf(stderr, "dlopen: %s\n", dlerror()); return 1; } + BIND(llama_dart_set_log_level); BIND(llama_backend_init); BIND(ggml_backend_load_all_from_path); + llama_dart_set_log_level_(4); llama_backend_init_(); ggml_backend_load_all_from_path_(bundle); + return 0; +} +void *shim_open_session(const char *model, int tokens) { + BIND(llama_model_default_params); BIND(llama_dart_model_load_from_file); + BIND(llama_context_default_params); BIND(llama_dart_init_from_model); + BIND(llama_sampler_chain_default_params); BIND(llama_sampler_chain_init); + BIND(llama_sampler_chain_add); BIND(llama_sampler_init_greedy); + auto *s = new shim_session; + auto mp = llama_model_default_params_(); + const char *g = getenv("PROBE_GPU_LAYERS"); + mp.n_gpu_layers = g ? atoi(g) : 0; + s->model = llama_dart_model_load_from_file_(model, mp); + if (!s->model) return nullptr; + auto cp = llama_context_default_params_(); + cp.n_ctx = 2048; cp.n_batch = 2048; cp.n_threads = 3; cp.n_threads_batch = 3; + s->ctx = llama_dart_init_from_model_(s->model, cp); + if (!s->ctx) return nullptr; + s->sampler = llama_sampler_chain_init_(llama_sampler_chain_default_params_()); + llama_sampler_chain_add_(s->sampler, llama_sampler_init_greedy_()); + for (int i = 0; i < tokens; ++i) s->tokens.push_back(100 + i % 400); + return s; +} +// One generation step: guarded decode, then guarded sample. +int shim_step(void *session) { + struct active_guard { active_guard() { ++active_calls; } ~active_guard() { --active_calls; } } guard; + const char *delay = getenv("PROBE_STEP_DELAY_MS"); + if (delay) { fprintf(stderr, "NATIVE_STEP_STARTED\n"); std::this_thread::sleep_for(std::chrono::milliseconds(atoi(delay))); } + BIND(llama_get_memory); BIND(llama_memory_clear); BIND(llama_dart_decode); + BIND(llama_dart_sampler_sample); BIND(llama_batch_get_one); + auto *s = static_cast(session); + llama_memory_clear_(llama_get_memory_(s->ctx), true); + int status = llama_dart_decode_(s->ctx, llama_batch_get_one_(s->tokens.data(), (int32_t)s->tokens.size())); + if (status != 0) return status; + llama_dart_sampler_sample_(s->sampler, s->ctx, -1); + return 0; +} +void shim_sleeping_atexit(int ms) { + static int delay; delay = ms; + atexit([] { std::this_thread::sleep_for(std::chrono::milliseconds(delay)); }); +} + +int shim_free_count() { return free_count.load(); } +int shim_active_calls() { return active_calls.load(); } +void shim_register_host() { + atexit([] { + fprintf(stderr, "HOST_HANDLER_STARTED\n"); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + fprintf(stderr, "HOST_HANDLER_COMPLETED\n"); + }); +} +void shim_buffer_output() { + static char buffer[4096]; + setvbuf(stdout, buffer, _IOFBF, sizeof(buffer)); + fputs("C_BUFFERED_PAYLOAD\n", stdout); +} +void shim_close_session(void *session) { + BIND(llama_sampler_free); BIND(llama_dart_exit_free); + auto *s = static_cast(session); + llama_sampler_free_(s->sampler); + llama_dart_exit_free_(s->ctx); + llama_dart_exit_free_(s->model); + delete s; + ++free_count; + fprintf(stderr, "NATIVE_SESSION_FREE_COMPLETED\n"); +} +} diff --git a/tests/manual/dart_host_shutdown_probe.dart b/tests/manual/dart_host_shutdown_probe.dart new file mode 100644 index 00000000..6b226fcc --- /dev/null +++ b/tests/manual/dart_host_shutdown_probe.dart @@ -0,0 +1,163 @@ +// Manual Linux host-shutdown probe. Build dart_exit_probe_shim.cpp as described +// in dart_exit_probe.dart, then run with PROBE_STEP_DELAY_MS=300: +// dart tests/manual/dart_host_shutdown_probe.dart +// cooperative-finalizer-slow-native verifies a native call is active before +// kill, all worker exits / finalizers complete, and normal C exit preserves +// the earlier host callback and buffered output. raw-control is the known +// Dart VM diagnostic; cooperative-control requires no native bundle. +import 'dart:async'; +import 'dart:convert'; +import 'dart:ffi'; +import 'dart:io'; +import 'dart:isolate'; + +typedef _OpenLibN = Int32 Function(Pointer); +typedef _OpenLibD = int Function(Pointer); +typedef _OpenSesN = Pointer Function(Pointer, Int32); +typedef _OpenSesD = Pointer Function(Pointer, int); +typedef _StepN = Int32 Function(Pointer); +typedef _StepD = int Function(Pointer); + +final _malloc = DynamicLibrary.process() + .lookupFunction< + Pointer Function(IntPtr), + Pointer Function(int) + >('malloc'); + +Pointer _cstr(String s) { + final bytes = utf8.encode(s); + final p = _malloc(bytes.length + 1); + for (var i = 0; i < bytes.length; i++) { + p[i] = bytes[i]; + } + p[bytes.length] = 0; + return p; +} + +Never _cExit() { + stdout.writeln('EXIT_PROBE_REACHED'); + DynamicLibrary.process() + .lookupFunction('exit')(0); + throw StateError('C exit returned'); +} + +void _spin(SendPort ready) { + var rounds = 0; + final bytes = utf8.encode('some text to decode, again and again'); + while (true) { + if (utf8.decode(bytes).isEmpty) throw StateError('unreachable'); + if (++rounds == 100) ready.send(null); + } +} + +// Generates as llamadart does: one guarded native step, then Dart work. +final class _ProbeAnchor implements Finalizable {} + +final _anchors = []; +final _finalizers = []; + +void _generate((SendPort, String, String, String, int) a) { + final (ready, shimPath, bundle, model, tokens) = a; + final shim = DynamicLibrary.open(shimPath); + shim.lookupFunction<_OpenLibN, _OpenLibD>('shim_open_library')(_cstr(bundle)); + final session = shim.lookupFunction<_OpenSesN, _OpenSesD>( + 'shim_open_session', + )(_cstr(model), tokens); + final anchor = _ProbeAnchor(); + final finalizer = NativeFinalizer( + shim.lookup)>>( + 'shim_close_session', + ), + ); + _anchors.add(anchor); + _finalizers.add(finalizer); + finalizer.attach(anchor, session); + final step = shim.lookupFunction<_StepN, _StepD>('shim_step'); + final bytes = utf8.encode('token text'); + var steps = 0; + while (true) { + final status = step(session); + if (status != 0) { + stderr.writeln('PROBE_STEP_STATUS $status'); + } + for (var i = 0; i < 200; i++) { + if (utf8.decode(bytes).isEmpty) throw StateError('unreachable'); + } + if (++steps == 3) ready.send(session.address); + } +} + +Future main(List args) async { + final [shimPath, bundle, scenario, model] = args; + final shim = DynamicLibrary.open(shimPath); + final registerHost = shim.lookupFunction( + 'shim_register_host', + ); + final bufferOutput = shim.lookupFunction( + 'shim_buffer_output', + ); + final freeCount = shim.lookupFunction( + 'shim_free_count', + ); + final activeCalls = shim.lookupFunction( + 'shim_active_calls', + ); + registerHost(); // Registered before the native bundle; must still run later. + final exited = []; + final stopped = >[]; + final isolates = []; + Future spawnWorker( + void Function(T) entry, + T arg, + ReceivePort ready, + ) async { + final onExit = ReceivePort(); + exited.add(onExit); + stopped.add(onExit.first); + isolates.add(await Isolate.spawn(entry, arg, onExit: onExit.sendPort)); + final value = await ready.first; + ready.close(); + return value; + } + + int? sessionAddress; + if (!scenario.contains('control')) { + final ready = ReceivePort(); + sessionAddress = await spawnWorker(_generate, ( + ready.sendPort, + shimPath, + bundle, + model, + scenario.contains('long') ? 1500 : 8, + ), ready) as int; + } + final spinning = ReceivePort(); + await spawnWorker(_spin, spinning.sendPort, spinning); + if (!scenario.startsWith('raw')) { + if (scenario.contains('slow-native')) { + final deadline = DateTime.now().add(const Duration(seconds: 3)); + while (activeCalls() == 0 && DateTime.now().isBefore(deadline)) { + await Future.delayed(const Duration(milliseconds: 1)); + } + if (activeCalls() == 0) throw StateError('slow native call not active'); + stdout.writeln('NATIVE_ACTIVE_BEFORE_KILL'); + } + final watch = Stopwatch()..start(); + for (final isolate in isolates) { + isolate.kill(priority: Isolate.immediate); + } + await Future.wait(stopped).timeout(const Duration(seconds: 20)); + for (final port in exited) { + port.close(); + } + stdout.writeln('ALL_WORKERS_EXITED ${watch.elapsedMicroseconds}'); + stdout.writeln('NATIVE_CALLS_AFTER_EXIT ${activeCalls()}'); + if (activeCalls() != 0) + throw StateError('native call survived worker exit'); + stdout.writeln('NATIVE_FREE_COUNT_AFTER_EXIT ${freeCount()}'); + if (sessionAddress != null && freeCount() != 1) + throw StateError('native finalizer not completed before onExit'); + } + bufferOutput(); + _cExit(); +} diff --git a/tests/test_llama_cpp_patches.py b/tests/test_llama_cpp_patches.py new file mode 100644 index 00000000..0e4527be --- /dev/null +++ b/tests/test_llama_cpp_patches.py @@ -0,0 +1,245 @@ +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", + "android_markers": [{"library": "libthing.so", "text": "marker " + file}], + }) + 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_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 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_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: + 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']") + 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], []), + 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_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, 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) + 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)) + (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["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/tests/test_validate_exports.py b/tests/test_validate_exports.py index 997468e2..fc8f1fbd 100644 --- a/tests/test_validate_exports.py +++ b/tests/test_validate_exports.py @@ -15,6 +15,26 @@ 0000000000004b20 T _llama_dart_decode """ +# readelf -Ws of an ELF library that imports two functions and has a hidden +# definition of __cxa_atexit in its full symbol table. +READELF_OUTPUT = """\ + +Symbol table '.dynsym' contains 3 entries: + Num: Value Size Type Bind Vis Ndx Name + 1: 0000000000000000 0 FUNC WEAK DEFAULT UND __cxa_finalize@GLIBC_2.17 (2) + 2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND dlsym@GLIBC_2.34 (3) + 3: 0000000000004b20 64 FUNC GLOBAL DEFAULT 12 llama_dart_decode + +Symbol table '.symtab' contains 1 entry: + Num: Value Size Type Bind Vis Ndx Name + 1: 000000000000f900 8 FUNC LOCAL DEFAULT 11 __cxa_atexit +""" + +READELF_IMPORT = ( + ' 4: 0000000000000000 0 FUNC GLOBAL DEFAULT UND ' + '__cxa_atexit@GLIBC_2.17 (2)\n' +) + class ValidateExportsTests(unittest.TestCase): def test_nm_exports_and_imports_are_told_apart(self): @@ -25,7 +45,17 @@ def test_nm_exports_and_imports_are_told_apart(self): validate_exports.imported_symbols_from_nm(NM_OUTPUT), {'__cxa_finalize', 'dlsym'}) - def run_tool(self, nm_output, *arguments, library_bytes=b''): + def test_readelf_imports_are_the_undefined_symbols(self): + self.assertEqual( + validate_exports.imported_symbols_from_readelf(READELF_OUTPUT), + {'__cxa_finalize', 'dlsym'}) + self.assertEqual( + validate_exports.imported_symbols_from_readelf( + READELF_OUTPUT + READELF_IMPORT), + {'__cxa_finalize', 'dlsym', '__cxa_atexit'}) + + def run_tool(self, nm_output, *arguments, library_bytes=b'', + tool_format='nm', symbol='llama_dart_decode'): with tempfile.TemporaryDirectory() as temp: library = Path(temp) / 'libllamadart.dylib' library.write_bytes(library_bytes) @@ -36,10 +66,49 @@ def run_tool(self, nm_output, *arguments, library_bytes=b''): tool.chmod(0o755) return subprocess.run( [sys.executable, str(ROOT / 'tools/validate_exports.py'), - '--format', 'nm', '--tool', str(tool), - '--symbol', 'llama_dart_decode', *arguments, str(library)], + '--format', tool_format, '--tool', str(tool), + '--symbol', symbol, *arguments, str(library)], capture_output=True, text=True) + @unittest.skipIf(sys.platform == 'win32', 'the stand-in nm is a shell script') + def test_forbidden_import_in_readelf_output(self): + # The hidden definition in the symbol table is not an import. + absent = self.run_tool( + READELF_OUTPUT, '--forbid-import', '__cxa_atexit', + tool_format='readelf') + self.assertEqual(absent.returncode, 0, absent.stderr) + + imported = self.run_tool( + READELF_OUTPUT + READELF_IMPORT, '--forbid-import', '__cxa_atexit', + tool_format='readelf') + self.assertEqual(imported.returncode, 1) + self.assertIn('__cxa_atexit', imported.stderr) + + @unittest.skipIf(sys.platform == 'win32', 'the stand-in nm is a shell script') + def test_imports_only_skips_the_required_exports(self): + # A llama.cpp library exports none of the wrapper's functions. + missing = self.run_tool( + READELF_OUTPUT, '--forbid-import', '__cxa_atexit', + tool_format='readelf', symbol='llama_dart_encode') + self.assertEqual(missing.returncode, 1) + self.assertIn('llama_dart_encode', missing.stderr) + + skipped = self.run_tool( + READELF_OUTPUT, '--forbid-import', '__cxa_atexit', '--imports-only', + tool_format='readelf', symbol='llama_dart_encode') + self.assertEqual(skipped.returncode, 0, skipped.stderr) + + imported = self.run_tool( + READELF_OUTPUT + READELF_IMPORT, '--forbid-import', '__cxa_atexit', + '--imports-only', tool_format='readelf') + self.assertEqual(imported.returncode, 1) + self.assertIn('__cxa_atexit', imported.stderr) + + unchecked = self.run_tool( + READELF_OUTPUT, '--imports-only', tool_format='readelf') + self.assertEqual(unchecked.returncode, 2) + self.assertIn('--forbid-import', unchecked.stderr) + @unittest.skipIf(sys.platform == 'win32', 'the stand-in nm is a shell script') def test_forbidden_import_fails_only_when_imported(self): absent = self.run_tool(NM_OUTPUT, '--forbid-import', '__cxa_atexit') diff --git a/tests/validate_linux_artifact_test.py b/tests/validate_linux_artifact_test.py index 79e38d0f..809da6cf 100644 --- a/tests/validate_linux_artifact_test.py +++ b/tests/validate_linux_artifact_test.py @@ -16,6 +16,8 @@ from tools.validate_linux_artifact import ( extract_archive, extract_member_safely, + is_nodelete, + parse_imports, resolve_tool, validate_archive, ) @@ -238,6 +240,142 @@ def test_multi_hop_symlink_cycles_are_rejected(self) -> None: errors, ) + def test_imports_are_the_undefined_dynamic_symbols(self) -> None: + readelf = ( + "Symbol table '.dynsym' contains 4 entries:\n" + " Num: Value Size Type Bind Vis Ndx Name\n" + " 0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND \n" + " 1: 0000000000000000 0 FUNC WEAK DEFAULT UND " + "__cxa_finalize@GLIBC_2.17 (2)\n" + " 2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND " + "__cxa_atexit@GLIBC_2.17 (2)\n" + " 3: 0000000000004b20 64 FUNC GLOBAL DEFAULT 12 " + "llama_decode\n" + ) + self.assertEqual( + parse_imports(readelf, "readelf"), {"__cxa_finalize", "__cxa_atexit"} + ) + objdump = ( + "DYNAMIC SYMBOL TABLE:\n" + "0000000000000000 w DF *UND*\t0000000000000000 (GLIBC_2.17) " + "__cxa_finalize\n" + "0000000000000000 DF *UND*\t0000000000000000 (GLIBC_2.17) " + "__cxa_atexit\n" + "0000000000004b20 g DF .text\t0000000000000040 Base " + "llama_decode\n" + ) + self.assertEqual( + parse_imports(objdump, "objdump"), {"__cxa_finalize", "__cxa_atexit"} + ) + + def test_nodelete_is_read_from_readelf_and_objdump(self) -> None: + self.assertTrue( + is_nodelete(" 0x000000006ffffffb (FLAGS_1) Flags: NODELETE\n") + ) + self.assertTrue( + is_nodelete(" 0x000000006ffffffb (FLAGS_1) Flags: NOW NODELETE\n") + ) + self.assertTrue(is_nodelete(" FLAGS_1 0x0000000000000009\n")) + self.assertFalse(is_nodelete(" FLAGS_1 0x0000000000000001\n")) + self.assertFalse( + is_nodelete(" 0x000000006ffffffb (FLAGS_1) Flags: NOW\n") + ) + self.assertFalse(is_nodelete(" 0x000000000000001e (FLAGS) BIND_NOW\n")) + + @unittest.skipIf(sys.platform == "win32", "the stand-in tool is a shell script") + def test_libllamadart_must_not_be_unloadable(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive_path = root / "runtime.tar.gz" + with tarfile.open(archive_path, "w:gz") as archive: + for name in ("libllamadart.so", "libmtmd.so.0"): + member = tarfile.TarInfo(name) + member.size = 1 + archive.addfile(member, BytesIO(b"x")) + link = tarfile.TarInfo("libmtmd.so") + link.type = tarfile.SYMTYPE + link.linkname = "libmtmd.so.0" + archive.addfile(link) + tool = root / "readelf" + tool.write_text( + "#!/bin/sh\n" + 'if [ "$1" = "-d" ]; then\n' + " printf ' 0x000000000000000e (SONAME) Library soname: [%s]\\n'" + ' "$(basename "$2")"\n' + "fi\n" + ) + tool.chmod(0o755) + + errors = validate_archive(archive_path, str(tool), "readelf") + + self.assertEqual( + errors, + [ + "libllamadart.so: is not linked with -z nodelete, so a dlclose " + "can unload held native objects and finalizer callbacks" + ], + ) + + @unittest.skipIf(sys.platform == "win32", "the stand-in tool is a shell script") + def test_a_local_library_must_not_import_cxa_atexit(self) -> None: + dynamic = ( + " 0x000000000000000e (SONAME) Library soname: [{soname}]\n" + " 0x000000006ffffffb (FLAGS_1) Flags: NODELETE\n" + ) + imported = ( + " 1: 0000000000000000 0 FUNC GLOBAL DEFAULT UND " + "__cxa_atexit@GLIBC_2.17 (2)\n" + ) + defined = ( + " 1: 000000000000f900 8 FUNC LOCAL DEFAULT 11 " + "__cxa_atexit\n" + ) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive_path = root / "runtime.tar.gz" + names = ( + "libllamadart.so", + "libmtmd.so.0", + "libggml-cuda.so", + "libopenblas.so.0", + ) + with tarfile.open(archive_path, "w:gz") as archive: + for name in names: + member = tarfile.TarInfo(name) + member.size = 1 + archive.addfile(member, BytesIO(b"x")) + link = tarfile.TarInfo("libmtmd.so") + link.type = tarfile.SYMTYPE + link.linkname = "libmtmd.so.0" + archive.addfile(link) + + # Answers readelf -d with the file's own name as its SONAME, and + # the symbol listing with the text under test. + symbols = root / "symbols.txt" + tool = root / "readelf" + tool.write_text( + "#!/bin/sh\n" + 'if [ "$1" = "-d" ]; then\n' + f" printf '{dynamic.format(soname='%s')}' \"$(basename \"$2\")\"\n" + "else\n" + f' cat "{symbols}"\n' + "fi\n" + ) + tool.chmod(0o755) + + symbols.write_text(imported) + errors = validate_archive(archive_path, str(tool), "readelf") + self.assertEqual( + errors, + [ + f"{name}: imports __cxa_atexit, so C exit() destroys its statics" + for name in ("libggml-cuda.so", "libllamadart.so", "libmtmd.so.0") + ], + ) + + symbols.write_text(defined) + self.assertEqual(validate_archive(archive_path, str(tool), "readelf"), []) + def test_missing_explicit_tool_reports_a_clean_cli_error(self) -> None: with tempfile.TemporaryDirectory() as directory: missing_tool = Path(directory) / "missing-readelf" diff --git a/tools/llama_cpp_patches.py b/tools/llama_cpp_patches.py new file mode 100644 index 00000000..247c11a5 --- /dev/null +++ b/tools/llama_cpp_patches.py @@ -0,0 +1,270 @@ +#!/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 + + +class NotApplicable(PatchError): + """The patch is well formed but does not fit this upstream source.""" + + +@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") + # 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 at least one " + "{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_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. 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)) + 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 + + +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["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, 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. + 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), skipped + + +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) + 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": + 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: + 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: diff --git a/tools/validate_exports.py b/tools/validate_exports.py index 03f8f0ad..8803c6da 100644 --- a/tools/validate_exports.py +++ b/tools/validate_exports.py @@ -26,6 +26,7 @@ "llama_dart_model_load_from_file", "llama_dart_init_from_model", "llama_dart_mtmd_init_from_file", + "llama_dart_mtmd_supports_image_token_limit", "llama_dart_decode", "llama_dart_encode", "llama_dart_synchronize", @@ -126,7 +127,16 @@ def parse_args() -> argparse.Namespace: default=[], help=( "Symbol the library must not import. Supported for --format nm " - "and single-architecture files." + "on Mach-O and --format readelf on ELF, and for " + "single-architecture files." + ), + ) + parser.add_argument( + "--imports-only", + action="store_true", + help=( + "Check only --forbid-import, for a library that has none of the " + "required exports, such as a llama.cpp library next to the wrapper." ), ) return parser.parse_args() @@ -178,6 +188,15 @@ def exported_symbols_from_readelf(output: str) -> set[str]: return symbols +def imported_symbols_from_readelf(output: str) -> set[str]: + symbols: set[str] = set() + for line in output.splitlines(): + parts = line.split() + if len(parts) >= 8 and parts[6] == "UND": + symbols.add(parts[7].split("@", 1)[0]) + return symbols + + def exported_symbols_from_nm(output: str) -> set[str]: symbols: set[str] = set() for line in output.splitlines(): @@ -216,8 +235,13 @@ def exported_symbols_from_dumpbin(output: str) -> set[str]: def main() -> int: args = parse_args() - if args.forbidden_imports and args.format != "nm": - print("--forbid-import requires --format nm", file=sys.stderr) + # nm names are read as Mach-O ones, without their leading underscore, so + # an ELF import such as __cxa_atexit would never match. + if args.forbidden_imports and args.format not in ("nm", "readelf"): + print("--forbid-import requires --format nm or readelf", file=sys.stderr) + return 2 + if args.imports_only and not args.forbidden_imports: + print("--imports-only requires --forbid-import", file=sys.stderr) return 2 # nm lists only the host architecture of a universal file, so the other # slices would go unchecked. @@ -233,7 +257,9 @@ def main() -> int: "nm": exported_symbols_from_nm, "dumpbin": exported_symbols_from_dumpbin, }[args.format](output) - required = args.symbols or DEFAULT_REQUIRED_SYMBOLS + required = ( + [] if args.imports_only else args.symbols or DEFAULT_REQUIRED_SYMBOLS + ) missing = [symbol for symbol in required if symbol not in exported] if missing: print(f"Missing exports in {args.library}:", file=sys.stderr) @@ -241,7 +267,11 @@ def main() -> int: print(f" - {symbol}", file=sys.stderr) return 1 - imported = imported_symbols_from_nm(output) + imported = ( + imported_symbols_from_readelf(output) + if args.format == "readelf" + else imported_symbols_from_nm(output) + ) forbidden = [s for s in args.forbidden_imports if s in imported] if forbidden: print(f"Forbidden imports in {args.library}:", file=sys.stderr) diff --git a/tools/validate_linux_artifact.py b/tools/validate_linux_artifact.py index 96ab30cf..6a2ec076 100644 --- a/tools/validate_linux_artifact.py +++ b/tools/validate_linux_artifact.py @@ -16,6 +16,12 @@ LOCAL_LIBRARY_PREFIXES = ("libllamadart", "libllama", "libggml", "libmtmd") +# The libraries built here bind __cxa_atexit to a definition of their own: +# libllamadart to the one that runs exit teardown first, the llama.cpp +# libraries to the one that registers no static destructor +# (src/llama_dart_static_destructors.c). One that imports it has its statics +# destroyed by C exit() under the calls in flight. +FORBIDDEN_LOCAL_IMPORTS = ("__cxa_atexit",) PLACEHOLDER = "SOVERSION" MAX_ERROR_DETAIL_LENGTH = 512 TARFILE_EXTRACT_SUPPORTS_FILTER = ( @@ -94,6 +100,39 @@ def inspect_dynamic(path: Path, tool: str, mode: str) -> DynamicMetadata: return DynamicMetadata(soname=soname, needed=tuple(needed), raw=raw) +def is_nodelete(raw: str) -> bool: + """Whether readelf -d or objdump -p output has DF_1_NODELETE set.""" + for line in raw.splitlines(): + if "FLAGS_1" not in line: + continue + if "NODELETE" in line: + return True + match = re.search(r"FLAGS_1\s+(0x[0-9a-fA-F]+)\s*$", line) + if match and int(match.group(1), 16) & 0x8: + return True + return False + + +def parse_imports(raw: str, mode: str) -> set[str]: + imports: set[str] = set() + for line in raw.splitlines(): + parts = line.split() + if mode == "objdump": + if "*UND*" in parts and parts[-1] != "*UND*": + imports.add(parts[-1].split("@", 1)[0]) + elif len(parts) >= 8 and parts[6] == "UND": + imports.add(parts[7].split("@", 1)[0]) + return imports + + +def inspect_imports(path: Path, tool: str, mode: str) -> set[str]: + options = ["-T"] if mode == "objdump" else ["--dyn-syms", "-W"] + result = subprocess.run( + [tool, *options, str(path)], check=True, capture_output=True, text=True + ) + return parse_imports(result.stdout, mode) + + def safe_member_name(name: str) -> str: normalized = name.removeprefix("./") path = PurePosixPath(normalized) @@ -237,6 +276,29 @@ def validate_archive(archive_path: Path, tool: str, mode: str) -> list[str]: for dependency in dynamic.needed: if dependency.startswith(LOCAL_LIBRARY_PREFIXES) and dependency not in names: errors.append(f"{name}: local DT_NEEDED dependency is absent: {dependency}") + # Held objects / finalizer callbacks may outlive dlclose. + # Keep the wrapper together with its owned statics. + if name == "libllamadart.so" and not is_nodelete(dynamic.raw): + errors.append( + f"{name}: is not linked with -z nodelete, so a dlclose " + "can unload held native objects and finalizer callbacks" + ) + if name.startswith(LOCAL_LIBRARY_PREFIXES): + try: + imports = inspect_imports(root / name, tool, mode) + except subprocess.CalledProcessError as error: + errors.append( + f"{name}: symbol inspection failed with exit code {error.returncode}" + ) + continue + except OSError as error: + errors.append(f"{name}: symbol inspection failed: {error}") + continue + for symbol in FORBIDDEN_LOCAL_IMPORTS: + if symbol in imports: + errors.append( + f"{name}: imports {symbol}, so C exit() destroys its statics" + ) mtmd = metadata.get("libmtmd.so") if mtmd is None: