Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions .github/workflows/validate_wrapper.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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: |
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
9 changes: 9 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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/`.

Expand Down
90 changes: 83 additions & 7 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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
$<TARGET_OBJECTS:llamadart_static_destructors>)
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
$<TARGET_OBJECTS:llamadart_static_destructors>)
# 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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand All @@ -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="$<TARGET_FILE:ggml-cpu>")
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}")
Expand All @@ -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
Expand Down Expand Up @@ -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:$<TARGET_FILE_DIR:llama>;LD_LIBRARY_PATH=path_list_prepend:$<TARGET_FILE_DIR:llamadart_lib>")
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()
Expand Down
4 changes: 3 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
30 changes: 23 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
84 changes: 84 additions & 0 deletions cmake/llama_cpp_patches.cmake
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading