From 858513b5b2224ace91feafc431d79b9749c28fe7 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Tue, 1 Dec 2026 18:28:15 -0500 Subject: [PATCH 1/5] Add Linux x64 OpenVINO sidecar and private device API --- .github/CODEOWNERS | 11 + .../actions/openvino-sidecar-build/action.yml | 40 ++ .../actions/openvino-sidecar-pair/action.yml | 24 + .github/workflows/native_release.yml | 65 ++- .../workflows/validate_linux_release_rows.yml | 55 +- .github/workflows/validate_wrapper.yml | 43 +- AGENTS.md | 3 + CMakeLists.txt | 23 + README.md | 4 + cmake/build_identity.cmake | 9 +- cmake/openvino_tests.cmake | 72 +++ docs/build_identity.md | 7 + docs/openvino_sidecar.md | 130 +++++ docs/platform_backend_strategy.md | 4 + scripts/generate_assets_manifest.sh | 2 + scripts/publish_prepared_release.py | 3 +- scripts/release_contract.py | 2 +- scripts/release_publication.py | 2 +- scripts/verify_release_provenance.py | 19 +- src/llama_dart_openvino.cpp | 494 ++++++++++++++++++ src/llama_dart_openvino_identity.h | 77 +++ src/llama_dart_openvino_internal.h | 30 ++ src/llama_dart_openvino_plugins.h | 12 + src/llama_dart_openvino_shim.cpp | 66 +++ src/llama_dart_openvino_test_hooks.h | 8 + src/llama_dart_wrapper.h | 64 +++ tests/fixtures/openvino_abort_sites.txt | 26 + tests/openvino_canary.c | 20 + tests/openvino_diagnosis_test.cpp | 56 ++ tests/openvino_fake_runtime_symbol.c | 5 + tests/openvino_ggml_origin_test.cpp | 27 + tests/openvino_identity_test.cpp | 55 ++ tests/openvino_pair_smoke.cpp | 356 +++++++++++++ tests/openvino_windows_canary.c | 16 + tests/run_openvino_contract.py | 300 +++++++++++ tests/test_assets_manifest.py | 6 + tests/test_ci_scope.py | 2 +- tests/test_linux_backends.py | 7 +- tests/test_linux_release_rows.py | 21 +- tests/test_mutate_embedded_identity.py | 41 ++ tests/test_openvino_env_contract.py | 46 ++ tests/test_openvino_identity_fields.py | 16 + tests/test_openvino_plugins_xml.py | 21 + tests/test_openvino_sdk.py | 50 ++ tests/test_package_openvino_sidecar.py | 58 ++ tests/test_publish_prepared.py | 4 +- tests/test_validate_exports.py | 16 +- tests/test_validate_openvino_sidecar.py | 93 ++++ tools/build.py | 55 +- tools/ci_scope.py | 2 +- tools/mutate_embedded_identity.py | 62 +++ tools/openvino_sdk.py | 94 ++++ tools/package_openvino_sidecar.py | 145 +++++ tools/validate_exports.py | 3 + tools/validate_openvino_sidecar.py | 148 ++++++ 55 files changed, 2989 insertions(+), 31 deletions(-) create mode 100644 .github/actions/openvino-sidecar-build/action.yml create mode 100644 .github/actions/openvino-sidecar-pair/action.yml create mode 100644 cmake/openvino_tests.cmake create mode 100644 docs/openvino_sidecar.md create mode 100644 src/llama_dart_openvino.cpp create mode 100644 src/llama_dart_openvino_identity.h create mode 100644 src/llama_dart_openvino_internal.h create mode 100644 src/llama_dart_openvino_plugins.h create mode 100644 src/llama_dart_openvino_shim.cpp create mode 100644 src/llama_dart_openvino_test_hooks.h create mode 100644 tests/fixtures/openvino_abort_sites.txt create mode 100644 tests/openvino_canary.c create mode 100644 tests/openvino_diagnosis_test.cpp create mode 100644 tests/openvino_fake_runtime_symbol.c create mode 100644 tests/openvino_ggml_origin_test.cpp create mode 100644 tests/openvino_identity_test.cpp create mode 100644 tests/openvino_pair_smoke.cpp create mode 100644 tests/openvino_windows_canary.c create mode 100644 tests/run_openvino_contract.py create mode 100644 tests/test_mutate_embedded_identity.py create mode 100644 tests/test_openvino_env_contract.py create mode 100644 tests/test_openvino_identity_fields.py create mode 100644 tests/test_openvino_plugins_xml.py create mode 100644 tests/test_openvino_sdk.py create mode 100644 tests/test_package_openvino_sidecar.py create mode 100644 tests/test_validate_openvino_sidecar.py create mode 100644 tools/mutate_embedded_identity.py create mode 100644 tools/openvino_sdk.py create mode 100644 tools/package_openvino_sidecar.py create mode 100644 tools/validate_openvino_sidecar.py diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 6c31d2f3..fde2213e 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -11,3 +11,14 @@ /.github/workflows/windows_consumer_qualification.yml @leehack /tools/qualification/windows_consumer/ @leehack /tests/test_windows_consumer_qualification.py @leehack +/.github/actions/openvino-sidecar-*/ @leehack +/.github/workflows/validate_linux_release_rows.yml @leehack +/cmake/openvino_tests.cmake @leehack +/docs/openvino_sidecar.md @leehack +/scripts/generate_assets_manifest.sh @leehack +/scripts/release_contract.py @leehack +/scripts/release_publication.py @leehack +/src/llama_dart_openvino* @leehack +/tools/openvino_sdk.py @leehack +/tools/package_openvino_sidecar.py @leehack +/tools/validate_openvino_sidecar.py @leehack diff --git a/.github/actions/openvino-sidecar-build/action.yml b/.github/actions/openvino-sidecar-build/action.yml new file mode 100644 index 00000000..c3b518be --- /dev/null +++ b/.github/actions/openvino-sidecar-build/action.yml @@ -0,0 +1,40 @@ +name: Build the Linux x64 OpenVINO sidecar +description: Build, package and validate the sidecar against the pinned SDK +inputs: + tag: + description: Native release tag used in the archive name + required: true +outputs: + sdk: + description: Path to the extracted, verified SDK + value: ${{ steps.sdk.outputs.path }} +runs: + using: composite + steps: + - name: Install build dependencies + shell: bash + run: | + . tools/apt_retry.sh + apt_get_update + apt_get_install ninja-build ccache binutils + - name: Fetch the pinned OpenVINO SDK and OpenCL C++ headers + id: sdk + shell: bash + run: | + sdk="$(python3 tools/openvino_sdk.py --output "$RUNNER_TEMP/openvino-sdk" --with-opencl-headers)" + echo "path=$sdk" >> "$GITHUB_OUTPUT" + - name: Build and validate the owner sidecar + shell: bash + env: + SDK: ${{ steps.sdk.outputs.path }} + NATIVE_TAG: ${{ inputs.tag }} + run: | + time python3 tools/build.py linux --arch x64 --backend openvino --openvino-sdk "$SDK" --jobs "$(nproc)" + archive="openvino-payload/llamadart-native-linux-x64-openvino-$NATIVE_TAG.tar.gz" + directory=build/linux-x64-openvino/openvino-payload + python3 tools/package_openvino_sidecar.py \ + --build-dir bin/linux/x64/openvino --sdk "$SDK" --directory "$directory" --output "$archive" + python3 tools/validate_openvino_sidecar.py "$directory" --sdk "$SDK" + stat --printf='%n %s bytes\n' "$directory"/libllamadart-openvino.so "$archive" + readelf -d "$directory/libllamadart-openvino.so" + python3 tools/check_glibc_floor.py "$directory" diff --git a/.github/actions/openvino-sidecar-pair/action.yml b/.github/actions/openvino-sidecar-pair/action.yml new file mode 100644 index 00000000..1f47453a --- /dev/null +++ b/.github/actions/openvino-sidecar-pair/action.yml @@ -0,0 +1,24 @@ +name: Test the packaged Linux x64 OpenVINO pair +description: Pair the release Vulkan core and independently built OpenVINO sidecar +runs: + using: composite + steps: + - name: Download the release Linux x64 Vulkan core + uses: actions/download-artifact@v8 + with: + name: native_linux_x64_vulkan + path: openvino-pair-input/core + - name: Download the release OpenVINO sidecar + uses: actions/download-artifact@v8 + with: + name: sidecar_linux_x64_openvino + path: openvino-pair-input/sidecar + - name: Validate and run the pair with origin and identity controls + shell: bash + run: | + sdk="$(python3 tools/openvino_sdk.py --output "$RUNNER_TEMP/openvino-sdk")" + shopt -s nullglob + sidecars=(openvino-pair-input/sidecar/*.tar.gz) + [ "${#sidecars[@]}" = 1 ] + python3 tests/run_openvino_contract.py --scratch "$RUNNER_TEMP/openvino-pair" --sdk "$sdk" \ + --core-archive openvino-pair-input/core/runtime.tar.gz --sidecar-archive "${sidecars[0]}" diff --git a/.github/workflows/native_release.yml b/.github/workflows/native_release.yml index d73b6d7e..04bf92a0 100644 --- a/.github/workflows/native_release.yml +++ b/.github/workflows/native_release.yml @@ -1071,6 +1071,61 @@ jobs: C:\vcpkg\installed key: vcpkg-${{ runner.os }}-${{ matrix.vcpkg_triplet }}-${{ env.VCPKG_CACHE_VERSION }} + build-linux-openvino: + needs: [resolve-tag] + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + submodules: recursive + persist-credentials: false + - name: Checkout llama.cpp ref + uses: ./.github/actions/checkout-llama-ref + with: + tag: ${{ needs.resolve-tag.outputs.llama_cpp_ref }} + expected_commit: ${{ needs.resolve-tag.outputs.llama_cpp_commit }} + github_token: ${{ github.token }} + - name: Checkout exact release source + uses: ./.github/actions/checkout-native-source + with: + native_commit: ${{ needs.resolve-tag.outputs.native_commit }} + llama_cpp_commit: ${{ needs.resolve-tag.outputs.llama_cpp_commit }} + - name: Build the pinned OpenVINO sidecar + uses: ./.github/actions/openvino-sidecar-build + with: + tag: ${{ needs.resolve-tag.outputs.release_tag }} + - name: Upload the OpenVINO sidecar + uses: actions/upload-artifact@v7 + with: + name: sidecar_linux_x64_openvino + path: openvino-payload/*.tar.gz + if-no-files-found: error + + openvino-sidecar-pair: + needs: [resolve-tag, build-linux, build-linux-openvino] + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + submodules: recursive + persist-credentials: false + - name: Checkout llama.cpp ref + uses: ./.github/actions/checkout-llama-ref + with: + tag: ${{ needs.resolve-tag.outputs.llama_cpp_ref }} + expected_commit: ${{ needs.resolve-tag.outputs.llama_cpp_commit }} + github_token: ${{ github.token }} + - name: Checkout exact release source + uses: ./.github/actions/checkout-native-source + with: + native_commit: ${{ needs.resolve-tag.outputs.native_commit }} + llama_cpp_commit: ${{ needs.resolve-tag.outputs.llama_cpp_commit }} + - uses: ./.github/actions/openvino-sidecar-pair + smoke-release-contract: needs: [resolve-tag, build-linux] runs-on: ubuntu-latest @@ -1106,7 +1161,7 @@ jobs: fi package-and-release: - needs: [resolve-tag, build-android, build-apple, metal-os-floor, build-linux, build-linux-hip, build-windows, smoke-release-contract] + needs: [resolve-tag, build-android, build-apple, metal-os-floor, build-linux, build-linux-hip, build-windows, smoke-release-contract, openvino-sidecar-pair] runs-on: macos-latest outputs: native_commit: ${{ needs.resolve-tag.outputs.native_commit }} @@ -1187,6 +1242,13 @@ jobs: fi done + if [ -n "$(find bundles/linux-x64 -iname '*openvino*' -print -quit)" ]; then + echo "OpenVINO belongs in the sidecar, not in the Linux x64 core" >&2 + exit 1 + fi + openvino_archive="llamadart-native-linux-x64-openvino-${{ needs.resolve-tag.outputs.release_tag }}.tar.gz" + cp "artifacts/sidecar_linux_x64_openvino/$openvino_archive" "release_assets/$openvino_archive" + for bundle_dir in bundles/windows-*; do [ -d "$bundle_dir" ] || continue python3 tools/package_windows_runtime.py install --arch "${bundle_dir##*/windows-}" "$bundle_dir" artifacts @@ -1238,6 +1300,7 @@ jobs: tar -czf "release_assets/${HEADER_ARCHIVE}" -C headers_bundle libllamadart llama_cpp for archive in release_assets/llamadart-native-linux-*.tar.gz; do + [ "${archive##*/}" != "$openvino_archive" ] || continue python3 tools/validate_linux_artifact.py "$archive" done diff --git a/.github/workflows/validate_linux_release_rows.yml b/.github/workflows/validate_linux_release_rows.yml index d45c5c6f..22b71ca9 100644 --- a/.github/workflows/validate_linux_release_rows.yml +++ b/.github/workflows/validate_linux_release_rows.yml @@ -1,7 +1,7 @@ name: Validate Linux Release Rows -# native_release.yml's Linux jobs without their upload, because the release runs -# only when dispatched and #132 went unnoticed until one failed. +# Exercise the Linux release jobs on pull requests. Only the packaged OpenVINO +# pair uploads temporary artifacts. # tests/test_linux_release_rows.py fails when the two differ. on: pull_request: @@ -15,6 +15,15 @@ on: - third_party/llama.cpp - tools/apt_retry.sh - tools/build.py + - tools/openvino_sdk.py + - tools/package_openvino_sidecar.py + - tools/validate_openvino_sidecar.py + - tools/mutate_embedded_identity.py + - src/llama_dart_openvino* + - src/llama_dart_wrapper.h + - tests/*openvino* + - third_party/OpenCL-Headers + - third_party/OpenCL-ICD-Loader - tools/check_glibc_floor.py - tools/check_linux_arm64_cpu_variants.sh - tools/docker/** @@ -270,6 +279,15 @@ jobs: QEMU_SYSROOT: /usr/aarch64-linux-gnu run: tools/check_linux_arm64_cpu_variants.sh "${RUNNER_TEMP}/llamadart-clean-arm64" + - name: Upload the x64 Vulkan core + if: matrix.arch == 'x64' && matrix.backend == 'vulkan' + uses: actions/upload-artifact@v7 + with: + name: native_linux_x64_vulkan + path: artifact_payload/runtime.tar.gz + if-no-files-found: error + retention-days: 1 + build-linux-hip: runs-on: ubuntu-latest container: rocm/dev-ubuntu-22.04:6.3.4 @@ -357,3 +375,36 @@ jobs: --output "$PAYLOAD/runtime.tar.gz" \ --pattern "libggml-hip.so" ls -la "$PAYLOAD" + + build-linux-openvino: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + submodules: recursive + persist-credentials: false + - name: Build the pinned OpenVINO sidecar + uses: ./.github/actions/openvino-sidecar-build + with: + tag: candidate + - name: Upload the OpenVINO sidecar + uses: actions/upload-artifact@v7 + with: + name: sidecar_linux_x64_openvino + path: openvino-payload/*.tar.gz + if-no-files-found: error + retention-days: 1 + + openvino-sidecar-pair: + needs: [build-linux, build-linux-openvino] + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + submodules: recursive + persist-credentials: false + - uses: ./.github/actions/openvino-sidecar-pair diff --git a/.github/workflows/validate_wrapper.yml b/.github/workflows/validate_wrapper.yml index aa57eb4c..3eb2dedb 100644 --- a/.github/workflows/validate_wrapper.yml +++ b/.github/workflows/validate_wrapper.yml @@ -470,6 +470,43 @@ jobs: QEMU_SYSROOT: /usr/aarch64-linux-gnu run: tools/check_linux_arm64_cpu_variants.sh "${RUNNER_TEMP}/llamadart-clean-arm64" + openvino-sidecar-contract: + needs: changes + if: needs.changes.outputs.native == 'true' + runs-on: ubuntu-24.04 + timeout-minutes: 30 + strategy: + matrix: + upstream: ${{ fromJSON(needs.changes.outputs.upstreams) }} + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + submodules: recursive + persist-credentials: false + - name: Select candidate upstream + if: matrix.upstream != needs.changes.outputs.pinned + env: + LLAMADART_QUALIFICATION_SHA: ${{ fromJSON(env.LLAMADART_UPSTREAMS)[matrix.upstream] }} + run: | + git -C third_party/llama.cpp fetch --depth=1 origin "$LLAMADART_QUALIFICATION_SHA" + git -C third_party/llama.cpp checkout --detach "$LLAMADART_QUALIFICATION_SHA" + test "$(git -C third_party/llama.cpp rev-parse HEAD)" = "$LLAMADART_QUALIFICATION_SHA" + - name: Build the pinned OpenVINO sidecar + uses: ./.github/actions/openvino-sidecar-build + with: + tag: candidate + - name: Build the OpenVINO contract tests + run: | + build=build/linux-x64-openvino + cmake -S . -B "$build" -DLLAMADART_BUILD_TESTS=ON + cmake --build "$build" --parallel "$(nproc)" --target \ + llamadart_openvino_api_test llamadart_openvino_identity_test llamadart_openvino_diagnosis_test + - name: Run the OpenVINO contract tests + run: ctest --test-dir build/linux-x64-openvino -R llamadart_openvino --output-on-failure + - name: Validate the OpenVINO build and package tools + run: python3 -m unittest discover -s tests -p 'test_*openvino*.py' + wrapper-contract: needs: changes if: needs.changes.outputs.native == 'true' @@ -526,6 +563,7 @@ jobs: llamadart_f16_dot_accumulation_test llamadart_speculative_api_test llamadart_build_identity_test llamadart_upstream_abi_test + llamadart_openvino_identity_test llamadart_cancel_flag_test llamadart_tts_api_test llamadart_tts_types_test @@ -659,6 +697,7 @@ jobs: llamadart_owner_api_test llamadart_owner_reentrancy_test llamadart_file_sha256_test llamadart_model_fd_test llamadart_build_identity_test llamadart_upstream_abi_test + llamadart_openvino_api_test llamadart_openvino_identity_test llamadart_cancel_flag_test llamadart_exit_teardown_test llamadart_vulkan_device_info_test @@ -676,7 +715,7 @@ jobs: $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 "owner_api|owner_reentrant|file_sha256|model_fd|barrier|build_identity|upstream_abi|cancel_flag|vocabulary|reasoning-budget|vulkan_device_info|device_memory|fit_api|tts_api|tts_types|asr_stream|tts_stream|image_token_limit" --timeout 120 --output-on-failure + ctest --test-dir build/wx64 -R "owner_api|owner_reentrant|file_sha256|model_fd|barrier|build_identity|openvino|upstream_abi|cancel_flag|vocabulary|reasoning-budget|vulkan_device_info|device_memory|fit_api|tts_api|tts_types|asr_stream|tts_stream|image_token_limit" --timeout 120 --output-on-failure - name: Validate wrapper exports shell: pwsh run: | @@ -794,7 +833,7 @@ jobs: wrapper-validation: if: always() - needs: [changes, android-arm64-isa, android-vulkan-shaders, kleidiai-dispatch-emulated, windows-arm64-kleidiai, windows-arm64-vulkan, windows-x64-runtime-closure, linux-artifact-contract, wrapper-contract, msvc-mtmd-link-contract, macos-exit-teardown] + needs: [changes, android-arm64-isa, android-vulkan-shaders, kleidiai-dispatch-emulated, windows-arm64-kleidiai, windows-arm64-vulkan, windows-x64-runtime-closure, linux-artifact-contract, openvino-sidecar-contract, wrapper-contract, msvc-mtmd-link-contract, macos-exit-teardown] runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 diff --git a/AGENTS.md b/AGENTS.md index 9ec2fb8a..4f471379 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -108,6 +108,9 @@ there. It dispatches `native_release.yml` for an exact unbuilt stable release and never publishes assets or mutates the repository itself. +See `docs/openvino_sidecar.md` for the Linux x64 OpenVINO sidecar contract, +packaged pair checks and Intel NPU qualification. + ## CI Triage - A cancelled job with no runner name and no steps never ran. Read diff --git a/CMakeLists.txt b/CMakeLists.txt index dc2df5b9..217f0977 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -318,12 +318,33 @@ endif() add_library(llamadart_lib SHARED "src/llama_dart_wrapper.cpp" "src/llama_dart_build_identity.cpp" + "src/llama_dart_openvino.cpp" "src/llama_dart_file_sha256.cpp" "src/llama_dart_image_token_limit.cpp" "src/llama_dart_device_memory.cpp" "src/llama_dart_vulkan_device_info.cpp") include(cmake/build_identity.cmake) llamadart_add_build_identity(llamadart_lib) +if (TARGET ggml-openvino) + if (NOT CMAKE_SYSTEM_NAME STREQUAL "Linux" OR + NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64)$" OR + NOT GGML_BACKEND_DL OR NOT LLAMADART_OPENVINO_RUNTIME_BUILD OR + NOT LLAMADART_OPENCL_CPP_HEADERS) + message(FATAL_ERROR "OpenVINO needs a Linux x64 module build with the pinned SDK from tools/build.py") + endif() + target_sources(ggml-openvino PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src/llama_dart_openvino_shim.cpp") + target_include_directories(ggml-openvino PRIVATE + third_party/llama.cpp/include third_party/llama.cpp/ggml/src/ggml-openvino) + target_include_directories(ggml-openvino SYSTEM PRIVATE "${LLAMADART_OPENCL_CPP_HEADERS}") + target_compile_definitions(ggml-openvino PRIVATE + LLAMADART_OPENVINO_RUNTIME_BUILD="${LLAMADART_OPENVINO_RUNTIME_BUILD}") + llamadart_use_build_identity(ggml-openvino) + target_link_options(ggml-openvino PRIVATE "LINKER:--disable-new-dtags") + set_target_properties(ggml-openvino PROPERTIES + OUTPUT_NAME llamadart-openvino + BUILD_WITH_INSTALL_RPATH ON + INSTALL_RPATH "$ORIGIN") +endif() if (CMAKE_SYSTEM_NAME STREQUAL "Linux") target_sources(llamadart_lib PRIVATE $) @@ -391,6 +412,7 @@ set_target_properties(llamadart_lib PROPERTIES target_include_directories(llamadart_lib PRIVATE third_party/llama.cpp/include + third_party/llama.cpp/ggml/src third_party/llama.cpp/src third_party/llama.cpp/common src @@ -399,6 +421,7 @@ target_include_directories(llamadart_lib PRIVATE if (LLAMADART_BUILD_TESTS) enable_testing() target_compile_definitions(llamadart_lib PRIVATE LLAMADART_TESTING=1) + include(cmake/openvino_tests.cmake) add_executable(llamadart_f16_dot_accumulation_test tests/f16_dot_accumulation_test.cpp) target_compile_features(llamadart_f16_dot_accumulation_test PRIVATE cxx_std_17) target_compile_definitions(llamadart_f16_dot_accumulation_test PRIVATE diff --git a/README.md b/README.md index a674104c..56e009fc 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,10 @@ Native build and release pipeline for `llamadart` binaries. +Linux x64 has an opt-in [OpenVINO NPU sidecar](docs/openvino_sidecar.md). +Intel NPU support is experimental and unqualified. Applications that bundle +it must pass the archive's license files and notices to users. + ## Purpose This repository is responsible for: diff --git a/cmake/build_identity.cmake b/cmake/build_identity.cmake index 9f7397ed..f77fba3c 100644 --- a/cmake/build_identity.cmake +++ b/cmake/build_identity.cmake @@ -79,7 +79,12 @@ function(llamadart_add_build_identity target) BYPRODUCTS "${header}" COMMENT "Stamping the libllamadart build identity" VERBATIM) - add_dependencies(${target} llamadart_build_identity) - target_include_directories(${target} PRIVATE "${header_dir}") + set(LLAMADART_BUILD_IDENTITY_INCLUDE "${header_dir}") + llamadart_use_build_identity(${target}) set(LLAMADART_BUILD_IDENTITY_INCLUDE "${header_dir}" PARENT_SCOPE) endfunction() + +function(llamadart_use_build_identity target) + add_dependencies(${target} llamadart_build_identity) + target_include_directories(${target} PRIVATE "${LLAMADART_BUILD_IDENTITY_INCLUDE}") +endfunction() diff --git a/cmake/openvino_tests.cmake b/cmake/openvino_tests.cmake new file mode 100644 index 00000000..6f4d62d4 --- /dev/null +++ b/cmake/openvino_tests.cmake @@ -0,0 +1,72 @@ +add_executable(llamadart_openvino_identity_test tests/openvino_identity_test.cpp) +target_compile_features(llamadart_openvino_identity_test PRIVATE cxx_std_17) +target_include_directories(llamadart_openvino_identity_test PRIVATE src) +add_test(NAME llamadart_openvino_identity_test COMMAND llamadart_openvino_identity_test) + +if (WIN32) + add_library(llamadart_openvino_windows_canary MODULE tests/openvino_windows_canary.c) + set_target_properties(llamadart_openvino_windows_canary PROPERTIES + PREFIX "" OUTPUT_NAME llamadart-openvino + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/openvino-canary") + add_executable(llamadart_openvino_api_test tests/openvino_pair_smoke.cpp) + target_compile_features(llamadart_openvino_api_test PRIVATE cxx_std_17) + target_include_directories(llamadart_openvino_api_test PRIVATE src) + target_link_libraries(llamadart_openvino_api_test PRIVATE llamadart_lib) + add_dependencies(llamadart_openvino_api_test llamadart_openvino_windows_canary) + add_test(NAME llamadart_openvino_api_unsupported + COMMAND llamadart_openvino_api_test unsupported "$") +endif() + +if (TARGET ggml-openvino) + find_package(Python3 COMPONENTS Interpreter REQUIRED) + add_library(llamadart_openvino_canary MODULE tests/openvino_canary.c) + target_link_libraries(llamadart_openvino_canary PRIVATE ${CMAKE_DL_LIBS}) + add_library(llamadart_openvino_fake_runtime_symbol MODULE tests/openvino_fake_runtime_symbol.c) + + add_executable(llamadart_openvino_api_test tests/openvino_pair_smoke.cpp) + target_compile_features(llamadart_openvino_api_test PRIVATE cxx_std_17) + target_compile_definitions(llamadart_openvino_api_test PRIVATE LLAMADART_TESTING=1) + target_include_directories(llamadart_openvino_api_test PRIVATE src) + target_link_libraries(llamadart_openvino_api_test PRIVATE llamadart_lib ggml ggml-base Threads::Threads ${CMAKE_DL_LIBS}) + target_link_options(llamadart_openvino_api_test PRIVATE "LINKER:-rpath-link,$") + add_dependencies(llamadart_openvino_api_test + ggml-cpu ggml-openvino llamadart_openvino_canary llamadart_openvino_fake_runtime_symbol) + + add_executable(llamadart_openvino_ggml_origin_test tests/openvino_ggml_origin_test.cpp) + target_compile_features(llamadart_openvino_ggml_origin_test PRIVATE cxx_std_17) + target_include_directories(llamadart_openvino_ggml_origin_test PRIVATE src + third_party/llama.cpp/include third_party/llama.cpp/ggml/include) + target_link_libraries(llamadart_openvino_ggml_origin_test PRIVATE ${CMAKE_DL_LIBS}) + add_dependencies(llamadart_openvino_api_test llamadart_openvino_ggml_origin_test) + + add_executable(llamadart_openvino_diagnosis_test tests/openvino_diagnosis_test.cpp) + target_compile_features(llamadart_openvino_diagnosis_test PRIVATE cxx_std_17) + target_include_directories(llamadart_openvino_diagnosis_test PRIVATE src) + target_link_libraries(llamadart_openvino_diagnosis_test PRIVATE llamadart_lib) + target_link_options(llamadart_openvino_diagnosis_test PRIVATE "LINKER:-rpath-link,$") + + set(openvino_runner "${CMAKE_CURRENT_SOURCE_DIR}/tests/run_openvino_contract.py") + get_filename_component(openvino_sdk "${OpenVINO_DIR}/../.." ABSOLUTE) + set(stage "${CMAKE_CURRENT_BINARY_DIR}/openvino-contract") + set(openvino_args --scratch "${stage}" --sdk "${openvino_sdk}" + --sidecar-dir "${CMAKE_CURRENT_BINARY_DIR}/openvino-payload" + --canary "$" + --fake-symbol "$" + --ggml-origin-test "$") + + add_test(NAME llamadart_openvino_prepare + COMMAND "${Python3_EXECUTABLE}" "${openvino_runner}" ${openvino_args} + --prepare --binary "$" + --core-library "$" --core-bin "$") + set_tests_properties(llamadart_openvino_prepare PROPERTIES FIXTURES_SETUP openvino_payload TIMEOUT 60) + execute_process(COMMAND "${Python3_EXECUTABLE}" "${openvino_runner}" --list + OUTPUT_VARIABLE openvino_cases OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY) + foreach(case IN LISTS openvino_cases) + add_test(NAME llamadart_openvino_${case} + COMMAND "${Python3_EXECUTABLE}" "${openvino_runner}" ${openvino_args} --case "${case}") + set_tests_properties(llamadart_openvino_${case} PROPERTIES FIXTURES_REQUIRED openvino_payload TIMEOUT 180) + endforeach() + add_test(NAME llamadart_openvino_diagnosis_test + COMMAND "${CMAKE_COMMAND}" -E env "LD_LIBRARY_PATH=$" + "$") +endif() diff --git a/docs/build_identity.md b/docs/build_identity.md index da3f03b7..f6403dc3 100644 --- a/docs/build_identity.md +++ b/docs/build_identity.md @@ -71,6 +71,13 @@ file from or for such a build. - **A different identity means incompatible.** Any input change produces a new identity, including ones that leave the state layout as it was. +## OpenVINO sidecar pairing + +The OpenVINO module has the identity of its own build row. The loader pairs +it with a core by comparing `owner`, `llama.cpp`, `ggml`, `patches` and +`target`. State file compatibility still compares the entire identity. +See [OpenVINO sidecar](openvino_sidecar.md). + ## Calling it The string is a constant of the library and stays valid while it is loaded. diff --git a/docs/openvino_sidecar.md b/docs/openvino_sidecar.md new file mode 100644 index 00000000..0e526e73 --- /dev/null +++ b/docs/openvino_sidecar.md @@ -0,0 +1,130 @@ +# Linux x64 OpenVINO sidecar + +Intel NPU support is experimental and unqualified. The Linux x64 core works +without the OpenVINO archive. Windows and other platforms return +`LLAMA_DART_OPENVINO_UNSUPPORTED_PLATFORM`. + +Fetch `llamadart-native-linux-x64-openvino-.tar.gz` only for an explicit +OpenVINO request. Verify the archive against the release metadata and +`SHA256SUMS`, then verify the size and SHA-256 of each file in +`llamadart-sidecar.json`. Install the listed files under their exact names +as regular files in the native library directory beside `libllamadart.so`. +Keep `plugins.xml` byte-for-byte intact and pass the shipped licenses and +notices on to users. The Intel libraries follow the Intel OpenVINO +Distribution License. oneTBB and the Khronos OpenCL ICD Loader follow +Apache-2.0. The bundle targets the release Linux x64 glibc 2.38 floor. + +## Owner API + +`llama_dart_openvino_api_version()` reports ABI 1. Set both `struct_size` +fields, use an absolute `sidecar_dir`, and set `flags` to zero. An optional +`cache_dir` must be an existing absolute directory. + +`llama_dart_openvino_probe()` checks the sidecar, then enumerates the +requested device. `llama_dart_openvino_open()` also initializes the private +backend and returns a device handle for a null-terminated +`llama_model_params.devices` list. A successful open fixes the process's +OpenVINO device and settings. Repeat opens for that device return its +handle, which lives until process exit. Join inference workers before a +direct `exit()`. The generic ggml module search ignores +`libllamadart-openvino.so` and the returned device stays outside the global +registry. + +The sidecar is built from the same release sources as the Vulkan core. +The loader compares the owner, llama.cpp, ggml, patch set and target fields, +then checks the layout of the structs passed across the boundary. + +| Result | Meaning | +| --- | --- | +| `SIDECAR_MISSING` | A required regular file is absent or is a symlink. | +| `SIDECAR_LOAD_FAILED` | The module or a dependency could not load. | +| `VERSION_MISMATCH` | The shim ABI, build identity, ggml layout, backend API or Intel runtime build differs. | +| `FOREIGN_RUNTIME` | The selected OpenVINO, oneTBB, OpenCL loader, ggml binding or plugin configuration conflicts with the sidecar. | +| `INVALID_SETTING` | A nonempty `GGML_OPENVINO_*` variable is outside the policy below. | +| `UNSUPPORTED_DEVICE` | The request is for a device other than NPU or CPU. | +| `NO_DEVICE` | The device did not enumerate and the NPU diagnosis found no matching hardware. | +| `MISSING_DRIVER` | NPU enumeration failed and the evidence points to the kernel driver, Level Zero loader, or user-mode driver or firmware. | +| `DEVICE_ACCESS_DENIED` | The process lacks read/write access to its NPU device nodes. | +| `DEVICE_CONFLICT` | An earlier open selected a different device in this process. | +| `PROBE_FAILED` | The sidecar threw or could not finish the operation. | + +OpenVINO resolves plugins relative to the mapped runtime. Use regular files +for optional OpenVINO libraries added beside the sidecar as well. The owner checks +the three runtime SONAMEs and their directories before and after load, +checks the module's OpenVINO and ggml bindings by address, then checks +loaded objects again after enumeration and registration. Keep the module's +`DT_RPATH=$ORIGIN` and keep the native directory free of +`openvino-*` entries. A previously mapped incompatible runtime remains a +process conflict even when it has the same version as the sidecar. + +The SDK CPU plugin is an optional test and diagnostics overlay. The archive +carries the NPU plugin and driver-compiler support. Registration requires +the device to remain available between enumeration and initialization. +The Intel plugin and driver run in the host process. + +## Settings + +Empty values use defaults. The owner rejects every nonempty +`GGML_OPENVINO_*` variable outside this table before loading the module. + +| Variable | Accepted values | +| --- | --- | +| `GGML_OPENVINO_DEVICE` | The requested device, `NPU` or `CPU`. The owner sets it on open if empty. | +| `GGML_OPENVINO_CACHE_DIR` | The exact requested cache directory. The owner sets it on open if supplied and empty. | +| `GGML_OPENVINO_STATEFUL_EXECUTION` | `0` | +| `GGML_OPENVINO_PROFILING` | `0`, `1`, `2` | +| `GGML_OPENVINO_LOG_UNSUPPORTED_OPS` | `0`, `1` | +| `GGML_OPENVINO_LOG_SUPPORTS_OP` | `0`, `1`, `2` | +| `GGML_OPENVINO_NPU_COMPILER_TYPE` | `DRIVER`, `PLUGIN`, `PREFER_PLUGIN`. The bundled configuration uses the driver compiler. | + +Set any required environment variables before starting threads if your host +cannot change its environment in a multithreaded process. Keep the environment +stable across registration. A path supplied as a cache directory may appear +in upstream diagnostics. Use a path without credentials or sensitive data. + +## Build and verify + +Use Ubuntu 24.04 x64 with CMake, Ninja, GCC and Python 3.12 or later, with +recursive submodules initialized. The SDK fetch also pins the Khronos C++ +headers compatible with the vendored OpenCL C headers. + +```sh +sdk="$(python3 tools/openvino_sdk.py --output build/openvino-sdk --with-opencl-headers)" +python3 tools/build.py linux --arch x64 --backend openvino --openvino-sdk "$sdk" +python3 tools/package_openvino_sidecar.py \ + --build-dir bin/linux/x64/openvino --sdk "$sdk" \ + --directory build/linux-x64-openvino/openvino-payload --output build/openvino.tar.gz +python3 tools/validate_openvino_sidecar.py build/linux-x64-openvino/openvino-payload --sdk "$sdk" +``` + +The release and pull request pair jobs build the core and sidecar +independently and run the pair with the published layout. The wrapper +contract job also tests loader rejections and exit with a live context. +On an SDK bump, review the EULA and `redist.txt` changes and re-run the +byte-for-byte SDK and license checks. + +## Community NPU qualification + +Run on both Lunar Lake and Panther Lake and record CPU model, distro, kernel, +`ivpu` driver, firmware, Intel user-mode driver and Level Zero loader versions. +Capture the native tag, asset SHA-256, exact model and quantization, and the +owner status, detail and driver version. Use upstream `llama-cli` with the +same llama.cpp and Intel runtime versions as the control. + +- Check enumeration with the kernel driver absent, with `/dev/accel` access + denied, with the Level Zero loader absent, and with a working configuration. +- On a working device, verify actual NPU placement, decoded output against + the control, cold and warm start with the cache directory, and a clean + exit with a live context after joining the worker. +- Use `LD_DEBUG=files` to identify the NPU compiler loader, VM runtime and + selected compiler. Record whether the Intel driver maps a separate + `libopenvino*` object and whether this returns `FOREIGN_RUNTIME`. +- Try a Gated DeltaNet model and record the result of requiring the + in-plugin compiler, which is outside the archive. +- On the Dart consumer follow-up, check the produced `flutter build linux` + and `dart build` bundles with `readelf -d`. Confirm `DT_RPATH=$ORIGIN`, + unchanged `plugins.xml` and a flat directory of regular files. + +The hosted CPU-plugin runs cover packaging, registration and CPU inference. +NPU behavior, driver-side runtime loading and the consumer build checks +remain qualification items. diff --git a/docs/platform_backend_strategy.md b/docs/platform_backend_strategy.md index 56cee26e..3e20f96a 100644 --- a/docs/platform_backend_strategy.md +++ b/docs/platform_backend_strategy.md @@ -1,5 +1,9 @@ # Platform Backend Strategy +The Linux x64 [OpenVINO sidecar](openvino_sidecar.md) is an independent +release asset for explicit Intel NPU requests. It shares the Linux glibc +2.38 floor. Intel NPU support is experimental and unqualified. + ## Worthy Backend Sets (Shipped Per Target) | Platform | Built backends | diff --git a/scripts/generate_assets_manifest.sh b/scripts/generate_assets_manifest.sh index 7b708827..864dae16 100755 --- a/scripts/generate_assets_manifest.sh +++ b/scripts/generate_assets_manifest.sh @@ -46,6 +46,8 @@ infer_meta() { platform="windows"; arch="arm64"; backend="core" ;; "llamadart-native-linux-x64-$tag.tar.gz") platform="linux"; arch="x64"; backend="core" ;; + "llamadart-native-linux-x64-openvino-$tag.tar.gz") + platform="linux"; arch="x64"; backend="openvino"; module="backend-openvino" ;; "llamadart-native-linux-arm64-$tag.tar.gz") platform="linux"; arch="arm64"; backend="core" ;; "llamadart-native-macos-arm64-$tag.tar.gz") diff --git a/scripts/publish_prepared_release.py b/scripts/publish_prepared_release.py index 2afe0cd8..797a9a63 100644 --- a/scripts/publish_prepared_release.py +++ b/scripts/publish_prepared_release.py @@ -24,7 +24,8 @@ REPOSITORY = 'leehack/llamadart-native' WORKFLOW_PATH = '.github/workflows/native_release.yml' MAX_ARCHIVE_BYTES = 4 * 1024 ** 3 -SUCCESS_JOBS = ('resolve-tag', 'build-linux-hip', 'smoke-release-contract', +SUCCESS_JOBS = ('resolve-tag', 'build-linux-hip', 'build-linux-openvino', + 'openvino-sidecar-pair', 'smoke-release-contract', 'package-and-release', 'emit-release-result', 'metal-os-floor / macos (macos-15)', 'metal-os-floor / macos (macos-26)', 'metal-os-floor / ios-simulator') diff --git a/scripts/release_contract.py b/scripts/release_contract.py index ade614b7..5f856c6e 100644 --- a/scripts/release_contract.py +++ b/scripts/release_contract.py @@ -43,7 +43,7 @@ ) # Backend archives published beside a runtime bundle and fetched only when an # app selects that backend. -BACKEND_SIDECARS = ("windows-x64-cuda12",) +BACKEND_SIDECARS = ("windows-x64-cuda12", "linux-x64-openvino") class ContractError(ValueError): diff --git a/scripts/release_publication.py b/scripts/release_publication.py index 2492039d..fcf2574e 100644 --- a/scripts/release_publication.py +++ b/scripts/release_publication.py @@ -43,7 +43,7 @@ class PublicationError(RuntimeError): ) # Backend archives published beside a runtime bundle and fetched only when an # app selects that backend. -BACKEND_SIDECARS = ("windows-x64-cuda12",) +BACKEND_SIDECARS = ("windows-x64-cuda12", "linux-x64-openvino") @dataclass(frozen=True) diff --git a/scripts/verify_release_provenance.py b/scripts/verify_release_provenance.py index 31f01428..19034418 100755 --- a/scripts/verify_release_provenance.py +++ b/scripts/verify_release_provenance.py @@ -43,6 +43,7 @@ } BACKEND_SIDECARS = { "windows-x64-cuda12": ("windows", "x64", "cuda", "backend-cuda12"), + "linux-x64-openvino": ("linux", "x64", "openvino", "backend-openvino"), } @@ -222,8 +223,8 @@ def verify_workflow_contract(errors: list[str]) -> None: errors, ) require( - workflow.count(expected_commit_input) == 7, - "all six build/package checkouts and the submodule update must assert the resolved commit", + workflow.count(expected_commit_input) == 9, + "all eight build/package checkouts and the submodule update must assert the resolved commit", errors, ) require( @@ -276,6 +277,8 @@ def verify_workflow_contract(errors: list[str]) -> None: "build-apple", "build-linux", "build-linux-hip", + "build-linux-openvino", + "openvino-sidecar-pair", "build-windows", "smoke-release-contract", "package-and-release", @@ -417,7 +420,7 @@ def verify_workflow_contract(errors: list[str]) -> None: ) require( "needs: [resolve-tag, build-android, build-apple, metal-os-floor, build-linux, " - "build-linux-hip, build-windows, smoke-release-contract]" + "build-linux-hip, build-windows, smoke-release-contract, openvino-sidecar-pair]" in package_job and "needs: [resolve-tag, smoke-release-contract, package-and-release]" in publish_job and "needs.package-and-release.result == 'success'" in publish_job, @@ -631,14 +634,18 @@ def release_source_contract_errors(workflow: str) -> list[str]: errors, ) for name in ("build-android", "build-apple", "build-linux", "build-linux-hip", - "build-windows", "package-and-release"): + "build-linux-openvino", "openvino-sidecar-pair", "build-windows", "package-and-release"): job = workflow_job(workflow, name) source = job.find("uses: ./.github/actions/checkout-native-source") start = job.rfind("\n -", 0, source) end = job.find("\n -", source) source_step = job[start:end if end >= 0 else len(job)] - build = job.find("tools/build.py" if name != "package-and-release" - else "- name: Prepare release assets") + task = { + "package-and-release": "- name: Prepare release assets", + "build-linux-openvino": "uses: ./.github/actions/openvino-sidecar-build", + "openvino-sidecar-pair": "uses: ./.github/actions/openvino-sidecar-pair", + }.get(name, "tools/build.py") + build = job.find(task) require( 0 <= source < build and "if:" not in source_step and "continue-on-error:" not in source_step diff --git a/src/llama_dart_openvino.cpp b/src/llama_dart_openvino.cpp new file mode 100644 index 00000000..1c86b351 --- /dev/null +++ b/src/llama_dart_openvino.cpp @@ -0,0 +1,494 @@ +#include "llama_dart_wrapper.h" + +#if defined(__linux__) && defined(__x86_64__) && !defined(__ANDROID__) +#include "llama_dart_openvino_internal.h" +#include "llama_dart_openvino_plugins.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#if defined(LLAMADART_TESTING) +#include "llama_dart_openvino_test_hooks.h" + +#include +#endif +#endif + +namespace { + +int32_t result(llama_dart_openvino_info & info, llama_dart_openvino_status status, + const char * detail) noexcept { + info.status = status; + if (detail) { + size_t i = 0; + for (; i < sizeof(info.detail) - 1 && detail[i]; ++i) { + info.detail[i] = detail[i]; + } + info.detail[i] = 0; + } + return status; +} + +#if defined(__linux__) && defined(__x86_64__) && !defined(__ANDROID__) +namespace fs = std::filesystem; +using namespace llamadart_openvino; + +constexpr const char * device_setting = "GGML_OPENVINO_DEVICE"; +constexpr const char * cache_setting = "GGML_OPENVINO_CACHE_DIR"; +constexpr const char * runtime_name = "libopenvino.so.2641"; +constexpr const char * runtime_sonames[] = {runtime_name, "libtbb.so.12", "libOpenCL.so.1"}; +constexpr const char * shared_files[] = { + module_name, runtime_sonames[0], runtime_sonames[1], runtime_sonames[2], "plugins.xml", +}; + +#if defined(LLAMADART_TESTING) +std::atomic skip_origin_checks{0}; +#endif + +struct option { + const char * name; + std::array values; +}; + +constexpr option settings[] = { + {"GGML_OPENVINO_STATEFUL_EXECUTION", {"0"}}, + {"GGML_OPENVINO_PROFILING", {"0", "1", "2"}}, + {"GGML_OPENVINO_LOG_UNSUPPORTED_OPS", {"0", "1"}}, + {"GGML_OPENVINO_LOG_SUPPORTS_OP", {"0", "1", "2"}}, + {"GGML_OPENVINO_NPU_COMPILER_TYPE", {"DRIVER", "PLUGIN", "PREFER_PLUGIN"}}, +}; + +std::string invalid_setting(const char * device, const char * cache) { + constexpr std::string_view prefix = "GGML_OPENVINO_"; + for (auto env = environ; env && *env; ++env) { + const std::string_view entry(*env); + const auto equals = entry.find('='); + const auto name = entry.substr(0, equals); + if (name.substr(0, prefix.size()) != prefix || equals == entry.size() - 1) { + continue; + } + const auto value = equals == entry.npos ? std::string_view{} : entry.substr(equals + 1); + if (name == device_setting && value == device) { + continue; + } + if (name == cache_setting && cache && value == cache) { + continue; + } + bool allowed = false; + for (const auto & setting : settings) { + if (name != setting.name) { + continue; + } + for (const auto allowed_value : setting.values) { + allowed |= !allowed_value.empty() && value == allowed_value; + } + break; + } + if (!allowed) { + return std::string(name); + } + } + return {}; +} + +bool set_if_empty(const char * name, const char * value) { + const char * current = std::getenv(name); + return !value || (current && *current) || setenv(name, value, 1) == 0; +} + +int32_t diagnose_npu(const fs::path & pci, const fs::path & accel, bool (*has_level_zero)(), + llama_dart_openvino_info & info) { + std::error_code error; + bool found_node = false; + for (fs::directory_iterator it(accel, error), end; !error && it != end; it.increment(error)) { + const auto name = it->path().filename().string(); + if (name.compare(0, 5, "accel") != 0) { + continue; + } + found_node = true; + if (access(it->path().c_str(), R_OK | W_OK) == 0) { + const char * missing = has_level_zero() ? "Intel NPU user-mode driver or firmware" : "libze_loader.so.1"; + return result(info, LLAMA_DART_OPENVINO_MISSING_DRIVER, missing); + } + } + if (found_node) { + return result(info, LLAMA_DART_OPENVINO_DEVICE_ACCESS_DENIED, "/dev/accel access"); + } + for (fs::directory_iterator it(pci, error), end; !error && it != end; it.increment(error)) { + std::ifstream vendor(it->path() / "vendor"); + std::ifstream device_class(it->path() / "class"); + unsigned vendor_id = 0, class_id = 0; + if (vendor >> std::hex >> vendor_id && device_class >> std::hex >> class_id && + vendor_id == 0x8086 && (class_id & 0xffff00) == 0x120000) { + return result(info, LLAMA_DART_OPENVINO_MISSING_DRIVER, "Intel ivpu kernel driver"); + } + } + return result(info, LLAMA_DART_OPENVINO_NO_DEVICE, "NPU"); +} + +bool has_level_zero() { + void * library = dlopen("libze_loader.so.1", RTLD_NOW | RTLD_LOCAL); + if (!library) { + return false; + } + dlclose(library); + return true; +} + +struct selection { + std::mutex mutex; + int32_t device = 0; + ggml_backend_dev_t handle = nullptr; + llama_dart_openvino_info info{}; +}; + +selection & process_selection() { + static selection state; + return state; +} + +template +Fn symbol(void * module, const char * name) { + return reinterpret_cast(dlsym(module, name)); +} + +const char * load_error() { + const char * error = dlerror(); + if (!error) { + return "dlopen failed"; + } + // The loader may name a file from outside the supplied sidecar. + const char * separator = std::strstr(error, ": "); + if (!separator || std::strchr(separator + 2, '/')) { + return "dlopen failed"; + } + return separator + 2; +} + +bool regular_file(const fs::path & path) { + std::error_code error; + return fs::is_regular_file(fs::symlink_status(path, error)); +} + +std::string layout_problem(const fs::path & directory) { + std::ifstream input(directory / "plugins.xml", std::ios::binary); + constexpr std::string_view expected = llama_dart_openvino_plugins_xml; + std::array bytes{}; + if (!input.read(bytes.data(), bytes.size()) || + std::string_view(bytes.data(), bytes.size()) != expected || + input.peek() != std::char_traits::eof() || input.bad()) { + return "plugin list: plugins.xml"; + } + for (const auto & entry : fs::directory_iterator(directory)) { + const auto name = entry.path().filename().string(); + if (name.compare(0, 9, "openvino-") == 0) { + return "plugin directory: " + name; + } + if (name.compare(0, 11, "libopenvino") == 0 && fs::is_symlink(entry.symlink_status())) { + return "plugin file: " + name; + } + } + return {}; +} + +const char * basename_of(const char * path) { + const char * slash = std::strrchr(path, '/'); + return slash ? slash + 1 : path; +} + +// OpenVINO resolves its plugin directory from the loader's recorded runtime name. +bool directory_matches(const char * path, const std::string & directory) { + const char * slash = std::strrchr(path, '/'); + if (!slash || slash - path >= PATH_MAX) { + return false; + } + char parent[PATH_MAX]; + const size_t length = slash == path ? 1 : static_cast(slash - path); + std::memcpy(parent, path, length); + parent[length] = '\0'; + char resolved[PATH_MAX]; + return realpath(parent, resolved) && directory == resolved; +} + +bool handle_matches(void * handle, const char * name, const std::string & directory) { + link_map * map = nullptr; + return dlinfo(handle, RTLD_DI_LINKMAP, &map) == 0 && map && map->l_name && + std::strcmp(basename_of(map->l_name), name) == 0 && directory_matches(map->l_name, directory); +} + +bool address_matches(const void * address, const char * name, const std::string & directory) { + Dl_info location{}; + return address && dladdr(address, &location) && location.dli_fname && + (!name || std::strcmp(basename_of(location.dli_fname), name) == 0) && + directory_matches(location.dli_fname, directory); +} + +std::string runtime_problem(const std::string & directory, bool loaded) { + // RTLD_NOLOAD uses the same SONAME match as DT_NEEDED without mapping a new object. + for (const char * soname : runtime_sonames) { + void * handle = dlopen(soname, RTLD_NOLOAD | RTLD_LAZY); + if (handle) { + const bool matches = handle_matches(handle, soname, directory); + dlclose(handle); + if (matches) { + continue; + } + } else if (!loaded) { + continue; + } + return std::string("runtime origin: ") + soname; + } + + struct mapped_runtime { + const std::string & directory; + char foreign[256]{}; + } mapped{directory}; + dl_iterate_phdr([](dl_phdr_info * info, size_t, void * data) { + auto & state = *static_cast(data); + if (!info->dlpi_name) { + return 0; + } + const char * name = basename_of(info->dlpi_name); + if (std::strncmp(name, "libopenvino", 11) == 0 && + (!directory_matches(info->dlpi_name, state.directory) || + (std::strncmp(name, "libopenvino.so", 14) == 0 && std::strcmp(name, runtime_name) != 0))) { + copy_text(state.foreign, name); + return 1; + } + return 0; + }, &mapped); + if (*mapped.foreign) { + return std::string("foreign runtime object: ") + mapped.foreign; + } + if (!loaded) { + for (const char * name : {"get_openvino_version", "TBB_runtime_version", "TBB_runtime_interface_version"}) { + const void * address = dlsym(RTLD_DEFAULT, name); + if (address && !address_matches(address, nullptr, directory)) { + return std::string("global runtime symbol: ") + name; + } + } + } + return {}; +} + +int32_t run(const llama_dart_openvino_request & request, llama_dart_openvino_info & info, + ggml_backend_dev_t * out_device) { + const fs::path directory(request.sidecar_dir ? request.sidecar_dir : ""); + if (!directory.is_absolute() || request.flags != 0 || + (request.cache_dir && (!fs::path(request.cache_dir).is_absolute() || + !fs::is_directory(request.cache_dir)))) { + return result(info, LLAMA_DART_OPENVINO_INVALID_ARGUMENT, "sidecar_dir, cache_dir or flags"); + } + const bool npu = request.device == LLAMA_DART_OPENVINO_DEVICE_NPU; + if (!npu && request.device != LLAMA_DART_OPENVINO_DEVICE_CPU) { + return result(info, LLAMA_DART_OPENVINO_UNSUPPORTED_DEVICE, "expected NPU or CPU"); + } + + auto & state = process_selection(); + const std::lock_guard lock(state.mutex); + if (state.handle) { + if (state.device != request.device) { + return result(info, LLAMA_DART_OPENVINO_DEVICE_CONFLICT, "OpenVINO device already selected"); + } + const auto size = info.struct_size; + info = state.info; + info.struct_size = size; + if (out_device) { + *out_device = state.handle; + } + return info.status; + } + + const char * device = npu ? "NPU" : "CPU"; + const auto invalid = invalid_setting(device, request.cache_dir); + if (!invalid.empty()) { + return result(info, LLAMA_DART_OPENVINO_INVALID_SETTING, invalid.c_str()); + } + for (const char * file : shared_files) { + if (!regular_file(directory / file)) { + return result(info, LLAMA_DART_OPENVINO_SIDECAR_MISSING, file); + } + } + if (npu) { + for (const char * file : {"libopenvino_intel_npu_plugin.so", + "libopenvino_intel_npu_compiler_loader.so", + "libopenvino_intel_npu_vm_runtime.so"}) { + if (!regular_file(directory / file)) { + return result(info, LLAMA_DART_OPENVINO_SIDECAR_MISSING, file); + } + } + } + + const auto layout_error = layout_problem(directory); + if (!layout_error.empty()) { + return result(info, LLAMA_DART_OPENVINO_FOREIGN_RUNTIME, layout_error.c_str()); + } + const auto sidecar = fs::canonical(directory).string(); + uint32_t skip = 0; +#if defined(LLAMADART_TESTING) + skip = skip_origin_checks.load(std::memory_order_relaxed); +#endif + if (!(skip & 1)) { + const auto problem = runtime_problem(sidecar, false); + if (!problem.empty()) { + return result(info, LLAMA_DART_OPENVINO_FOREIGN_RUNTIME, problem.c_str()); + } + } + + // The runtime and the private ggml device can outlive the caller. + // RTLD_NODELETE retains their state without accumulating dlopen references. + void * module = dlopen((fs::path(sidecar) / module_name).c_str(), RTLD_NOW | RTLD_LOCAL | RTLD_NODELETE); + if (!module) { + return result(info, LLAMA_DART_OPENVINO_SIDECAR_LOAD_FAILED, load_error()); + } + struct module_ref { + void * handle; + ~module_ref() { dlclose(handle); } + } reference{module}; + + const auto abi = symbol(module, "llama_dart_openvino_shim_abi"); + const auto identity = symbol(module, "llama_dart_openvino_shim_identity"); + const auto get_layout = symbol(module, "llama_dart_openvino_shim_layout"); + const auto enumerate = symbol( + module, "llama_dart_openvino_shim_enumerate"); + const auto selected = symbol(module, "llama_dart_openvino_shim_selected"); + const auto init = symbol(module, "ggml_backend_init"); + const auto runtime_anchor = symbol(module, "llama_dart_openvino_shim_runtime_anchor"); + const auto ggml_anchor = symbol(module, "llama_dart_openvino_shim_ggml_anchor"); + if (!abi || !identity || !get_layout || !enumerate || !selected || !init || + !runtime_anchor || !ggml_anchor || abi() != shim_abi) { + return result(info, LLAMA_DART_OPENVINO_VERSION_MISMATCH, "shim ABI"); + } + if (!(skip & 2)) { + if (!handle_matches(module, module_name, sidecar)) { + return result(info, LLAMA_DART_OPENVINO_FOREIGN_RUNTIME, "module origin"); + } + const auto problem = runtime_problem(sidecar, true); + if (!problem.empty()) { + return result(info, LLAMA_DART_OPENVINO_FOREIGN_RUNTIME, problem.c_str()); + } + if (!address_matches(runtime_anchor(), runtime_name, sidecar)) { + return result(info, LLAMA_DART_OPENVINO_FOREIGN_RUNTIME, "runtime binding: libopenvino.so.2641"); + } + if (ggml_anchor() != reinterpret_cast(&ggml_time_us)) { + return result(info, LLAMA_DART_OPENVINO_FOREIGN_RUNTIME, "ggml-base instance"); + } + } + const auto field = identity_mismatch(llama_dart_build_identity(), identity()); + if (!field.empty()) { + const auto detail = "build identity: " + std::string(field); + return result(info, LLAMA_DART_OPENVINO_VERSION_MISMATCH, detail.c_str()); + } + if (!layout_matches(current_layout(), get_layout())) { + return result(info, LLAMA_DART_OPENVINO_VERSION_MISMATCH, "ggml layout"); + } + + const auto enumeration = enumerate(device, &info); + const auto probe_problem = runtime_problem(sidecar, true); + if (!probe_problem.empty()) { + return result(info, LLAMA_DART_OPENVINO_FOREIGN_RUNTIME, probe_problem.c_str()); + } + switch (enumeration) { + case LLAMA_DART_OPENVINO_OK: + break; + case LLAMA_DART_OPENVINO_VERSION_MISMATCH: + return result(info, LLAMA_DART_OPENVINO_VERSION_MISMATCH, "OpenVINO runtime"); + case LLAMA_DART_OPENVINO_NO_DEVICE: + return npu ? diagnose_npu("/sys/bus/pci/devices", "/dev/accel", has_level_zero, info) + : result(info, LLAMA_DART_OPENVINO_NO_DEVICE, "CPU"); + default: + return result(info, LLAMA_DART_OPENVINO_PROBE_FAILED, "OpenVINO enumeration"); + } + if (!out_device) { + return result(info, LLAMA_DART_OPENVINO_OK, nullptr); + } + + if (!set_if_empty(device_setting, device) || !set_if_empty(cache_setting, request.cache_dir)) { + return result(info, LLAMA_DART_OPENVINO_PROBE_FAILED, "could not set OpenVINO environment"); + } + const auto reg = init(); + if (!reg || reg->api_version != GGML_BACKEND_API_VERSION) { + return result(info, LLAMA_DART_OPENVINO_VERSION_MISMATCH, "ggml backend API"); + } + const auto open_problem = runtime_problem(sidecar, true); + if (!open_problem.empty()) { + return result(info, LLAMA_DART_OPENVINO_FOREIGN_RUNTIME, open_problem.c_str()); + } + const auto selected_device = selected(); + if (!selected_device || std::strcmp(selected_device, device) != 0) { + return result(info, LLAMA_DART_OPENVINO_PROBE_FAILED, "OpenVINO device selection"); + } + for (size_t i = 0; i < ggml_backend_reg_dev_count(reg); ++i) { + const auto candidate = ggml_backend_reg_dev_get(reg, i); + if (candidate && ggml_backend_dev_type(candidate) == GGML_BACKEND_DEVICE_TYPE_GPU) { + state.device = request.device; + state.info = info; + state.handle = candidate; + *out_device = candidate; + return result(info, LLAMA_DART_OPENVINO_OK, nullptr); + } + } + return result(info, LLAMA_DART_OPENVINO_PROBE_FAILED, "OpenVINO device handle"); +} +#endif + +int32_t dispatch(const llama_dart_openvino_request * request, llama_dart_openvino_info * info, + bool opening, ggml_backend_dev_t * out_device) noexcept { + if (out_device) { + *out_device = nullptr; + } + if (!info || info->struct_size < sizeof(*info)) { + return LLAMA_DART_OPENVINO_INVALID_ARGUMENT; + } + const auto size = info->struct_size; + *info = {}; + info->struct_size = size; + if (!request || request->struct_size < sizeof(*request) || (opening && !out_device)) { + return result(*info, LLAMA_DART_OPENVINO_INVALID_ARGUMENT, "request, info or out_device"); + } +#if defined(__linux__) && defined(__x86_64__) && !defined(__ANDROID__) + try { + return run(*request, *info, out_device); + } catch (...) { + return result(*info, LLAMA_DART_OPENVINO_PROBE_FAILED, "OpenVINO sidecar operation"); + } +#else + return result(*info, LLAMA_DART_OPENVINO_UNSUPPORTED_PLATFORM, "OpenVINO sidecar requires Linux x64"); +#endif +} + +} // namespace + +uint32_t llama_dart_openvino_api_version() { + return LLAMA_DART_OPENVINO_API_VERSION; +} + +int32_t llama_dart_openvino_probe(const llama_dart_openvino_request * request, llama_dart_openvino_info * info) { + return dispatch(request, info, false, nullptr); +} + +int32_t llama_dart_openvino_open(const llama_dart_openvino_request * request, llama_dart_openvino_info * info, + ggml_backend_dev_t * out_device) { + return dispatch(request, info, true, out_device); +} + +#if defined(LLAMADART_TESTING) && defined(__linux__) && defined(__x86_64__) && !defined(__ANDROID__) +void llama_dart_openvino_test_skip_origin_checks(uint32_t mask) { + skip_origin_checks.store(mask, std::memory_order_relaxed); +} + +int32_t llama_dart_openvino_test_diagnose(const char * pci, const char * accel, bool (*has_loader)(), + llama_dart_openvino_info * info) { + return diagnose_npu(pci, accel, has_loader, *info); +} +#endif diff --git a/src/llama_dart_openvino_identity.h b/src/llama_dart_openvino_identity.h new file mode 100644 index 00000000..cc5defd3 --- /dev/null +++ b/src/llama_dart_openvino_identity.h @@ -0,0 +1,77 @@ +#pragma once + +#include +#include +#include + +namespace llamadart_openvino { + +// The other fields describe the build row and may differ across the C boundary. +constexpr std::string_view paired_fields[] = {"owner", "llama.cpp", "ggml", "patches", "target"}; + +inline bool parse_identity(const char * identity, std::map & fields) { + constexpr std::string_view tag = "llamadart-native-build/1"; + constexpr std::string_view value_chars = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._+,-"; + if (!identity) { + return false; + } + std::string_view text(identity); + if (text.size() <= tag.size() || text.substr(0, tag.size()) != tag || text[tag.size()] != ';') { + return false; + } + text.remove_prefix(tag.size() + 1); + for (;;) { + const auto end = text.find(';'); + const auto field = text.substr(0, end); + const auto equals = field.find('='); + if (equals == std::string_view::npos || equals == 0 || equals == field.size() - 1) { + return false; + } + const auto key = field.substr(0, equals); + const auto value = field.substr(equals + 1); + if (key.find_first_not_of(value_chars) != std::string_view::npos || + value.find_first_not_of(value_chars) != std::string_view::npos || + !fields.emplace(key, value).second) { + return false; + } + if (end == std::string_view::npos) { + return true; + } + text.remove_prefix(end + 1); + } +} + +inline std::string_view identity_mismatch(const char * core, const char * module) { + std::map core_fields, module_fields; + if (!parse_identity(core, core_fields)) { + return "core identity"; + } + if (!parse_identity(module, module_fields)) { + return "module identity"; + } + for (const auto key : paired_fields) { + const auto a = core_fields.find(key); + const auto b = module_fields.find(key); + if (a == core_fields.end() || b == module_fields.end() || a->second != b->second) { + return key; + } + } + return {}; +} + +struct layout { + uint32_t tensor; + uint32_t backend; + uint32_t device; + uint32_t buffer; + uint32_t buffer_type; + uint32_t max_name; +}; + +inline bool layout_matches(const layout & a, const layout & b) { + return a.tensor == b.tensor && a.backend == b.backend && a.device == b.device && + a.buffer == b.buffer && a.buffer_type == b.buffer_type && a.max_name == b.max_name; +} + +} // namespace llamadart_openvino diff --git a/src/llama_dart_openvino_internal.h b/src/llama_dart_openvino_internal.h new file mode 100644 index 00000000..91127b0a --- /dev/null +++ b/src/llama_dart_openvino_internal.h @@ -0,0 +1,30 @@ +#pragma once + +#include "llama_dart_openvino_identity.h" + +#include "ggml-backend-impl.h" + +#include +#include + +namespace llamadart_openvino { + +constexpr uint32_t shim_abi = 1; +constexpr const char * module_name = "libllamadart-openvino.so"; + +constexpr layout current_layout() { + return { + sizeof(ggml_tensor), sizeof(ggml_backend_i), sizeof(ggml_backend_device_i), + sizeof(ggml_backend_buffer_i), sizeof(ggml_backend_buffer_type_i), GGML_MAX_NAME, + }; +} + +template +void copy_text(char (&output)[N], const char * value) noexcept { + const size_t size = std::strlen(value); + const size_t copied = size < N ? size : N - 1; + std::memcpy(output, value, copied); + output[copied] = 0; +} + +} // namespace llamadart_openvino diff --git a/src/llama_dart_openvino_plugins.h b/src/llama_dart_openvino_plugins.h new file mode 100644 index 00000000..6ffbe999 --- /dev/null +++ b/src/llama_dart_openvino_plugins.h @@ -0,0 +1,12 @@ +#pragma once + +inline constexpr char llama_dart_openvino_plugins_xml[] = R"xml( + + + + + + + + +)xml"; diff --git a/src/llama_dart_openvino_shim.cpp b/src/llama_dart_openvino_shim.cpp new file mode 100644 index 00000000..a4f5f889 --- /dev/null +++ b/src/llama_dart_openvino_shim.cpp @@ -0,0 +1,66 @@ +#include "llama_dart_openvino_internal.h" +#include "llama_dart_wrapper.h" +#include "llama_dart_build_identity.h" + +#include "ggml-openvino-extra.h" + +#include + +#include + +using namespace llamadart_openvino; + +extern "C" LLAMADART_API uint32_t llama_dart_openvino_shim_abi() noexcept { + return shim_abi; +} + +extern "C" LLAMADART_API const char * llama_dart_openvino_shim_identity() noexcept { + return LLAMA_DART_BUILD_IDENTITY; +} + +extern "C" LLAMADART_API layout llama_dart_openvino_shim_layout() noexcept { + return current_layout(); +} + +extern "C" LLAMADART_API const void * llama_dart_openvino_shim_runtime_anchor() noexcept { + return reinterpret_cast(&ov::get_openvino_version); +} + +extern "C" LLAMADART_API const void * llama_dart_openvino_shim_ggml_anchor() noexcept { + return reinterpret_cast(&ggml_time_us); +} + +extern "C" LLAMADART_API int32_t llama_dart_openvino_shim_enumerate( + const char * device, llama_dart_openvino_info * info) noexcept { + try { + const auto version = ov::get_openvino_version(); + copy_text(info->openvino_version, version.buildNumber); + if (std::strcmp(version.buildNumber, LLAMADART_OPENVINO_RUNTIME_BUILD) != 0) { + return LLAMA_DART_OPENVINO_VERSION_MISMATCH; + } + auto & core = ov_singleton_core(); + const auto devices = core.get_available_devices(); + if (std::find(devices.begin(), devices.end(), device) == devices.end()) { + return LLAMA_DART_OPENVINO_NO_DEVICE; + } + copy_text(info->device_description, ggml_openvino_get_device_description(device).c_str()); + if (std::strcmp(device, "NPU") == 0) { + try { + info->npu_driver_version = core.get_property(device, "NPU_DRIVER_VERSION").as(); + } catch (...) { + // Driver reporting can be unavailable even on an enumerated NPU. + } + } + return LLAMA_DART_OPENVINO_OK; + } catch (...) { + return LLAMA_DART_OPENVINO_PROBE_FAILED; + } +} + +extern "C" LLAMADART_API const char * llama_dart_openvino_shim_selected() noexcept { + try { + return ggml_openvino_get_device_name().c_str(); + } catch (...) { + return nullptr; + } +} diff --git a/src/llama_dart_openvino_test_hooks.h b/src/llama_dart_openvino_test_hooks.h new file mode 100644 index 00000000..8547c3cb --- /dev/null +++ b/src/llama_dart_openvino_test_hooks.h @@ -0,0 +1,8 @@ +#pragma once + +#include "llama_dart_wrapper.h" + +LLAMADART_API int32_t llama_dart_openvino_test_diagnose( + const char * pci, const char * accel, bool (*has_loader)(), llama_dart_openvino_info * info); + +LLAMADART_API void llama_dart_openvino_test_skip_origin_checks(uint32_t mask); diff --git a/src/llama_dart_wrapper.h b/src/llama_dart_wrapper.h index 210da0e9..e21d1586 100644 --- a/src/llama_dart_wrapper.h +++ b/src/llama_dart_wrapper.h @@ -345,6 +345,70 @@ LLAMADART_API void llama_dart_clear_last_error(void); // state, so it needs no exit teardown guard. See docs/build_identity.md. LLAMADART_API const char * llama_dart_build_identity(void); +#define LLAMA_DART_OPENVINO_API_VERSION 1 + +enum llama_dart_openvino_device { + LLAMA_DART_OPENVINO_DEVICE_NPU = 1, + LLAMA_DART_OPENVINO_DEVICE_CPU = 2, +}; + +enum llama_dart_openvino_status { + LLAMA_DART_OPENVINO_OK = 0, + LLAMA_DART_OPENVINO_INVALID_ARGUMENT = 1, + LLAMA_DART_OPENVINO_UNSUPPORTED_PLATFORM = 2, + LLAMA_DART_OPENVINO_SIDECAR_MISSING = 3, + LLAMA_DART_OPENVINO_SIDECAR_LOAD_FAILED = 4, + LLAMA_DART_OPENVINO_VERSION_MISMATCH = 5, + LLAMA_DART_OPENVINO_INVALID_SETTING = 6, + LLAMA_DART_OPENVINO_UNSUPPORTED_DEVICE = 7, + LLAMA_DART_OPENVINO_NO_DEVICE = 8, + LLAMA_DART_OPENVINO_MISSING_DRIVER = 9, + LLAMA_DART_OPENVINO_DEVICE_ACCESS_DENIED = 10, + LLAMA_DART_OPENVINO_DRIVER_VERSION_MISMATCH = 11, // Reserved. + LLAMA_DART_OPENVINO_DEVICE_CONFLICT = 12, + LLAMA_DART_OPENVINO_PROBE_FAILED = 13, + LLAMA_DART_OPENVINO_UNSAFE_PROCESS_POLICY = 14, // Reserved. + LLAMA_DART_OPENVINO_PROBE_CRASHED = 15, // Reserved. + LLAMA_DART_OPENVINO_FOREIGN_RUNTIME = 16, +}; + +struct llama_dart_openvino_request { + uint32_t struct_size; + int32_t device; + const char * sidecar_dir; + const char * cache_dir; + uint32_t flags; +}; + +struct llama_dart_openvino_info { + uint32_t struct_size; + int32_t status; + uint32_t npu_driver_version; + char openvino_version[64]; + char device_description[256]; + char detail[512]; +}; + +LLAMADART_API uint32_t llama_dart_openvino_api_version(void); + +// Linux x64. Initialize both struct_size fields and set flags to zero. +// sidecar_dir and optional cache_dir are absolute paths. A cache directory +// must already exist. CPU requires a separately supplied Intel CPU plugin. +// FOREIGN_RUNTIME reports a conflicting runtime, binding or plugin layout. +// These calls leave llama_dart_last_error unchanged. +LLAMADART_API int32_t llama_dart_openvino_probe( + const struct llama_dart_openvino_request * request, + struct llama_dart_openvino_info * info); + +// The first successful open fixes the process's OpenVINO device and settings. +// It does not change the global ggml registry. The returned handle lives until +// process exit and can be passed in a NULL-terminated llama_model_params.devices +// list. On failure *out_device is NULL. +LLAMADART_API int32_t llama_dart_openvino_open( + const struct llama_dart_openvino_request * request, + struct llama_dart_openvino_info * info, + ggml_backend_dev_t * out_device); + // Vulkan device facts // // The devices that ggml-vulkan registers on this system, read from the Vulkan diff --git a/tests/fixtures/openvino_abort_sites.txt b/tests/fixtures/openvino_abort_sites.txt new file mode 100644 index 00000000..d52daeb6 --- /dev/null +++ b/tests/fixtures/openvino_abort_sites.txt @@ -0,0 +1,26 @@ +# llama.cpp 171527522610996f5f0acf12334e185156ca8f44 +device/npu_quant_policy.cpp:17 Owner refuses the requant override. +device/npu_quant_policy.cpp:38 Owner refuses the token embedding quantization override. +ggml-openvino-extra.cpp:98 Owner enumerates the requested device before registering. Hot-unplug remains possible. +ggml-openvino-extra.cpp:257 Owner rejects enum overrides. +ggml-openvino-extra.cpp:261 Owner allowlists fixed whole-number values. +ggml-openvino-extra.cpp:268 Owner rejects float overrides. +ggml-openvino-extra.cpp:274 Owner allowlists literal 0 and 1 for boolean settings. +ggml-openvino-extra.cpp:354 Owner accepts one of CPU and NPU. +ggml-openvino-extra.cpp:396 Owner does not select GPU device lists or initialize their OpenCL contexts. +ggml-openvino-extra.cpp:403 Owner does not select GPU devices. +ggml-openvino-extra.cpp:409 Owner does not select GPU devices. +ggml-openvino-extra.cpp:436 Owner does not select GPU devices. +ggml-openvino-extra.cpp:1193 Owner refuses channel-wise requantization. +ggml-openvino.cpp:255 Upstream inference invariant after registration. +ggml-openvino.cpp:634 Owner refuses cache-only mode. +ggml-openvino.cpp:694 Owner refuses cache-only mode. +ggml-openvino.cpp:812 Owner refuses cache-only mode. +ggml-openvino.cpp:1153 Upstream inference invariant for missing source identity. +ggml-openvino.cpp:2113 Owner refuses the GDN native-state override. +ggml-openvino.cpp:2240 Owner returns only the selected device handle. +ggml-openvino.cpp:2254 Consumer must refuse recurrent rollback and speculative decoding with this device. +model-cache.cpp:197 Owner refuses cache-only mode. +model-cache.cpp:203 Owner refuses cache-only mode. +model-cache.cpp:207 Owner refuses cache-only mode. +model-cache.cpp:316 Owner refuses cache-only mode. diff --git a/tests/openvino_canary.c b/tests/openvino_canary.c new file mode 100644 index 00000000..29a7b042 --- /dev/null +++ b/tests/openvino_canary.c @@ -0,0 +1,20 @@ +#define _GNU_SOURCE +#include +#include +#include +#include + +static void mark(void) __attribute__((constructor)); + +static void mark(void) { + const char * marker = getenv("LLAMADART_CANARY_MARKER"); + Dl_info info; + if (marker && dladdr((const void *) mark, &info)) { + FILE * file = fopen(marker, "a"); + if (file) { + const char * slash = strrchr(info.dli_fname, '/'); + fprintf(file, "%s\n", slash ? slash + 1 : info.dli_fname); + fclose(file); + } + } +} diff --git a/tests/openvino_diagnosis_test.cpp b/tests/openvino_diagnosis_test.cpp new file mode 100644 index 00000000..e2745884 --- /dev/null +++ b/tests/openvino_diagnosis_test.cpp @@ -0,0 +1,56 @@ +#include "llama_dart_openvino_test_hooks.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +bool has_loader() { + return true; +} + +bool missing_loader() { + return false; +} + +int main() { + char temporary[] = "/tmp/llamadart-openvino-diagnosis-XXXXXX"; + if (!mkdtemp(temporary)) { + return 1; + } + const fs::path root(temporary), pci = root / "pci", accel = root / "accel"; + fs::create_directories(pci / "device"); + fs::create_directories(accel); + std::ofstream(pci / "device/vendor") << "0x8086\n"; + std::ofstream(pci / "device/class") << "0x030000\n"; + + bool ok = true; + const auto expect = [&](int32_t status, const char * reason, bool (*loader)()) { + llama_dart_openvino_info info{}; + const auto result = llama_dart_openvino_test_diagnose(pci.c_str(), accel.c_str(), loader, &info); + if (result != status || info.status != status || std::strcmp(info.detail, reason) != 0) { + std::fprintf(stderr, "expected %d (%s), got %d (%s)\n", status, reason, result, info.detail); + ok = false; + } + }; + expect(LLAMA_DART_OPENVINO_NO_DEVICE, "NPU", has_loader); + std::ofstream(pci / "device/class") << "0x120001\n"; + expect(LLAMA_DART_OPENVINO_MISSING_DRIVER, "Intel ivpu kernel driver", has_loader); + + const auto node = accel / "accel0"; + std::ofstream(node) << "test\n"; + chmod(node.c_str(), 0); + if (geteuid() != 0) { + expect(LLAMA_DART_OPENVINO_DEVICE_ACCESS_DENIED, "/dev/accel access", has_loader); + } + chmod(node.c_str(), S_IRUSR | S_IWUSR); + expect(LLAMA_DART_OPENVINO_MISSING_DRIVER, "libze_loader.so.1", missing_loader); + expect(LLAMA_DART_OPENVINO_MISSING_DRIVER, "Intel NPU user-mode driver or firmware", has_loader); + fs::remove_all(root); + return ok ? 0 : 1; +} diff --git a/tests/openvino_fake_runtime_symbol.c b/tests/openvino_fake_runtime_symbol.c new file mode 100644 index 00000000..c3cecd9c --- /dev/null +++ b/tests/openvino_fake_runtime_symbol.c @@ -0,0 +1,5 @@ +#include + +void get_openvino_version(void) { + abort(); +} diff --git a/tests/openvino_ggml_origin_test.cpp b/tests/openvino_ggml_origin_test.cpp new file mode 100644 index 00000000..8ae1a223 --- /dev/null +++ b/tests/openvino_ggml_origin_test.cpp @@ -0,0 +1,27 @@ +#include "llama_dart_wrapper.h" + +#include +#include +#include + +int main(int argc, char ** argv) { + if (argc != 4) { + return 1; + } + void * core = dlopen(argv[1], RTLD_LOCAL | RTLD_NOW); + if (!core || !dlopen(argv[2], RTLD_GLOBAL | RTLD_NOW)) { + std::fprintf(stderr, "could not load test fixture: %s\n", dlerror()); + return 1; + } + const auto probe = reinterpret_cast( + dlsym(core, "llama_dart_openvino_probe")); + llama_dart_openvino_request request{sizeof(request), LLAMA_DART_OPENVINO_DEVICE_CPU, argv[3], nullptr, 0}; + llama_dart_openvino_info info{}; + info.struct_size = sizeof(info); + if (!probe || probe(&request, &info) != LLAMA_DART_OPENVINO_FOREIGN_RUNTIME || + std::strcmp(info.detail, "ggml-base instance") != 0) { + std::fprintf(stderr, "expected ggml-base instance refusal, got %d (%s)\n", info.status, info.detail); + return 1; + } + return 0; +} diff --git a/tests/openvino_identity_test.cpp b/tests/openvino_identity_test.cpp new file mode 100644 index 00000000..870ce021 --- /dev/null +++ b/tests/openvino_identity_test.cpp @@ -0,0 +1,55 @@ +#include "llama_dart_openvino_identity.h" + +#include +#include +#include + +using namespace llamadart_openvino; + +void check(bool condition, const std::string & message) { + if (!condition) { + throw std::runtime_error(message); + } +} + +int main() { + try { + const std::string prefix = "llamadart-native-build/1;"; + const std::string fields = + "owner=a+dirty.ab;llama.cpp=b;ggml=c;patches=d;target=x;" + "config=Release;compiler=GCC;backends=cpu,vulkan;options=e"; + const std::string original = prefix + fields; + check(identity_mismatch(original.c_str(), original.c_str()).empty(), "same identities"); + check(identity_mismatch(nullptr, original.c_str()) == "core identity", "null core"); + check(identity_mismatch(original.c_str(), "") == "module identity", "empty module"); + check(identity_mismatch(original.c_str(), fields.c_str()) == "module identity", "wrong format"); + check(identity_mismatch(original.c_str(), (original + ";owner=a").c_str()) == + "module identity", "duplicate key"); + check(identity_mismatch(original.c_str(), (prefix + fields.substr(fields.find(';') + 1)).c_str()) == + "owner", "missing owner"); + + for (const auto & field : { + "owner", "llama.cpp", "ggml", "patches", "target", + "config", "compiler", "backends", "options"}) { + const std::string expected = + std::string(";config;compiler;backends;options;").find( + std::string(";") + field + ";") == std::string::npos ? field : ""; + auto mutated = original; + const auto value = mutated.find(std::string(field) + "=") + std::string(field).size() + 1; + mutated[value] = 'z'; + check(identity_mismatch(original.c_str(), mutated.c_str()) == expected, field); + } + auto dirty = original; + dirty.replace(dirty.find("dirty.ab"), 8, "dirty.ac"); + check(identity_mismatch(original.c_str(), dirty.c_str()) == "owner", "different dirty digest"); + + const layout core{336, 128, 120, 112, 64, 64}; + check(layout_matches(core, core), "same layout"); + check(!layout_matches(core, {336, 128, 120, 112, 64, 128}), "max name"); + check(!layout_matches(core, {328, 128, 120, 112, 64, 64}), "tensor"); + check(!layout_matches(core, {336, 128, 120, 112, 56, 64}), "buffer type"); + } catch (const std::exception & error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/tests/openvino_pair_smoke.cpp b/tests/openvino_pair_smoke.cpp new file mode 100644 index 00000000..0b45aeb6 --- /dev/null +++ b/tests/openvino_pair_smoke.cpp @@ -0,0 +1,356 @@ +#include "llama_dart_wrapper.h" + +#include +#include +#include +#include +#include +#include + +#if defined(__linux__) && defined(__x86_64__) && !defined(__ANDROID__) +#include "gguf.h" + +#if defined(LLAMADART_TESTING) +#include "llama_dart_openvino_test_hooks.h" +#endif + +#include +#include +#include +#endif + +namespace { + +namespace fs = std::filesystem; + +int fail(const char * expression) { + std::fprintf(stderr, "OpenVINO contract failed: %s\n", expression); + return 1; +} + +#define CHECK(condition) do { if (!(condition)) return fail(#condition); } while (false) + +llama_dart_openvino_info info() { + llama_dart_openvino_info value{}; + value.struct_size = sizeof(value); + return value; +} + +bool expect(int32_t actual, const llama_dart_openvino_info & value, int32_t status, + std::string_view detail) { + if (actual == status && value.status == status && detail == value.detail) { + return true; + } + std::fprintf(stderr, "expected status %d (%.*s), got %d / %d (%s)\n", + status, static_cast(detail.size()), detail.empty() ? "" : detail.data(), actual, value.status, value.detail); + return false; +} + +#if defined(__linux__) && defined(__x86_64__) && !defined(__ANDROID__) +bool loaded_library(const char * name) { + return dl_iterate_phdr([](dl_phdr_info * object, size_t, void * opaque) -> int { + const char * base = std::strrchr(object->dlpi_name, '/'); + return std::strcmp(base ? base + 1 : object->dlpi_name, static_cast(opaque)) == 0; + }, const_cast(name)) != 0; +} + +bool preload(const fs::path & library, int scope = RTLD_LOCAL) { + if (dlopen(library.c_str(), RTLD_NOW | scope)) { + return true; + } + std::fprintf(stderr, "test preload failed: %s\n", dlerror()); + return false; +} + +bool openvino_registry_clean(size_t count) { + if (ggml_backend_dev_count() != count) { + return false; + } + for (size_t index = 0; index < count; ++index) { + if (std::string_view(ggml_backend_dev_name(ggml_backend_dev_get(index))).rfind("OPENVINO", 0) == 0) { + return false; + } + } + return true; +} + +bool openvino_in_sidecar(const fs::path & directory) { + const auto canonical = fs::canonical(directory); + struct audit { + const fs::path & directory; + int runtime_count = 0; + int base_count = 0; + bool ok = true; + } state{canonical}; + dl_iterate_phdr([](dl_phdr_info * object, size_t, void * opaque) -> int { + auto & state = *static_cast(opaque); + const fs::path path(object->dlpi_name); + const auto name = path.filename().string(); + if (name.rfind("libggml-base.so", 0) == 0) { + ++state.base_count; + } + if (name == "libopenvino.so.2641") { + ++state.runtime_count; + } + if (name.rfind("libopenvino", 0) == 0) { + std::error_code error; + state.ok &= fs::canonical(path.parent_path(), error) == state.directory; + } + return 0; + }, &state); + return state.ok && state.base_count == 1 && state.runtime_count == 1; +} + +bool make_model(const char * path) { + constexpr int width = 128, hidden = 256, vocab = 256, layers = 2; + gguf_context * file = gguf_init_empty(); + gguf_set_val_str(file, "general.architecture", "llama"); + gguf_set_val_str(file, "tokenizer.ggml.model", "no_vocab"); + gguf_set_val_u32(file, "llama.vocab_size", vocab); + gguf_set_val_u32(file, "llama.context_length", 256); + gguf_set_val_u32(file, "llama.embedding_length", width); + gguf_set_val_u32(file, "llama.feed_forward_length", hidden); + gguf_set_val_u32(file, "llama.block_count", layers); + gguf_set_val_u32(file, "llama.attention.head_count", 4); + gguf_set_val_f32(file, "llama.attention.layer_norm_rms_epsilon", 1e-5f); + + ggml_context * data = ggml_init({4 * 1024 * 1024, nullptr, false}); + uint32_t seed = 1; + const auto add = [&](const std::string & name, int columns, int rows = 0) { + auto * tensor = rows == 0 ? ggml_new_tensor_1d(data, GGML_TYPE_F32, columns) + : ggml_new_tensor_2d(data, GGML_TYPE_F32, columns, rows); + ggml_set_name(tensor, (name + ".weight").c_str()); + auto * weights = static_cast(tensor->data); + for (int64_t i = 0; i < ggml_nelements(tensor); ++i) { + seed = seed * 1664525u + 1013904223u; + weights[i] = rows == 0 ? 1.0f : (static_cast(seed >> 8) / 16777216.0f - 0.5f) * 0.1f; + } + gguf_add_tensor(file, tensor); + }; + add("token_embd", width, vocab); + add("output_norm", width); + add("output", width, vocab); + for (int layer = 0; layer < layers; ++layer) { + const auto prefix = "blk." + std::to_string(layer) + "."; + for (const char * name : {"attn_q", "attn_k", "attn_v", "attn_output"}) { + add(prefix + name, width, width); + } + add(prefix + "attn_norm", width); + add(prefix + "ffn_norm", width); + add(prefix + "ffn_up", width, hidden); + add(prefix + "ffn_gate", width, hidden); + add(prefix + "ffn_down", hidden, width); + } + const bool written = gguf_write_to_file(file, path, false); + gguf_free(file); + ggml_free(data); + return written; +} + +int decode(const char * model_path, ggml_backend_dev_t device, int layers, bool exit_live = false) { + std::string log; + llama_log_set([](ggml_log_level, const char * text, void * data) { + static_cast(data)->append(text); + }, &log); + struct restore_log { + ~restore_log() { llama_log_set(nullptr, nullptr); } + } guard; + + auto model_params = llama_model_default_params(); + ggml_backend_dev_t devices[] = {device, nullptr}; + model_params.devices = device ? devices : nullptr; + model_params.n_gpu_layers = layers; + auto * model = llama_model_load_from_file(model_path, model_params); + if (!model) { + std::fputs(log.c_str(), stderr); + return fail("model load"); + } + const bool saw_openvino = log.find("OPENVINO") != std::string::npos; + const bool placed = log.find("OPENVINO0 model buffer") != std::string::npos; + auto context_params = llama_context_default_params(); + context_params.n_ctx = 128; + context_params.n_batch = context_params.n_ubatch = 32; + context_params.n_threads = context_params.n_threads_batch = 2; + auto * context = llama_init_from_model(model, context_params); + bool decoded = false; + if (context) { + std::thread worker([&] { + llama_token tokens[] = {3, 4, 5}; + decoded = llama_decode(context, llama_batch_get_one(tokens, 3)) == 0 && + llama_get_logits_ith(context, -1) != nullptr; + }); + worker.join(); + } + if (decoded && saw_openvino == (device != nullptr) && (!device || placed)) { + if (exit_live) { + llama_log_set(nullptr, nullptr); + std::exit(0); + } + llama_free(context); + llama_model_free(model); + return 0; + } + std::fputs(log.c_str(), stderr); + llama_free(context); + llama_model_free(model); + return fail("OpenVINO placement and decode"); +} + +#endif + +} // namespace + +int main(int argc, char ** argv) { + CHECK(argc >= 3); + const std::string_view scenario(argv[1]); + const std::string directory = fs::absolute(argv[2]).string(); + llama_dart_openvino_request request{sizeof(request), LLAMA_DART_OPENVINO_DEVICE_CPU, + directory.c_str(), nullptr, 0}; + auto result = info(); + ggml_backend_dev_t device = nullptr; + CHECK(llama_dart_openvino_api_version() == LLAMA_DART_OPENVINO_API_VERSION); + +#if defined(__linux__) && defined(__x86_64__) && !defined(__ANDROID__) + if (scenario == "make-model") { + CHECK(make_model(directory.c_str())); + return 0; + } + const char * marker = std::getenv("LLAMADART_CANARY_MARKER"); + const auto marker_exists = [&] { return marker && fs::exists(marker); }; + const auto probe = [&] { return llama_dart_openvino_probe(&request, &result); }; + const auto open = [&] { return llama_dart_openvino_open(&request, &result, &device); }; + const auto refusal = [&](int32_t status, std::string_view detail) { + const size_t count = ggml_backend_dev_count(); + return expect(probe(), result, status, detail) && expect(open(), result, status, detail) && + !device && openvino_registry_clean(count); + }; + + if (scenario == "refusal") { + CHECK(argc == 5); + CHECK(refusal(std::stoi(argv[3]), argv[4])); + CHECK(!loaded_library("libllamadart-openvino.so")); + CHECK(!marker_exists()); + return 0; + } + if (scenario == "mismatch") { + CHECK(argc == 4); + CHECK(refusal(LLAMA_DART_OPENVINO_VERSION_MISMATCH, std::string("build identity: ") + argv[3])); + CHECK(!marker_exists()); + return 0; + } + if (scenario == "load-failed") { + CHECK(probe() == LLAMA_DART_OPENVINO_SIDECAR_LOAD_FAILED); + CHECK(open() == LLAMA_DART_OPENVINO_SIDECAR_LOAD_FAILED && !device); + CHECK(!loaded_library("libllamadart-openvino.so")); + return 0; + } + + if (scenario == "foreign-runtime" || scenario == "foreign-runtime-after-load" || + scenario == "foreign-runtime-unchecked" || scenario == "foreign-tbb" || scenario == "foreign-opencl") { + CHECK(argc == 4); + const fs::path foreign = argv[3]; + const char * soname = scenario == "foreign-opencl" ? "libOpenCL.so.1" : "libtbb.so.12"; + CHECK(preload(foreign / soname)); + if (scenario != "foreign-opencl" && scenario != "foreign-tbb") { + soname = "libopenvino.so.2641"; + CHECK(preload(foreign / soname)); + } + const bool after_load = scenario == "foreign-runtime-after-load"; + const bool unchecked = scenario == "foreign-runtime-unchecked"; +#if defined(LLAMADART_TESTING) + llama_dart_openvino_test_skip_origin_checks(unchecked ? 3 : after_load ? 1 : 0); +#endif + CHECK(refusal(LLAMA_DART_OPENVINO_FOREIGN_RUNTIME, std::string("runtime origin: ") + soname)); + CHECK(loaded_library("libllamadart-openvino.so") == (after_load || unchecked)); + CHECK(marker_exists() == unchecked); + return 0; + } + + if (scenario == "foreign-runtime-global-symbol" || scenario == "foreign-binding-after-load") { + CHECK(argc == 4); + CHECK(preload(argv[3], RTLD_GLOBAL)); + const bool after_load = scenario == "foreign-binding-after-load"; +#if defined(LLAMADART_TESTING) + llama_dart_openvino_test_skip_origin_checks(after_load ? 1 : 0); +#endif + const char * detail = after_load ? "runtime binding: libopenvino.so.2641" : "global runtime symbol: get_openvino_version"; + CHECK(refusal(LLAMA_DART_OPENVINO_FOREIGN_RUNTIME, detail)); + CHECK(loaded_library("libllamadart-openvino.so") == after_load); + CHECK(!marker_exists()); + return 0; + } + + if (scenario == "load-all") { + ggml_backend_load_all_from_path(directory.c_str()); + CHECK(openvino_registry_clean(ggml_backend_dev_count())); + CHECK(!loaded_library("libllamadart-openvino.so")); + if (argc == 4) { + ggml_backend_load_all_from_path(argv[3]); + CHECK(openvino_registry_clean(ggml_backend_dev_count())); + CHECK(!loaded_library("libllamadart-openvino.so")); + } + return 0; + } + + CHECK(argc == 5); + const char * core = argv[3]; + const char * model = argv[4]; + llama_backend_init(); + ggml_backend_load_all_from_path(core); + const size_t count = ggml_backend_dev_count(); + CHECK(ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU)); + + if (scenario == "pair-npu" || scenario == "npu-absent") { + request.device = LLAMA_DART_OPENVINO_DEVICE_NPU; + CHECK(refusal(LLAMA_DART_OPENVINO_NO_DEVICE, "NPU")); + CHECK(!marker_exists()); + return scenario == "npu-absent" ? decode(model, nullptr, 0) : 0; + } + if (scenario == "own-runtime-preloaded") { + CHECK(preload(fs::path(directory) / "libtbb.so.12")); + CHECK(preload(fs::path(directory) / "libopenvino.so.2641")); + } + CHECK(expect(probe(), result, LLAMA_DART_OPENVINO_OK, "")); + CHECK(expect(open(), result, LLAMA_DART_OPENVINO_OK, "")); + CHECK(device && ggml_backend_dev_type(device) == GGML_BACKEND_DEVICE_TYPE_GPU); + CHECK(openvino_registry_clean(count)); + CHECK(openvino_in_sidecar(directory)); + CHECK(!marker_exists()); + + if (scenario == "settings-accepted") { + return 0; + } + if (scenario == "device-conflict" || scenario == "reopen") { + const auto first = device; + CHECK(open() == LLAMA_DART_OPENVINO_OK && device == first); + request.device = LLAMA_DART_OPENVINO_DEVICE_NPU; + CHECK(expect(open(), result, LLAMA_DART_OPENVINO_DEVICE_CONFLICT, "OpenVINO device already selected")); + CHECK(!device); + return 0; + } + CHECK(decode(model, device, 99, scenario == "process-exit") == 0); + CHECK(!marker_exists()); + if (scenario == "default-not-contaminated") { + CHECK(decode(model, nullptr, 99) == 0); + CHECK(openvino_registry_clean(count)); + } + return 0; +#else + if (scenario == "unsupported") { + const auto marker = fs::path(directory).parent_path() / "openvino-windows-load-marker"; + fs::remove(marker); +#if defined(_WIN32) + CHECK(fs::is_regular_file(fs::path(directory) / "llamadart-openvino.dll")); + CHECK(_putenv_s("LLAMADART_CANARY_MARKER", marker.string().c_str()) == 0); +#endif + CHECK(expect(llama_dart_openvino_probe(&request, &result), result, + LLAMA_DART_OPENVINO_UNSUPPORTED_PLATFORM, "OpenVINO sidecar requires Linux x64")); + CHECK(expect(llama_dart_openvino_open(&request, &result, &device), result, + LLAMA_DART_OPENVINO_UNSUPPORTED_PLATFORM, "OpenVINO sidecar requires Linux x64")); + CHECK(!device); + CHECK(!fs::exists(marker)); + return 0; + } +#endif + return fail("unknown scenario"); +} diff --git a/tests/openvino_windows_canary.c b/tests/openvino_windows_canary.c new file mode 100644 index 00000000..dc9cc348 --- /dev/null +++ b/tests/openvino_windows_canary.c @@ -0,0 +1,16 @@ +#include +#include +#include + +BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) { + (void) instance; + (void) reserved; + if (reason == DLL_PROCESS_ATTACH) { + const char * marker = getenv("LLAMADART_CANARY_MARKER"); + FILE * file = marker ? fopen(marker, "a") : NULL; + if (file) { + fclose(file); + } + } + return TRUE; +} diff --git a/tests/run_openvino_contract.py b/tests/run_openvino_contract.py new file mode 100644 index 00000000..5bcb00c8 --- /dev/null +++ b/tests/run_openvino_contract.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +"""Stage the OpenVINO contract fixtures and run each case in a fresh process.""" + +from __future__ import annotations + +import argparse +import errno +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tarfile +import tempfile + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) + +from mutate_embedded_identity import mutate # noqa: E402 +from package_openvino_sidecar import MODULE, RUNTIME # noqa: E402 +from validate_build_identity import KEYS # noqa: E402 +from validate_openvino_sidecar import PAIRED_FIELDS, PLUGIN_NAME, validate # noqa: E402 + +RUNTIMES = (RUNTIME, "libtbb.so.12", "libOpenCL.so.1") +CPU_PLUGIN = "libopenvino_intel_cpu_plugin.so" +INVALID_SETTINGS = { + "stateful": ("STATEFUL_EXECUTION", "invalid"), + "profiling": ("PROFILING", "abc"), + "enum": ("NPU_REQUANT_POLICY", "bogus"), + "cache-only": ("COMPILED_MODEL_CACHE_ONLY", "1"), + "unknown": ("TYPO", "1"), + "device-list": ("DEVICE", "CPU,NPU"), + "gpu": ("DEVICE", "GPU"), +} +ACCEPTED_SETTINGS = { + "STATEFUL_EXECUTION": ("0",), + "PROFILING": ("0", "1", "2"), + "LOG_UNSUPPORTED_OPS": ("0", "1"), + "LOG_SUPPORTS_OP": ("0", "1", "2"), + "NPU_COMPILER_TYPE": ("DRIVER", "PLUGIN", "PREFER_PLUGIN"), +} +PAIR_CASES = [ + "pair-npu", "pair-cpu", "foreign-runtime", "own-runtime-preloaded", "ld-library-path-runtime", + *[f"identity-{field}" for field in KEYS], +] +CONTRACT_CASES = [ + *PAIR_CASES, *[f"settings-{case}" for case in INVALID_SETTINGS], "settings-accepted", + "npu-absent", "cpu-open", "default-not-contaminated", "load-all-ignores-sidecar", + "device-conflict", "reopen", "sidecar-missing", "plugins-missing", "load-failed", + "planted-plugin", "foreign-tbb", "foreign-opencl", "foreign-runtime-global-symbol", + "foreign-runtime-after-load", "foreign-binding-after-load", "foreign-runtime-unchecked", + "foreign-ggml-instance", "symlinked-sidecar", "plugin-list-mismatch-missing-device", + "plugin-list-mismatch-dotdot", "plugin-list-mismatch-absolute", "plugin-directory", + "sidecar-symlinked-file", "sidecar-symlinked-cpu-plugin", "clean-dlopen", "process-exit", +] + + +def link_or_copy(source: Path, target: Path) -> None: + try: + os.link(source.resolve(), target) + except OSError as error: + if error.errno != errno.EXDEV: + raise + shutil.copy2(source, target) + + +def stage_flat(source: Path, target: Path) -> None: + for path in sorted(source.iterdir()): + if path.is_file(): + link_or_copy(path, target / path.name) + + +def stage_core_archive(archive: Path, directory: Path) -> None: + with tempfile.TemporaryDirectory() as temporary: + with tarfile.open(archive) as tar: + tar.extractall(temporary, filter="data") + stage_flat(Path(temporary), directory) + + +def extract_sidecar(archive: Path, directory: Path) -> None: + with tarfile.open(archive) as tar: + for member in tar.getmembers(): + if not (member.isfile() or member.isdir()): + raise ValueError(f"Unexpected archive entry: {member.name}") + tar.extractall(directory, filter="data") + + +def prepare_model(scratch: Path, core: Path) -> Path: + model = scratch / "openvino-tiny.gguf" + if not model.exists(): + subprocess.run([core / "openvino_api_test", "make-model", model], check=True) + return model + + +def prepare_contract(args: argparse.Namespace) -> None: + core = args.scratch / "core" + core.mkdir(parents=True, exist_ok=True) + for library in args.core_bin.glob("*.so*"): + if library.name != MODULE: + (core / library.name).unlink(missing_ok=True) + link_or_copy(library, core / library.name) + for name in ("libllamadart.so", "openvino_api_test"): + (core / name).unlink(missing_ok=True) + link_or_copy(args.core_library, core / "libllamadart.so") + link_or_copy(args.binary, core / "openvino_api_test") + prepare_model(args.scratch, core) + + +def prepare_pair(args: argparse.Namespace) -> None: + core, sidecar = (args.scratch / name for name in ("core", "sidecar")) + core.mkdir(parents=True) + sidecar.mkdir() + stage_core_archive(args.core_archive, core) + extract_sidecar(args.sidecar_archive, sidecar) + validate(sidecar, args.sdk, core) + + command = [ + "g++", "-std=c++17", "-O2", "-pthread", + "-I", ROOT / "src", "-I", ROOT / "third_party/llama.cpp/include", + "-I", ROOT / "third_party/llama.cpp/ggml/include", + ROOT / "tests/openvino_pair_smoke.cpp", "-L", core, + "-Wl,-rpath,$ORIGIN", "-lllamadart", "-lllama", "-lggml", "-lggml-base", "-ldl", + "-o", core / "openvino_api_test", + ] + subprocess.run(command, check=True) + subprocess.run(["gcc", "-shared", "-fPIC", ROOT / "tests/openvino_canary.c", "-ldl", + "-o", args.scratch / "canary.so"], check=True) + prepare_model(args.scratch, core) + + +def case_command(args: argparse.Namespace, name: str, scratch: Path, + core: Path, model: Path, environment: dict[str, str]) -> tuple[list, Path]: + sidecar = scratch / "sidecar" + sidecar.mkdir() + stage_flat(args.sidecar_dir or args.scratch / "sidecar", sidecar) + if args.core_archive: + stage_flat(core, sidecar) + core = sidecar + if name != "pair-npu": + link_or_copy(args.sdk / "runtime/lib/intel64" / CPU_PLUGIN, sidecar / CPU_PLUGIN) + foreign = scratch / "foreign" + foreign.mkdir() + for soname in RUNTIMES: + link_or_copy(sidecar / soname, foreign / soname) + + canary_dir = scratch / "canary" + canary_dir.mkdir() + runtime_plugins = set(PLUGIN_NAME.findall((sidecar / RUNTIME).read_bytes())) + if len(runtime_plugins) < 6: + raise ValueError("Expected at least six plugin names in the pinned runtime") + canary = args.canary or args.scratch / "canary.so" + marker = scratch / "marker" + environment["LLAMADART_CANARY_MARKER"] = str(marker) + for filename in (*sorted(file.decode() for file in runtime_plugins), + "libtbbmalloc.so.2", "libtbbbind_2_5.so.3", "libze_loader.so.1", + "libopenvino_intel_npu_compiler.so"): + link_or_copy(canary, canary_dir / filename) + + binary = core / "openvino_api_test" + + def call(scenario: str, *parameters: object) -> list: + return [binary, scenario, sidecar, *map(str, parameters)] + + if name in {"foreign-runtime", "foreign-tbb", "foreign-opencl", "foreign-runtime-after-load", + "foreign-runtime-unchecked"}: + return call(name, foreign), canary_dir + if name in {"foreign-runtime-global-symbol", "foreign-binding-after-load"}: + return call(name, args.fake_symbol), canary_dir + if name == "foreign-ggml-instance": + base = foreign / "libggml-base.so.1" + # A hard link would be coalesced with the already loaded ggml object. + shutil.copyfile(core / base.name, base) + return [args.ggml_origin_test, core / "libllamadart.so", base, sidecar], canary_dir + if name == "ld-library-path-runtime": + environment["LD_LIBRARY_PATH"] = str(foreign) + if name == "symlinked-sidecar": + alias = scratch / "sidecar-alias" + alias.symlink_to(sidecar, target_is_directory=True) + sidecar = alias + if name == "sidecar-symlinked-file": + (sidecar / RUNTIME).unlink() + (sidecar / RUNTIME).symlink_to(foreign / RUNTIME) + return call("refusal", 3, RUNTIME), canary_dir + + if name == "sidecar-symlinked-cpu-plugin": + plugin = sidecar / CPU_PLUGIN + plugin.unlink() + plugin.symlink_to(canary_dir / CPU_PLUGIN) + return call("refusal", 16, f"plugin file: {CPU_PLUGIN}"), canary_dir + + xml = sidecar / "plugins.xml" + if name.startswith("plugin-list-mismatch-"): + text = xml.read_text() + xml.unlink() + gpu = '\n' + if name.endswith("missing-device"): + text = text.replace(gpu, "") + elif name.endswith("dotdot"): + text = text.replace('location="libopenvino_intel_gpu_plugin.so"', 'location="../canary/libopenvino_intel_gpu_plugin.so"') + else: + text = text.replace('location="libopenvino_intel_gpu_plugin.so"', f'location="{canary_dir}/libopenvino_intel_gpu_plugin.so"') + xml.write_text(text) + return call("refusal", 16, "plugin list: plugins.xml"), canary_dir + if name == "plugin-directory": + injected = sidecar / "openvino-2026.4.1" + injected.mkdir() + (injected / "plugins.xml").write_text('') + link_or_copy(canary, injected / CPU_PLUGIN) + return call("refusal", 16, "plugin directory: openvino-2026.4.1"), canary_dir + + if name in {"sidecar-missing", "plugins-missing"}: + missing = "libtbb.so.12" if name == "sidecar-missing" else "plugins.xml" + (sidecar / missing).unlink() + return call("refusal", 3, missing), canary_dir + if name == "load-failed": + module = sidecar / MODULE + module.unlink() + module.write_bytes(b"short") + return call(name), canary_dir + if name.startswith("identity-"): + field = name.removeprefix("identity-") + (sidecar / MODULE).unlink() + shutil.copy2((args.sidecar_dir or args.scratch / "sidecar") / MODULE, sidecar / MODULE) + mutate(sidecar / MODULE, field) + if field in PAIRED_FIELDS: + return call("mismatch", field), canary_dir + if name.removeprefix("settings-") in INVALID_SETTINGS: + key, value = INVALID_SETTINGS[name.removeprefix("settings-")] + variable = f"GGML_OPENVINO_{key}" + environment[variable] = value + return call("refusal", 6, variable), canary_dir + if name == "load-all-ignores-sidecar": + merged = scratch / "merged" + merged.mkdir() + stage_flat(sidecar, merged) + stage_flat(core, merged) + environment["GGML_OPENVINO_DEVICE"] = "NPU" + return call("load-all", merged), canary_dir + + cwd = canary_dir if name in {"symlinked-sidecar", "planted-plugin", "npu-absent", + "own-runtime-preloaded", "ld-library-path-runtime"} else Path("/") + return call(name, core, model), cwd + + +def run_case(args: argparse.Namespace, name: str) -> None: + core = args.scratch / "core" + model = args.scratch / "openvino-tiny.gguf" + with tempfile.TemporaryDirectory(dir=args.scratch) as temporary: + scratch = Path(temporary) + env = {key: value for key, value in os.environ.items() if not key.startswith("GGML_OPENVINO_")} + env.pop("LD_LIBRARY_PATH", None) + command, cwd = case_command(args, name, scratch, core, model, env) + if name == "settings-accepted": + for variable, values in ACCEPTED_SETTINGS.items(): + for value in values: + subprocess.run(command, cwd=cwd, env={**env, f"GGML_OPENVINO_{variable}": value}, + check=True, timeout=45) + else: + subprocess.run(command, cwd=cwd, env=env, check=True, timeout=90) + if name != "foreign-runtime-unchecked" and (scratch / "marker").exists(): + raise ValueError(f"Unexpected OpenVINO plugin load in {name}") + if name == "foreign-runtime-unchecked": + entries = set((scratch / "marker").read_text().splitlines()) + if not {CPU_PLUGIN, "libopenvino_intel_gpu_plugin.so", "libopenvino_auto_plugin.so"} <= entries: + raise ValueError(f"Missing OpenVINO fixture markers: {sorted(entries)}") + print(f"PASS {name}", flush=True) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--list", action="store_true") + parser.add_argument("--scratch", type=Path) + parser.add_argument("--sdk", type=Path) + parser.add_argument("--prepare", action="store_true") + parser.add_argument("--case", choices=CONTRACT_CASES) + parser.add_argument("--core-archive", type=Path) + parser.add_argument("--sidecar-archive", type=Path) + parser.add_argument("--sidecar-dir", type=Path) + parser.add_argument("--core-bin", type=Path) + parser.add_argument("--core-library", type=Path) + parser.add_argument("--binary", type=Path) + parser.add_argument("--canary", type=Path) + parser.add_argument("--fake-symbol", type=Path) + parser.add_argument("--ggml-origin-test", type=Path) + args = parser.parse_args() + if args.list: + print(";".join(CONTRACT_CASES)) + return + if args.core_archive: + prepare_pair(args) + for name in PAIR_CASES: + run_case(args, name) + elif args.prepare: + prepare_contract(args) + else: + run_case(args, args.case) + + +if __name__ == "__main__": + main() diff --git a/tests/test_assets_manifest.py b/tests/test_assets_manifest.py index 07226b51..a353f2b4 100644 --- a/tests/test_assets_manifest.py +++ b/tests/test_assets_manifest.py @@ -29,6 +29,8 @@ def test_dynamic_metadata_is_json_escaped(self) -> None: assets = root / "assets" assets.mkdir() (assets / "fixture.bin").write_bytes(b"fixture") + sidecar = "llamadart-native-linux-x64-openvino-v0.2.0.tar.gz" + (assets / sidecar).write_bytes(b"openvino") output = root / "assets.json" checksums = root / "SHA256SUMS" environment = os.environ.copy() @@ -54,3 +56,7 @@ def test_dynamic_metadata_is_json_escaped(self) -> None: for environment_name, expected in values.items(): manifest_name = environment_name.removeprefix("LLAMADART_").lower() self.assertEqual(expected, manifest[manifest_name]) + + row = next(asset for asset in manifest["artifacts"] if asset["file"] == sidecar) + self.assertEqual((row["platform"], row["arch"], row["backend"], row["module"]), + ("linux", "x64", "openvino", "backend-openvino")) diff --git a/tests/test_ci_scope.py b/tests/test_ci_scope.py index 32fe6b9d..72ec63d8 100644 --- a/tests/test_ci_scope.py +++ b/tests/test_ci_scope.py @@ -18,7 +18,7 @@ JOBS = ('android-arm64-isa', 'android-vulkan-shaders', 'kleidiai-dispatch-emulated', 'windows-arm64-kleidiai', 'windows-arm64-vulkan', 'windows-x64-runtime-closure', - 'linux-artifact-contract', + 'linux-artifact-contract', 'openvino-sidecar-contract', 'wrapper-contract', 'msvc-mtmd-link-contract', 'macos-exit-teardown') diff --git a/tests/test_linux_backends.py b/tests/test_linux_backends.py index 4ea36edc..46beb6fc 100644 --- a/tests/test_linux_backends.py +++ b/tests/test_linux_backends.py @@ -15,7 +15,7 @@ class LinuxBackendContractsTest(unittest.TestCase): def test_linux_backend_cache_vars_and_reachability(self) -> None: self.assertEqual( - ("full", "cpu", "vulkan", "cuda", "hip", "blas"), + ("full", "cpu", "vulkan", "cuda", "hip", "blas", "openvino"), build.LINUX_BACKENDS, ) @@ -26,10 +26,12 @@ def expected_vars( cuda: bool = False, hip: bool = False, blas: bool = False, + openvino: bool = False, ) -> dict[str, str]: expected = { "GGML_VULKAN": "ON" if vulkan else "OFF", "GGML_OPENCL": "OFF", + "GGML_OPENVINO": "ON" if openvino else "OFF", "GGML_CUDA": "ON" if cuda else "OFF", "GGML_HIP": "ON" if hip else "OFF", "GGML_BLAS": "ON" if blas else "OFF", @@ -47,6 +49,7 @@ def expected_vars( "vulkan": expected_vars("x64", vulkan=True), "cuda": expected_vars("x64", cuda=True), "hip": expected_vars("x64", hip=True), + "openvino": expected_vars("x64", openvino=True), "blas": expected_vars("x64", blas=True), }, "arm64": { @@ -64,7 +67,7 @@ def expected_vars( build.linux_backend_cache_vars(arch, backend), ) - for backend in ("cuda", "hip"): + for backend in ("cuda", "hip", "openvino"): with self.subTest(backend=backend): with self.assertRaises(SystemExit): build.linux_backend_cache_vars("arm64", backend) diff --git a/tests/test_linux_release_rows.py b/tests/test_linux_release_rows.py index 87594154..96902712 100644 --- a/tests/test_linux_release_rows.py +++ b/tests/test_linux_release_rows.py @@ -14,7 +14,7 @@ # The lane replaces these: it builds checked-out sources and never saves a cache # the release could restore or that would evict the release's. RELEASE_ONLY = {"Checkout llama.cpp ref", "Checkout exact release source", "Set up ccache", "Upload"} -LANE_ONLY = {"Restore release ccache", "Prime ccache"} +LANE_ONLY = {"Restore release ccache", "Prime ccache", "Upload the x64 Vulkan core"} def workflow_env(workflow: str) -> dict[str, str]: @@ -52,6 +52,20 @@ def test_build_linux_hip_runs_the_release_steps_and_the_floor_check(self) -> Non self.assertLess(names.index("Validate Linux HIP artifacts"), names.index("Check the glibc floor")) self.assertLess(names.index("Check the glibc floor"), names.index("Stage upload payload")) + def test_packaged_openvino_pair_runs_on_the_same_release_inputs(self) -> None: + for workflow in (RELEASE, LANE): + build = job_block(workflow, "build-linux-openvino") + pair = job_block(workflow, "openvino-sidecar-pair") + self.assertIn("runs-on: ubuntu-24.04", build) + self.assertIn("uses: ./.github/actions/openvino-sidecar-build", build) + self.assertIn("name: sidecar_linux_x64_openvino", build) + self.assertNotIn("native_linux_x64_openvino", build) + self.assertIn("build-linux, build-linux-openvino]", pair) + self.assertIn("uses: ./.github/actions/openvino-sidecar-pair", pair) + release = job_block(RELEASE, "package-and-release") + self.assertIn("openvino-sidecar-pair]", release) + self.assertIn("find bundles/linux-x64 -iname '*openvino*'", release) + def test_the_lane_runs_exactly_the_release_rows(self) -> None: # A pull request that moves the pin runs this lane on the new upstream. release = matrix_rows(job_block(RELEASE, "build-linux")) @@ -80,6 +94,7 @@ def test_the_loaded_core_reports_the_tts_types_the_headers_promise(self) -> None def test_steps_are_not_skipped_or_allowed_to_fail(self) -> None: allowed_conditions = { + "Upload the x64 Vulkan core": "if: matrix.arch == 'x64' && matrix.backend == 'vulkan'", "Report ccache stats": "if: always()", "Validate clean Linux consumer dlopen": "if: ${{ matrix.include_core }}", "Audit and select the Linux arm64 CPU variants": "if: ${{ matrix.arch == 'arm64' && matrix.include_core }}", @@ -99,7 +114,9 @@ def setUp(self) -> None: self.text = (WORKFLOWS / LANE).read_text() def test_the_lane_publishes_nothing_and_saves_no_cache(self) -> None: - for forbidden in ("upload-artifact", "actions/cache@", "setup-ccache", "gh release", "workflow_call", "RELEASE_TOKEN"): + self.assertEqual(2, self.text.count("actions/upload-artifact@")) + self.assertEqual(2, self.text.count("retention-days: 1")) + for forbidden in ("actions/cache@", "setup-ccache", "gh release", "workflow_call", "RELEASE_TOKEN"): self.assertNotIn(forbidden, self.text) self.assertEqual(2, self.text.count("actions/cache/restore@")) self.assertRegex(self.text, r"(?m)^permissions:\n contents: read\n") diff --git a/tests/test_mutate_embedded_identity.py b/tests/test_mutate_embedded_identity.py new file mode 100644 index 00000000..144ecf19 --- /dev/null +++ b/tests/test_mutate_embedded_identity.py @@ -0,0 +1,41 @@ +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +from mutate_embedded_identity import mutate + +IDENTITY = ( + b"llamadart-native-build/1;owner=a;llama.cpp=b;ggml=c;patches=d;" + b"config=Release;compiler=GCC;target=x;backends=cpu;options=e" +) + + +class MutateEmbeddedIdentityTest(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.module = Path(directory.name) / "module.so" + + def test_rewrites_one_field_preserving_size(self): + contents = b"ELF\0" + IDENTITY + b"\0" + self.module.write_bytes(contents) + mutate(self.module, "owner", "f") + self.assertEqual(self.module.read_bytes(), contents.replace(b"owner=a", b"owner=f")) + + def test_requires_exactly_one_identity(self): + for contents in (b"ELF", IDENTITY + b"\0" + IDENTITY): + with self.subTest(contents=contents): + self.module.write_bytes(contents) + with self.assertRaisesRegex(ValueError, "exactly one"): + mutate(self.module, "owner") + self.assertEqual(self.module.read_bytes(), contents) + + def test_refuses_new_length_or_unknown_field(self): + self.module.write_bytes(IDENTITY) + with self.assertRaisesRegex(ValueError, "same length"): + mutate(self.module, "owner", "ff") + with self.assertRaisesRegex(ValueError, "unknown field"): + mutate(self.module, "missing") + self.assertEqual(self.module.read_bytes(), IDENTITY) diff --git a/tests/test_openvino_env_contract.py b/tests/test_openvino_env_contract.py new file mode 100644 index 00000000..ae7a7ecd --- /dev/null +++ b/tests/test_openvino_env_contract.py @@ -0,0 +1,46 @@ +import re +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +UPSTREAM = ROOT / "third_party/llama.cpp/ggml/src/ggml-openvino" +EXPECTED_TYPES = { + "DEVICE": "STR", "CACHE_DIR": "STR", "STATEFUL_EXECUTION": "BOOL", + "PROFILING": "INT", "LOG_UNSUPPORTED_OPS": "BOOL", "LOG_SUPPORTS_OP": "INT", + "NPU_COMPILER_TYPE": "STR", +} + + +def upstream_settings(source): + table = source.split("constexpr env_var env_vars[] = {", 1)[1].split("};", 1)[0] + return dict(re.findall(r'\{"GGML_OPENVINO_([A-Z0-9_]+)", env_type::(\w+)', table)) + + +def abort_sites(sources): + return { + f"{name}:{source.count(chr(10), 0, match.start()) + 1}" + for name, source in sources.items() + for match in re.finditer(r"\bGGML_ABORT\s*\(", source) + } + + +class OpenVINOEnvContractTest(unittest.TestCase): + def test_allowlist_matches_the_reviewed_upstream_types(self): + source = (UPSTREAM / "ggml-openvino-extra.cpp").read_text() + types = upstream_settings(source) + self.assertEqual({name: types.get(name) for name in EXPECTED_TYPES}, EXPECTED_TYPES) + owner = (ROOT / "src/llama_dart_openvino.cpp").read_text() + gate = owner.split("std::string invalid_setting", 1)[0] + self.assertEqual(set(re.findall(r'"GGML_OPENVINO_([A-Z0-9_]+)"', gate)), set(EXPECTED_TYPES)) + changed = source.replace('{"GGML_OPENVINO_PROFILING", env_type::INT', + '{"GGML_OPENVINO_PROFILING", env_type::STR') + self.assertNotEqual(upstream_settings(changed)["PROFILING"], EXPECTED_TYPES["PROFILING"]) + + def test_reviewed_abort_sites_cover_the_pinned_upstream(self): + reviewed = (ROOT / "tests/fixtures/openvino_abort_sites.txt").read_text().splitlines() + sites = {line.split(" ", 1)[0] for line in reviewed if line and not line.startswith("#")} + sources = {path.relative_to(UPSTREAM).as_posix(): path.read_text() + for path in UPSTREAM.rglob("*") if path.suffix in {".cpp", ".c", ".hpp", ".h"}} + self.assertEqual(abort_sites(sources), sites) + changed = {**sources, "new.cpp": 'GGML_ABORT("new abort");\n'} + self.assertNotEqual(abort_sites(changed), sites) diff --git a/tests/test_openvino_identity_fields.py b/tests/test_openvino_identity_fields.py new file mode 100644 index 00000000..55bb955f --- /dev/null +++ b/tests/test_openvino_identity_fields.py @@ -0,0 +1,16 @@ +import re +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +from validate_openvino_sidecar import PAIRED_FIELDS + + +class OpenVINOIdentityFieldsTest(unittest.TestCase): + def test_runtime_and_packaged_validator_compare_the_same_five_fields(self): + header = (ROOT / "src/llama_dart_openvino_identity.h").read_text() + fields = re.search(r"paired_fields\[\] = \{([^}]+)\}", header)[1] + self.assertEqual(tuple(re.findall(r'"([^"]+)"', fields)), PAIRED_FIELDS) + self.assertEqual(len(PAIRED_FIELDS), 5) diff --git a/tests/test_openvino_plugins_xml.py b/tests/test_openvino_plugins_xml.py new file mode 100644 index 00000000..e10a9770 --- /dev/null +++ b/tests/test_openvino_plugins_xml.py @@ -0,0 +1,21 @@ +import sys +import unittest +from pathlib import Path +from xml.etree import ElementTree + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +from package_openvino_sidecar import plugin_xml + + +class OpenVINOPluginsXmlTest(unittest.TestCase): + def test_packaged_text_names_all_seven_devices_with_bare_locations(self): + header = (ROOT / "src/llama_dart_openvino_plugins.h").read_bytes() + expected = header.split(b'R"xml(', 1)[1].split(b')xml"', 1)[0] + self.assertEqual(plugin_xml(), expected) + plugins = ElementTree.fromstring(expected).findall("./plugins/plugin") + self.assertEqual(len(plugins), 7) + self.assertEqual({entry.attrib["name"] for entry in plugins}, + {"NPU", "CPU", "GPU", "AUTO", "MULTI", "HETERO", "BATCH"}) + for entry in plugins: + self.assertRegex(entry.attrib["location"], r"^libopenvino_[a-z0-9_]+_plugin\.so$") diff --git a/tests/test_openvino_sdk.py b/tests/test_openvino_sdk.py new file mode 100644 index 00000000..5042a9ec --- /dev/null +++ b/tests/test_openvino_sdk.py @@ -0,0 +1,50 @@ +import io +import sys +import tarfile +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import openvino_sdk as sdk + + +class OpenVINOSDKTest(unittest.TestCase): + def test_refuses_bytes_that_fail_the_pin(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + archive = root / "fixture.tar.gz" + archive.write_bytes(b"test") + with self.assertRaisesRegex(ValueError, "size or SHA-256 mismatch"): + sdk.extract(archive, root / "sdk") + self.assertFalse((root / "sdk").exists()) + + @unittest.skipUnless(hasattr(tarfile, "data_filter"), "SDK extraction requires the data filter") + def test_checks_archive_paths_even_with_validated_bytes(self): + for name, target, refused in ( + (f"{sdk.SDK_DIRECTORY}/lib/fixture.so", None, False), + (f"{sdk.SDK_DIRECTORY}/../../outside", None, True), + (f"{sdk.SDK_DIRECTORY}/outside-link", "../../outside", True), + ): + with self.subTest(name=name), tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + archive = root / "fixture.tar.gz" + with tarfile.open(archive, "w:gz") as tar: + member = tarfile.TarInfo(name) + if target is None: + member.size = 1 + tar.addfile(member, io.BytesIO(b"x")) + else: + member.type = tarfile.SYMTYPE + member.linkname = target + tar.addfile(member) + with patch.object(sdk, "SIZE", archive.stat().st_size), patch.object(sdk, "SHA256", sdk.sha256(archive)): + if refused: + with self.assertRaises((ValueError, tarfile.FilterError)): + sdk.extract(archive, root / "sdk") + else: + result = sdk.extract(archive, root / "sdk") + self.assertEqual((result / "lib/fixture.so").read_bytes(), b"x") + self.assertFalse((root / "outside").exists()) diff --git a/tests/test_package_openvino_sidecar.py b/tests/test_package_openvino_sidecar.py new file mode 100644 index 00000000..1215b69e --- /dev/null +++ b/tests/test_package_openvino_sidecar.py @@ -0,0 +1,58 @@ +import json +import sys +import tarfile +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import package_openvino_sidecar as package +from test_mutate_embedded_identity import IDENTITY + + +class OpenVINOPackageTest(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + self.sdk = self.root / "sdk" + self.build = self.root / "build" + self.payload = self.root / "payload" + self.build.mkdir() + (self.build / package.MODULE).write_bytes(b"ELF\0" + IDENTITY + b"\0") + (self.build / "libOpenCL.so.1").write_bytes(b"OpenCL") + for filename, source in package.SDK_LIBS.items(): + path = self.sdk / source + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(filename.encode()) + self.sdk_licenses = self.sdk / "docs/licensing" + self.sdk_licenses.mkdir(parents=True) + (self.sdk_licenses / "EULA.txt").write_bytes(b"license fixture") + package.assemble(self.build, self.sdk, self.payload) + + def test_manifest_lists_every_payload_file_and_notice(self): + manifest = json.loads((self.payload / package.MANIFEST).read_text()) + self.assertEqual(manifest["build_identity"], IDENTITY.decode()) + self.assertEqual(manifest["llama_cpp_commit"], "b") + self.assertEqual(manifest["devices"], ["NPU"]) + names = {entry["name"] for entry in manifest["files"]} + self.assertEqual(names | {package.MANIFEST, "licenses"}, {path.name for path in self.payload.iterdir()}) + for entry in manifest["files"]: + path = self.payload / entry["name"] + self.assertEqual(entry["sha256"], package.sha256(path)) + self.assertEqual(entry["size"], path.stat().st_size) + self.assertIn("licenses/openvino/EULA.txt", manifest["notices"]) + self.assertEqual((self.payload / "licenses/openvino/EULA.txt").read_bytes(), + (self.sdk_licenses / "EULA.txt").read_bytes()) + + def test_archive_is_byte_reproducible_and_uses_regular_files(self): + first, second = self.root / "one.tar.gz", self.root / "two.tar.gz" + package.archive(self.payload, first) + package.archive(self.payload, second) + self.assertEqual(first.read_bytes(), second.read_bytes()) + with tarfile.open(first) as archive: + self.assertEqual(archive.getnames(), sorted(archive.getnames())) + for entry in archive: + self.assertTrue(entry.isfile() or entry.isdir()) + self.assertEqual(entry.mtime, 0) diff --git a/tests/test_publish_prepared.py b/tests/test_publish_prepared.py index 09917124..7481c02f 100644 --- a/tests/test_publish_prepared.py +++ b/tests/test_publish_prepared.py @@ -133,7 +133,7 @@ def prepare(self): def test_exact_bytes_source_and_policy_derived_wrapper_prerelease(self): report, desired = self.prepare() self.assertEqual(self.source_result, report['source']); self.assertTrue(desired.prerelease) - self.assertEqual(16, len(desired.assets)); self.assertIn(self.expected.run_url, desired.body) + self.assertEqual(17, len(desired.assets)); self.assertIn(self.expected.run_url, desired.body) self.assertIn('a' * 40, desired.body); self.assertEqual(self.expected.native_commit, git(self.reader, 'rev-parse', 'refs/remotes/prepared/release-provenance')) for path in (self.files / 'release_assets').iterdir(): self.assertEqual(path.read_bytes(), (self.temp / 'verified/prepared/release_assets' / path.name).read_bytes()) @@ -150,7 +150,7 @@ def test_untrusted_run_controls(self): with self.assertRaises(ContractError): prepared.validate_run(self.expected, run, self.jobs) def test_all_required_smoke_matrix_and_skip_gates(self): - for name in ['smoke-release-contract', 'package-and-release', self.jobs[len(prepared.SUCCESS_JOBS)]['name']]: + for name in ['smoke-release-contract', 'openvino-sidecar-pair', 'package-and-release', self.jobs[len(prepared.SUCCESS_JOBS)]['name']]: for mutation in ['missing', 'failure', 'skipped']: jobs = copy.deepcopy(self.jobs) if mutation == 'missing': jobs = [j for j in jobs if j['name'] != name] diff --git a/tests/test_validate_exports.py b/tests/test_validate_exports.py index 110a4259..c8fcd301 100644 --- a/tests/test_validate_exports.py +++ b/tests/test_validate_exports.py @@ -56,8 +56,8 @@ def test_speculative_retirement_inventory_retains_nextn_query(self): self.assertEqual(len(retiring), 15) required = set(validate_exports.DEFAULT_REQUIRED_SYMBOLS) self.assertFalse(required & retiring) - self.assertEqual(len(validate_exports.DEFAULT_REQUIRED_SYMBOLS), 122) - self.assertEqual(len(required), 122) + self.assertEqual(len(validate_exports.DEFAULT_REQUIRED_SYMBOLS), 125) + self.assertEqual(len(required), 125) self.assertIn('llama_dart_speculative_need_embd_nextn', required) self.assertEqual(len(validate_exports.RETIRED_SPECULATIVE_SYMBOLS), 15) self.assertEqual(set(validate_exports.RETIRED_SPECULATIVE_SYMBOLS), retiring) @@ -88,7 +88,17 @@ def test_full_surviving_export_inventory_is_accepted(self): result, diagnostics = self.validate_synthetic_exports( validate_exports.DEFAULT_REQUIRED_SYMBOLS) self.assertEqual(result, 0, diagnostics) - self.assertIn('Validated 122 required export(s)', diagnostics) + self.assertIn('Validated 125 required export(s)', diagnostics) + + def test_every_openvino_owner_export_is_required(self): + for name in ("api_version", "probe", "open"): + symbol = f"llama_dart_openvino_{name}" + with self.subTest(symbol=symbol): + self.assertIn(symbol, validate_exports.DEFAULT_REQUIRED_SYMBOLS) + result, diagnostics = self.validate_synthetic_exports( + s for s in validate_exports.DEFAULT_REQUIRED_SYMBOLS if s != symbol) + self.assertEqual(result, 1, diagnostics) + self.assertIn(f' - {symbol}\n', diagnostics) def test_file_hash_requires_both_version_and_operation(self): for name in ('llama_dart_file_sha256', 'llama_dart_file_sha256_api_version'): diff --git a/tests/test_validate_openvino_sidecar.py b/tests/test_validate_openvino_sidecar.py new file mode 100644 index 00000000..2709979c --- /dev/null +++ b/tests/test_validate_openvino_sidecar.py @@ -0,0 +1,93 @@ +import json +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from test_package_openvino_sidecar import OpenVINOPackageTest +from validate_openvino_sidecar import ( + MODULE, RUNTIME, RUNTIME_NEEDED, validate, validate_pair, +) +from test_mutate_embedded_identity import IDENTITY + + +class OpenVINOValidatorTest(unittest.TestCase): + def setUp(self): + fixture = OpenVINOPackageTest() + fixture.setUp() + self.addCleanup(fixture.doCleanups) + self.sdk, self.payload = fixture.sdk, fixture.payload + runtime = self.payload / RUNTIME + plugin = b"\0" + b"libopenvino_intel_npu_plugin.so" + b"\0" + for path in (runtime, self.sdk / "runtime/lib/intel64/libopenvino.so.2026.4.1"): + path.write_bytes(path.read_bytes() + plugin) + from package_openvino_sidecar import manifest, notice_text + (self.payload / "licenses/NOTICE.md").write_text(notice_text(self.payload)) + (self.payload / "llamadart-sidecar.json").write_text(json.dumps(manifest(self.payload))) + self.dynamic = {"RPATH": ["$ORIGIN"], "NEEDED": sorted(RUNTIME_NEEDED | {"libggml-base.so.1"})} + self.header = "ELF64 Advanced Micro Devices X86-64" + self.symbol_table = "" + + def verify(self): + with patch("validate_openvino_sidecar.dynamic", return_value=self.dynamic), \ + patch("validate_openvino_sidecar.elf", side_effect=lambda _, kind: ( + self.header if kind == "--file-header" else self.symbol_table)): + validate(self.payload, self.sdk) + + def test_baseline_and_dynamic_and_floor_mutations(self): + self.verify() + for tags, message in ( + ({"RUNPATH": ["$ORIGIN"], "NEEDED": self.dynamic["NEEDED"]}, "DT_RPATH"), + ({**self.dynamic, "NEEDED": ["libggml-base.so.1"]}, "missing direct dependencies"), + ({**self.dynamic, "NEEDED": [*self.dynamic["NEEDED"], "libggml.so.1"]}, "ggml registry"), + ): + with self.subTest(message=message): + with patch.object(self, "dynamic", tags), self.assertRaisesRegex(ValueError, message): + self.verify() + with patch.object(self, "symbol_table", " UND sqrtf@GLIBC_2.43"), \ + self.assertRaisesRegex(ValueError, "glibc imports exceed"): + self.verify() + + def test_sidecar_layout_and_content_mutations(self): + module = self.payload / MODULE + renamed = self.payload / "libggml-openvino.so" + module.rename(renamed) + with self.assertRaisesRegex(ValueError, "unexpected or missing entries"): + self.verify() + renamed.rename(module) + target = self.payload / "plugins.xml" + original = target.read_bytes() + target.write_bytes(original + b" ") + with self.assertRaisesRegex(ValueError, "plugins.xml differs"): + self.verify() + target.unlink() + target.symlink_to(module) + with self.assertRaisesRegex(ValueError, "regular file"): + self.verify() + target.unlink() + target.write_bytes(original) + (self.payload / "licenses/openvino/EULA.txt").write_bytes(b"modified") + with self.assertRaisesRegex(ValueError, "SDK license bytes differ"): + self.verify() + + def test_paired_core_rejects_same_identity_and_mismatched_fields(self): + with tempfile.TemporaryDirectory() as temporary: + core = Path(temporary) + library = core / "libllamadart.so" + library.write_bytes(IDENTITY.replace(b"backends=cpu", b"backends=cpu,vulkan")) + needed = self.dynamic["NEEDED"] + with patch("validate_openvino_sidecar.dynamic", return_value={"SONAME": ["libggml-base.so.1"]}), \ + patch("validate_openvino_sidecar.symbols", side_effect=[ + ({"ggml_time_us"}, set()), (set(), {"ggml_time_us"}), + ]): + validate_pair(self.payload, core, needed) + library.write_bytes(IDENTITY) + with self.assertRaisesRegex(ValueError, "independently built release core"): + validate_pair(self.payload, core, needed) + library.write_bytes(IDENTITY.replace(b"owner=a", b"owner=q")) + with self.assertRaisesRegex(ValueError, "build identity: owner"): + validate_pair(self.payload, core, needed) + library.write_bytes(IDENTITY.replace(b"backends=cpu", b"backends=cpu,vulkan")) + with patch("validate_openvino_sidecar.dynamic", return_value={"SONAME": ["libggml-base.so.1"]}), \ + self.assertRaisesRegex(ValueError, "ggml-base dependency"): + validate_pair(self.payload, core, []) diff --git a/tools/build.py b/tools/build.py index 574c53a8..087646ed 100755 --- a/tools/build.py +++ b/tools/build.py @@ -12,6 +12,7 @@ from pathlib import Path from typing import NoReturn +import openvino_sdk import windows_runtime REPO_ROOT = Path(__file__).resolve().parents[1] @@ -128,7 +129,7 @@ def linux_arm64_cpu_variant_libs() -> tuple[str, ...]: WINDOWS_VCPKG_TRIPLETS = {"x64": "x64-windows", "arm64": "arm64-windows"} ANDROID_BACKENDS = ("full", "vulkan", "opencl") -LINUX_BACKENDS = ("full", "cpu", "vulkan", "cuda", "hip", "blas") +LINUX_BACKENDS = ("full", "cpu", "vulkan", "cuda", "hip", "blas", "openvino") WINDOWS_BACKENDS = ("full", "vulkan", "cuda", "blas") def fail(message: str) -> NoReturn: @@ -242,12 +243,13 @@ def cmake_cache_args(cache_vars: dict[str, str]) -> list[str]: def linux_backend_cache_vars(arch: str, backend: str) -> dict[str, str]: - if backend in ("cuda", "hip") and arch != "x64": + if backend in ("cuda", "hip", "openvino") and arch != "x64": fail(f"Linux {backend} backend build is only available for x64") cache_vars: dict[str, str] = { "GGML_VULKAN": "OFF", "GGML_OPENCL": "OFF", + "GGML_OPENVINO": "ON" if backend == "openvino" else "OFF", "GGML_CUDA": "OFF", "GGML_HIP": "OFF", "GGML_BLAS": "OFF", @@ -923,6 +925,46 @@ def build_apple(args: argparse.Namespace) -> None: copy_runtime_libraries(build_dir, out_dir) +def build_linux_openvino(args: argparse.Namespace, preset: str, cache_vars: dict[str, str]) -> None: + if detect_linux_arch() != "x64": + fail("OpenVINO requires a Linux x64 host") + if args.openvino_sdk is None: + fail("OpenVINO requires --openvino-sdk from tools/openvino_sdk.py") + sdk = args.openvino_sdk.resolve() + openvino_cmake = sdk / "runtime/cmake" + opencl_cpp_headers = args.opencl_cpp_headers or sdk.parent + for name in openvino_sdk.CLHPP_HEADERS: + ensure_submodule(opencl_cpp_headers / "CL" / name, "Fetch OpenCL C++ headers with --with-opencl-headers") + if openvino_sdk.sha256(opencl_cpp_headers / "CL" / name) != openvino_sdk.CLHPP_HEADERS[name]: + fail(f"OpenCL C++ header does not match the pin: {name}") + ensure_submodule(openvino_cmake / "OpenVINOConfig.cmake", "Missing OpenVINO SDK CMake configuration") + ensure_submodule(OPENCL_LOADER_DIR / "CMakeLists.txt", "Missing OpenCL-ICD-Loader submodule") + ensure_submodule(OPENCL_HEADERS_DIR / "CL/cl.h", "Missing OpenCL-Headers submodule") + + build_dir = BUILD_ROOT / "linux-x64-openvino" + clean_build_dir(build_dir.name, args.clean) + loader = build_dir / "opencl-icd-loader" + jobs = ["--parallel", str(args.jobs)] if args.jobs else [] + run([ + "cmake", "-S", str(OPENCL_LOADER_DIR), "-B", str(loader), "-G", "Ninja", + "-DCMAKE_BUILD_TYPE=Release", "-DENABLE_OPENCL_LAYERS=OFF", + "-DENABLE_OPENCL_LAYERINFO=OFF", "-DBUILD_TESTING=OFF", + f"-DOPENCL_ICD_LOADER_HEADERS_DIR={OPENCL_HEADERS_DIR}", + ]) + run(["cmake", "--build", str(loader), *jobs]) + opencl = find_file_with_suffix(loader, "libOpenCL.so") + run([ + "cmake", "--preset", preset, "-B", str(build_dir), *cmake_cache_args(cache_vars), + f"-DOpenVINO_DIR={openvino_cmake}", f"-DOpenCL_INCLUDE_DIR={OPENCL_HEADERS_DIR}", + f"-DOpenCL_LIBRARY={opencl}", f"-DLLAMADART_OPENCL_CPP_HEADERS={opencl_cpp_headers.resolve()}", + f"-DLLAMADART_OPENVINO_RUNTIME_BUILD={openvino_sdk.RUNTIME_BUILD}", + ]) + run(["cmake", "--build", str(build_dir), "--target", "ggml-openvino", *jobs]) + output = BIN_DIR / "linux/x64/openvino" + copy_output(find_file_with_suffix(build_dir, "libllamadart-openvino.so"), output / "libllamadart-openvino.so") + copy_output(opencl.resolve(), output / "libOpenCL.so.1") + + def build_linux(args: argparse.Namespace) -> None: if platform.system().lower() != "linux": fail("Linux builds must be run on Linux hosts") @@ -934,9 +976,12 @@ def build_linux(args: argparse.Namespace) -> None: arch = args.arch or detect_linux_arch() backend = args.backend preset = f"linux-{arch}-full" + cache_vars = linux_backend_cache_vars(arch, backend) + if backend == "openvino": + build_linux_openvino(args, preset, cache_vars) + return clean_build_dir(preset, args.clean) - cache_vars = linux_backend_cache_vars(arch, backend) if cache_vars["GGML_VULKAN"] == "ON": ensure_vulkan_header_submodules() @@ -1125,7 +1170,7 @@ def build_windows(args: argparse.Namespace) -> None: def print_presets() -> None: presets = [ "apple: target=macos-arm64|macos-x86_64|ios-device-arm64|ios-sim-arm64|ios-sim-x86_64 (consolidated: metal+cpu in one dylib)", - "linux: arch=x64|arm64 backend=full|cpu|vulkan|cuda|hip|blas (x64 full=vulkan+cuda+blas+cpu, arm64 full=vulkan+blas+kleidi+cpu, arm64 full|cpu|vulkan add runtime-selected CPU variants, hip=x64 only)", + "linux: arch=x64|arm64 backend=full|cpu|vulkan|cuda|hip|blas|openvino (x64 full=vulkan+cuda+blas+cpu, arm64 full=vulkan+blas+kleidi+cpu, arm64 full|cpu|vulkan add runtime-selected CPU variants, hip/openvino=x64 only)", "android: abi=arm64-v8a|x86_64|all backend=full|vulkan|opencl (arm64 builds isolated CPU variants so Kleidi stays enabled where safe; x86_64 full=vulkan+opencl+cpu)", "windows: arch=x64|arm64 backend=full|vulkan|cuda|blas (x64 full=vulkan+cuda+blas+cpu, arm64 full=vulkan+blas+kleidi+cpu)", ] @@ -1175,6 +1220,8 @@ def parse_args() -> argparse.Namespace: linux = subparsers.add_parser("linux", help="Build Linux shared libraries") linux.add_argument("--arch", choices=["x64", "arm64"], default=None) linux.add_argument("--backend", choices=LINUX_BACKENDS, default="full") + linux.add_argument("--openvino-sdk", type=Path) + linux.add_argument("--opencl-cpp-headers", type=Path) add_common_args(linux) linux.set_defaults(func=build_linux) diff --git a/tools/ci_scope.py b/tools/ci_scope.py index 1eabbbcb..b19161fb 100644 --- a/tools/ci_scope.py +++ b/tools/ci_scope.py @@ -79,7 +79,7 @@ def validate_results(needs): expected = 'success' if selected == 'true' else 'skipped' jobs = {'android-arm64-isa', 'android-vulkan-shaders', 'kleidiai-dispatch-emulated', 'windows-arm64-kleidiai', 'windows-arm64-vulkan', 'windows-x64-runtime-closure', - 'linux-artifact-contract', + 'linux-artifact-contract', 'openvino-sidecar-contract', 'wrapper-contract', 'msvc-mtmd-link-contract', 'macos-exit-teardown'} return set(needs) == jobs | {'changes'} and all( needs[job].get('result') == expected for job in jobs diff --git a/tools/mutate_embedded_identity.py b/tools/mutate_embedded_identity.py new file mode 100644 index 00000000..f14ba673 --- /dev/null +++ b/tools/mutate_embedded_identity.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""Rewrite one field of the single identity embedded in a test library.""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +from validate_build_identity import IDENTITY, KEYS + + +def read_identity(contents: bytes) -> tuple[int, int, dict[str, str]]: + matches = list(IDENTITY.finditer(contents)) + if len(matches) != 1: + raise ValueError("expected exactly one embedded build identity") + match = matches[0] + fields: dict[str, str] = {} + for field in match[0].decode().split(";")[1:]: + key, _, value = field.partition("=") + if not value or key in fields: + raise ValueError("malformed embedded build identity") + fields[key] = value + if tuple(fields) != KEYS: + raise ValueError("incomplete embedded build identity") + return match.start(), match.end(), fields + + +def mutate(path: Path, field: str, replacement: str | None = None) -> None: + contents = path.read_bytes() + start, end, fields = read_identity(contents) + if field not in fields: + raise ValueError(f"unknown field: {field}") + value = fields[field] + if replacement is None: + replacement = value[:-1] + ("0" if value[-1] != "0" else "1") + if len(replacement) != len(value): + raise ValueError("replacement must have the same length") + if replacement == value or any( + not (c.isascii() and (c.isalnum() or c in "._+,-")) for c in replacement + ): + raise ValueError("replacement must be a different valid identity value") + before = f"{field}={value}".encode() + after = f"{field}={replacement}".encode() + stamp = contents[start:end].split(b";") + stamp[stamp.index(before)] = after + path.write_bytes(contents[:start] + b";".join(stamp) + contents[end:]) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("module", type=Path) + parser.add_argument("field", choices=KEYS) + parser.add_argument("--replacement") + args = parser.parse_args() + try: + mutate(args.module, args.field, args.replacement) + except (OSError, ValueError) as error: + parser.exit(1, f"{error}\n") + + +if __name__ == "__main__": + main() diff --git a/tools/openvino_sdk.py b/tools/openvino_sdk.py new file mode 100644 index 00000000..4cf4450b --- /dev/null +++ b/tools/openvino_sdk.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""Fetch the pinned Linux x64 OpenVINO SDK and OpenCL C++ headers.""" + +from __future__ import annotations + +import argparse +import hashlib +import tarfile +import tempfile +import urllib.request +from pathlib import Path, PurePosixPath + +VERSION = "2026.4.1.22982.07f9c262b05" +RUNTIME_BUILD = "2026.4.1-22982-e213a147257-releases/2026/4" +SDK_DIRECTORY = f"openvino_toolkit_ubuntu24_{VERSION}_x86_64" +URL = f"https://storage.openvinotoolkit.org/repositories/openvino/packages/2026.4/linux/{SDK_DIRECTORY}.tgz" +SIZE = 121_681_483 +SHA256 = "772ce52d9b0aa375c77d391fccea71450d889c98b9af197bb8f05167a9dabd87" + +CLHPP_VERSION = "v2025.07.22" +CLHPP_HEADERS = { + "cl2.hpp": "f0b1b551739bc706f07b3053ebdc164e4abe2b6cdaa1620dd3665cbfba3d769b", + "opencl.hpp": "3fd79183c830ba998b9cd3ea053050d6bbdd6f7099dc5c181a9d1f6fc75968cf", +} + + +def fetch_opencl_headers(output: Path) -> None: + base = f"https://raw.githubusercontent.com/KhronosGroup/OpenCL-CLHPP/{CLHPP_VERSION}/include/CL/" + with tempfile.TemporaryDirectory(dir=output) as temporary: + headers = Path(temporary) / "CL" + headers.mkdir() + for name, expected in CLHPP_HEADERS.items(): + with urllib.request.urlopen(base + name, timeout=120) as response: + content = response.read(512 * 1024) + if hashlib.sha256(content).hexdigest() != expected: + raise ValueError(f"OpenCL C++ header SHA-256 mismatch: {name}") + (headers / name).write_bytes(content) + headers.rename(output / "CL") + + +def sha256(path: Path) -> str: + with path.open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def extract(archive: Path, output: Path) -> Path: + if archive.stat().st_size != SIZE or sha256(archive) != SHA256: + raise ValueError("OpenVINO SDK archive size or SHA-256 mismatch") + output.mkdir(parents=True, exist_ok=True) + destination = output / SDK_DIRECTORY + with tempfile.TemporaryDirectory(dir=output) as temporary: + root = Path(temporary) + with tarfile.open(archive, "r:gz") as sdk: + for member in sdk: + parts = PurePosixPath(member.name).parts + if not parts or parts[0] != SDK_DIRECTORY or ".." in parts: + raise ValueError("OpenVINO SDK archive entry outside SDK directory") + sdk.extract(member, root, filter="data") + (root / SDK_DIRECTORY).rename(destination) + return destination + + +def fetch(output: Path, archive: Path | None = None) -> Path: + if archive is not None: + return extract(archive, output) + with tempfile.TemporaryDirectory() as temporary: + download = Path(temporary) / "openvino.tgz" + with urllib.request.urlopen(URL, timeout=120) as response, download.open("wb") as stream: + remaining = SIZE + while chunk := response.read(min(1024 * 1024, remaining + 1)): + if len(chunk) > remaining: + raise ValueError("OpenVINO SDK archive exceeds pinned size") + stream.write(chunk) + remaining -= len(chunk) + return extract(download, output) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--archive", type=Path) + parser.add_argument("--with-opencl-headers", action="store_true") + args = parser.parse_args() + try: + sdk = fetch(args.output, args.archive) + if args.with_opencl_headers: + fetch_opencl_headers(args.output) + print(sdk) + except (OSError, ValueError, tarfile.TarError) as error: + parser.exit(1, f"{error}\n") + + +if __name__ == "__main__": + main() diff --git a/tools/package_openvino_sidecar.py b/tools/package_openvino_sidecar.py new file mode 100644 index 00000000..0da12048 --- /dev/null +++ b/tools/package_openvino_sidecar.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Build the flat Linux x64 OpenVINO sidecar from its owner build and pinned SDK.""" + +from __future__ import annotations + +import argparse +import gzip +import json +from pathlib import Path +import re +import shutil +import tarfile + +from check_glibc_floor import GLIBC_FLOOR +from mutate_embedded_identity import read_identity +from openvino_sdk import SHA256, VERSION, sha256 + +ROOT = Path(__file__).resolve().parents[1] +MODULE = "libllamadart-openvino.so" +RUNTIME = "libopenvino.so.2641" +MANIFEST = "llamadart-sidecar.json" +ICD_LICENSE = "licenses/OpenCL-ICD-Loader-LICENSE" +NOTICE = "licenses/NOTICE.md" +SDK_LIBS = { + RUNTIME: "runtime/lib/intel64/libopenvino.so.2026.4.1", + "libopenvino_intel_npu_plugin.so": "runtime/lib/intel64/libopenvino_intel_npu_plugin.so", + "libopenvino_intel_npu_compiler_loader.so": "runtime/lib/intel64/libopenvino_intel_npu_compiler_loader.so", + "libopenvino_intel_npu_vm_runtime.so": "runtime/lib/intel64/libopenvino_intel_npu_vm_runtime.so", + "libtbb.so.12": "runtime/3rdparty/tbb/lib/libtbb.so.12.13", +} +LICENSES = {name: "Intel-OpenVINO-EULA" for name in SDK_LIBS} +LICENSES.update({MODULE: "MIT", "plugins.xml": "MIT", "libOpenCL.so.1": "Apache-2.0", "libtbb.so.12": "Apache-2.0"}) + + +def plugin_xml() -> bytes: + header = (ROOT / "src/llama_dart_openvino_plugins.h").read_bytes() + match = re.search(rb'llama_dart_openvino_plugins_xml\[\] = R"xml\((.*?)\)xml";', header, re.DOTALL) + if match is None: + raise ValueError("OpenVINO plugin list is missing from the owner header") + return match[1] + + +def file_record(path: Path) -> dict: + role = {MODULE: "module", "plugins.xml": "config"}.get(path.name, "runtime") + return { + "name": path.name, "role": role, "sha256": sha256(path), + "size": path.stat().st_size, "license": LICENSES[path.name], + } + + +def manifest(directory: Path) -> dict: + module = (directory / MODULE).read_bytes() + start, end, identity = read_identity(module) + upstream = ROOT / "third_party/llama.cpp/ggml/src/ggml-backend-impl.h" + backend_version = re.search(r"^\s*#define GGML_BACKEND_API_VERSION (\d+)$", upstream.read_text(), re.MULTILINE) + if backend_version is None: + raise ValueError("ggml backend ABI version is missing") + return { + "schema": 1, + "bundle": "linux-x64", + "backend": "openvino", + "module": MODULE, + "owner_api_version": 1, + "shim_abi": 1, + "build_identity": module[start:end].decode(), + "llama_cpp_commit": identity["llama.cpp"].split("+dirty.")[0], + "ggml_backend_api_version": int(backend_version[1]), + "openvino": {"version": VERSION, "archive_sha256": SHA256}, + "glibc_floor": ".".join(map(str, GLIBC_FLOOR)), + "devices": ["NPU"], + "files": [file_record(directory / name) for name in sorted(LICENSES)], + "notices": sorted(path.relative_to(directory).as_posix() + for path in (directory / "licenses").rglob("*") if path.is_file()), + } + + +def notice_text(directory: Path) -> str: + files = "\n".join( + f'- `{name}` (`{sha256(directory / name)}`)' + for name in SDK_LIBS if LICENSES[name] == "Intel-OpenVINO-EULA" + ) + return f"""# OpenVINO sidecar notices + +The Intel binaries below are distributed under the Intel OpenVINO Distribution +License. See `openvino/EULA.txt` and `openvino/redist.txt`. + +{files} + +`libtbb.so.12` is distributed under Apache-2.0. See +`openvino/Apache_license.txt` and `openvino/onetbb_third-party-programs.txt`. + +`libOpenCL.so.1` is built from the Khronos OpenCL ICD Loader and uses +`OpenCL-ICD-Loader-LICENSE`. The owner module uses the Khronos OpenCL C++ +headers under the same Apache-2.0 license. + +Applications bundling this sidecar must pass these notices and license files +to their users. +""" + + +def assemble(build_dir: Path, sdk: Path, directory: Path) -> None: + directory.mkdir(parents=True) + for name in (MODULE, "libOpenCL.so.1"): + shutil.copyfile(build_dir / name, directory / name) + for name, source in SDK_LIBS.items(): + shutil.copyfile(sdk / source, directory / name) + (directory / "plugins.xml").write_bytes(plugin_xml()) + shutil.copytree(sdk / "docs/licensing", directory / "licenses/openvino") + shutil.copyfile(ROOT / "third_party/OpenCL-ICD-Loader/LICENSE", directory / ICD_LICENSE) + (directory / NOTICE).write_text(notice_text(directory)) + (directory / MANIFEST).write_text(json.dumps(manifest(directory), indent=2) + "\n") + + +def archive(directory: Path, output: Path) -> None: + output.parent.mkdir(parents=True, exist_ok=True) + with output.open("wb") as stream, gzip.GzipFile(filename="", mode="wb", fileobj=stream, mtime=0) as gzip_stream: + with tarfile.open(mode="w|", fileobj=gzip_stream) as tar: + for path in sorted(directory.rglob("*")): + entry = tar.gettarinfo(str(path), path.relative_to(directory).as_posix()) + entry.uid = entry.gid = entry.mtime = 0 + entry.uname = entry.gname = "" + entry.mode = 0o755 if entry.isdir() else 0o644 + if entry.isfile(): + with path.open("rb") as contents: + tar.addfile(entry, contents) + else: + tar.addfile(entry) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--build-dir", required=True, type=Path) + parser.add_argument("--sdk", required=True, type=Path) + parser.add_argument("--directory", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + try: + assemble(args.build_dir, args.sdk, args.directory) + archive(args.directory, args.output) + except (OSError, ValueError) as error: + parser.exit(1, f"{error}\n") + + +if __name__ == "__main__": + main() diff --git a/tools/validate_exports.py b/tools/validate_exports.py index e6db4166..2e646bd9 100644 --- a/tools/validate_exports.py +++ b/tools/validate_exports.py @@ -13,6 +13,9 @@ DEFAULT_REQUIRED_SYMBOLS = [ "llama_dart_build_identity", + "llama_dart_openvino_api_version", + "llama_dart_openvino_probe", + "llama_dart_openvino_open", "llama_dart_file_sha256_api_version", "llama_dart_file_sha256", "llama_dart_last_error", diff --git a/tools/validate_openvino_sidecar.py b/tools/validate_openvino_sidecar.py new file mode 100644 index 00000000..ed4e148d --- /dev/null +++ b/tools/validate_openvino_sidecar.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +"""Validate an unpacked OpenVINO sidecar and optionally its release core pair.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import re +import subprocess +from xml.etree import ElementTree + +from check_glibc_floor import imports_above_floor +from mutate_embedded_identity import read_identity +from openvino_sdk import sha256 +from package_openvino_sidecar import ( + ICD_LICENSE, LICENSES, MANIFEST, MODULE, NOTICE, ROOT, RUNTIME, SDK_LIBS, + manifest, notice_text, plugin_xml, +) + +PAIRED_FIELDS = ("owner", "llama.cpp", "ggml", "patches", "target") +RUNTIME_NEEDED = {RUNTIME, "libtbb.so.12", "libOpenCL.so.1"} +PLUGIN_NAME = re.compile(rb"libopenvino_[a-z0-9_]+_plugin\.so") +EXPECTED_DEVICES = {"NPU", "CPU", "GPU", "AUTO", "MULTI", "HETERO", "BATCH"} + + +def require(condition: bool, message: str) -> None: + if not condition: + raise ValueError(message) + + +def elf(path: Path, *args: str) -> str: + return subprocess.check_output(["readelf", "--wide", *args, str(path)], text=True) + + +def dynamic(path: Path) -> dict[str, list[str]]: + values: dict[str, list[str]] = {} + for kind, value in re.findall(r"\((\w+)\)[^\n]*?\[([^\]]*)\]", elf(path, "--dynamic")): + values.setdefault(kind, []).append(value) + return values + + +def symbols(path: Path) -> tuple[set[str], set[str]]: + imports, exports = set(), set() + for line in elf(path, "--dyn-syms").splitlines(): + fields = line.split() + if len(fields) < 8 or not fields[0].endswith(":"): + continue + name = fields[7].split("@", 1)[0] + if name.startswith(("ggml_", "gguf_")): + (imports if fields[6] == "UND" else exports).add(name) + return imports, exports + + +def licenses_match(directory: Path, sdk: Path) -> None: + dist = directory / "licenses/openvino" + source = sdk / "docs/licensing" + shipped = {path.relative_to(dist) for path in dist.rglob("*")} + expected = {path.relative_to(source) for path in source.rglob("*")} + require(shipped == expected and bool(expected), "SDK licensing tree differs") + for relative in sorted(expected): + if (source / relative).is_file(): + require(sha256(dist / relative) == sha256(source / relative), + f"SDK license bytes differ: {relative}") + require(sha256(directory / ICD_LICENSE) == sha256(ROOT / "third_party/OpenCL-ICD-Loader/LICENSE"), + "OpenCL ICD Loader license differs") + require((directory / NOTICE).read_text() == notice_text(directory), "Sidecar notice differs") + + +def validate_pair(directory: Path, core: Path, needed: list[str]) -> None: + _, _, core_id = read_identity((core / "libllamadart.so").read_bytes()) + _, _, module_id = read_identity((directory / MODULE).read_bytes()) + require(core_id != module_id and "openvino" not in core_id["backends"].split(","), + "Expected the independently built release core") + for field in PAIRED_FIELDS: + require(core_id[field] == module_id[field], f"build identity: {field}") + + base = core / "libggml-base.so.1" + soname = dynamic(base).get("SONAME", []) + ggml_base = [name for name in needed if name.startswith("libggml-base.so")] + require(len(soname) == 1 and ggml_base == soname, "Module ggml-base dependency differs from the core SONAME") + imported, exported = symbols(directory / MODULE) + _, core_exports = symbols(base) + require(bool(imported) and imported <= core_exports, f"Missing ggml-base exports: {sorted(imported - core_exports)}") + require(not exported & core_exports, f"Module also exports ggml-base symbols: {sorted(exported & core_exports)}") + + +def validate(directory: Path, sdk: Path, core: Path | None = None) -> None: + require({path.name for path in directory.iterdir()} == {*LICENSES, MANIFEST, "licenses"}, + "Sidecar root contains unexpected or missing entries") + for path in directory.rglob("*"): + require(not path.is_symlink() and (path.is_file() or path.is_dir()), + f"Expected a regular file or directory: {path.name}") + require(all((directory / name).is_file() for name in (*LICENSES, MANIFEST)), + "Sidecar payload must use regular files") + require({path.name for path in (directory / "licenses").iterdir()} == + {"openvino", Path(ICD_LICENSE).name, Path(NOTICE).name}, "Sidecar licenses tree differs") + + module = directory / MODULE + tags = dynamic(module) + needed = tags.get("NEEDED", []) + require(tags.get("RPATH") == ["$ORIGIN"] and "RUNPATH" not in tags, "Module needs DT_RPATH $ORIGIN") + require(RUNTIME_NEEDED <= set(needed), f"Module is missing direct dependencies: {sorted(RUNTIME_NEEDED - set(needed))}") + require(not any(name.startswith(("libggml.so", "libllama")) for name in needed), + "Module links the ggml registry or llama") + + plugin_bytes = (directory / "plugins.xml").read_bytes() + require(plugin_bytes == plugin_xml(), "plugins.xml differs from the owner header") + plugins = list(ElementTree.fromstring(plugin_bytes).findall("./plugins/plugin")) + require({plugin.attrib["name"] for plugin in plugins} == EXPECTED_DEVICES, "Unexpected plugin device names") + locations = {plugin.attrib["location"] for plugin in plugins} + require(all(PLUGIN_NAME.fullmatch(name.encode()) for name in locations), "Plugin locations must use bare filenames") + runtime_plugins = {name.decode() for name in PLUGIN_NAME.findall((directory / RUNTIME).read_bytes())} + require(bool(runtime_plugins) and runtime_plugins <= locations, + f"Unlisted runtime plugins: {sorted(runtime_plugins - locations)}") + + for name, source in SDK_LIBS.items(): + require(sha256(directory / name) == sha256(sdk / source), f"SDK library bytes differ: {name}") + licenses_match(directory, sdk) + for name in LICENSES: + if name.endswith(".so") or ".so." in name: + library = directory / name + header = elf(library, "--file-header") + require("Advanced Micro Devices X86-64" in header and "ELF64" in header, + f"Expected Linux x64 ELF: {name}") + violations = imports_above_floor(elf(library, "--dyn-syms")) + require(not violations, f"{name}: glibc imports exceed the floor: {violations}") + + require(json.loads((directory / MANIFEST).read_text()) == manifest(directory), "Sidecar manifest differs") + if core is not None: + validate_pair(directory, core, needed) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("directory", type=Path) + parser.add_argument("--sdk", required=True, type=Path) + parser.add_argument("--core-dir", type=Path) + args = parser.parse_args() + try: + validate(args.directory, args.sdk, args.core_dir) + except (OSError, ValueError, subprocess.CalledProcessError) as error: + parser.exit(1, f"{error}\n") + print(f"PASS OpenVINO sidecar ({args.directory / MODULE})") + + +if __name__ == "__main__": + main() From 22c2868b0545399637a64be1d39d8741f10c6fce Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Tue, 1 Dec 2026 18:35:55 -0500 Subject: [PATCH 2/5] Fetch the exact OpenVINO SDK patch release --- tests/openvino_pair_smoke.cpp | 11 +++++++---- tools/openvino_sdk.py | 5 +++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/tests/openvino_pair_smoke.cpp b/tests/openvino_pair_smoke.cpp index a44a2cf1..e1e52dbf 100644 --- a/tests/openvino_pair_smoke.cpp +++ b/tests/openvino_pair_smoke.cpp @@ -74,26 +74,29 @@ bool openvino_registry_clean(size_t count) { return true; } -bool openvino_in_sidecar(const fs::path & directory) { +bool openvino_in_sidecar(const fs::path & directory, const fs::path & core) { const auto canonical = fs::canonical(directory); + const auto core_directory = fs::canonical(core); struct audit { const fs::path & directory; + const fs::path & core; int runtime_count = 0; int base_count = 0; bool ok = true; - } state{canonical}; + } state{canonical, core_directory}; dl_iterate_phdr([](dl_phdr_info * object, size_t, void * opaque) -> int { auto & state = *static_cast(opaque); const fs::path path(object->dlpi_name); const auto name = path.filename().string(); + std::error_code error; if (name.rfind("libggml-base.so", 0) == 0) { ++state.base_count; + state.ok &= fs::canonical(path.parent_path(), error) == state.core; } if (name == "libopenvino.so.2641") { ++state.runtime_count; } if (name.rfind("libopenvino", 0) == 0) { - std::error_code error; state.ok &= fs::canonical(path.parent_path(), error) == state.directory; } return 0; @@ -315,7 +318,7 @@ int main(int argc, char ** argv) { CHECK(expect(open(), result, LLAMA_DART_OPENVINO_OK, "")); CHECK(device && ggml_backend_dev_type(device) == GGML_BACKEND_DEVICE_TYPE_GPU); CHECK(openvino_registry_clean(count)); - CHECK(openvino_in_sidecar(directory)); + CHECK(openvino_in_sidecar(directory, core)); CHECK(!marker_exists()); if (scenario == "settings-accepted") { diff --git a/tools/openvino_sdk.py b/tools/openvino_sdk.py index 4cf4450b..b8556b14 100644 --- a/tools/openvino_sdk.py +++ b/tools/openvino_sdk.py @@ -10,10 +10,11 @@ import urllib.request from pathlib import Path, PurePosixPath -VERSION = "2026.4.1.22982.07f9c262b05" +RELEASE = "2026.4.1" +VERSION = f"{RELEASE}.22982.07f9c262b05" RUNTIME_BUILD = "2026.4.1-22982-e213a147257-releases/2026/4" SDK_DIRECTORY = f"openvino_toolkit_ubuntu24_{VERSION}_x86_64" -URL = f"https://storage.openvinotoolkit.org/repositories/openvino/packages/2026.4/linux/{SDK_DIRECTORY}.tgz" +URL = f"https://storage.openvinotoolkit.org/repositories/openvino/packages/{RELEASE}/linux/{SDK_DIRECTORY}.tgz" SIZE = 121_681_483 SHA256 = "772ce52d9b0aa375c77d391fccea71450d889c98b9af197bb8f05167a9dabd87" From 7f82b6d3f83fe6c6ef4a76122927c4636b6a608c Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Tue, 1 Dec 2026 18:36:43 -0500 Subject: [PATCH 3/5] Stage OpenVINO only from the current build output --- .github/actions/openvino-sidecar-build/action.yml | 2 +- docs/openvino_sidecar.md | 2 +- tools/build.py | 9 ++++++--- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/.github/actions/openvino-sidecar-build/action.yml b/.github/actions/openvino-sidecar-build/action.yml index c3b518be..2154d57f 100644 --- a/.github/actions/openvino-sidecar-build/action.yml +++ b/.github/actions/openvino-sidecar-build/action.yml @@ -33,7 +33,7 @@ runs: archive="openvino-payload/llamadart-native-linux-x64-openvino-$NATIVE_TAG.tar.gz" directory=build/linux-x64-openvino/openvino-payload python3 tools/package_openvino_sidecar.py \ - --build-dir bin/linux/x64/openvino --sdk "$SDK" --directory "$directory" --output "$archive" + --build-dir bin/linux/x64-openvino --sdk "$SDK" --directory "$directory" --output "$archive" python3 tools/validate_openvino_sidecar.py "$directory" --sdk "$SDK" stat --printf='%n %s bytes\n' "$directory"/libllamadart-openvino.so "$archive" readelf -d "$directory/libllamadart-openvino.so" diff --git a/docs/openvino_sidecar.md b/docs/openvino_sidecar.md index 0e526e73..1e6f292c 100644 --- a/docs/openvino_sidecar.md +++ b/docs/openvino_sidecar.md @@ -92,7 +92,7 @@ headers compatible with the vendored OpenCL C headers. sdk="$(python3 tools/openvino_sdk.py --output build/openvino-sdk --with-opencl-headers)" python3 tools/build.py linux --arch x64 --backend openvino --openvino-sdk "$sdk" python3 tools/package_openvino_sidecar.py \ - --build-dir bin/linux/x64/openvino --sdk "$sdk" \ + --build-dir bin/linux/x64-openvino --sdk "$sdk" \ --directory build/linux-x64-openvino/openvino-payload --output build/openvino.tar.gz python3 tools/validate_openvino_sidecar.py build/linux-x64-openvino/openvino-payload --sdk "$sdk" ``` diff --git a/tools/build.py b/tools/build.py index 3e92f11a..e5efefab 100755 --- a/tools/build.py +++ b/tools/build.py @@ -967,7 +967,9 @@ def build_linux_openvino(args: argparse.Namespace, preset: str, cache_vars: dict f"-DOPENCL_ICD_LOADER_HEADERS_DIR={OPENCL_HEADERS_DIR}", ]) run(["cmake", "--build", str(loader), *jobs]) - opencl = find_file_with_suffix(loader, "libOpenCL.so") + opencl = loader / "libOpenCL.so" + if not opencl.is_file(): + fail("OpenCL ICD Loader build did not produce libOpenCL.so") run([ "cmake", "--preset", preset, "-B", str(build_dir), *cmake_cache_args(cache_vars), f"-DOpenVINO_DIR={openvino_cmake}", f"-DOpenCL_INCLUDE_DIR={OPENCL_HEADERS_DIR}", @@ -975,8 +977,9 @@ def build_linux_openvino(args: argparse.Namespace, preset: str, cache_vars: dict f"-DLLAMADART_OPENVINO_RUNTIME_BUILD={openvino_sdk.RUNTIME_BUILD}", ]) run(["cmake", "--build", str(build_dir), "--target", "ggml-openvino", *jobs]) - output = BIN_DIR / "linux/x64/openvino" - copy_output(find_file_with_suffix(build_dir, "libllamadart-openvino.so"), output / "libllamadart-openvino.so") + output = BIN_DIR / "linux/x64-openvino" + module = build_dir / "bin/libllamadart-openvino.so" + copy_output(module, output / module.name) copy_output(opencl.resolve(), output / "libOpenCL.so.1") From fee2fdc06438f36dd052b199f09f9680f50033b9 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Tue, 1 Dec 2026 18:45:59 -0500 Subject: [PATCH 4/5] Keep the OpenVINO plugin configuration private --- src/llama_dart_openvino.cpp | 16 +++++++++------- src/llama_dart_openvino_internal.h | 12 ++++++++++++ src/llama_dart_openvino_plugins.h | 2 +- tests/test_validate_openvino_sidecar.py | 10 ++++++++-- tools/validate_openvino_sidecar.py | 13 ++++++++++--- 5 files changed, 40 insertions(+), 13 deletions(-) diff --git a/src/llama_dart_openvino.cpp b/src/llama_dart_openvino.cpp index 1c86b351..2ed56b0c 100644 --- a/src/llama_dart_openvino.cpp +++ b/src/llama_dart_openvino.cpp @@ -356,15 +356,17 @@ int32_t run(const llama_dart_openvino_request & request, llama_dart_openvino_inf ~module_ref() { dlclose(handle); } } reference{module}; - const auto abi = symbol(module, "llama_dart_openvino_shim_abi"); - const auto identity = symbol(module, "llama_dart_openvino_shim_identity"); - const auto get_layout = symbol(module, "llama_dart_openvino_shim_layout"); - const auto enumerate = symbol( + const auto abi = symbol(module, "llama_dart_openvino_shim_abi"); + const auto identity = symbol(module, "llama_dart_openvino_shim_identity"); + const auto get_layout = symbol(module, "llama_dart_openvino_shim_layout"); + const auto enumerate = symbol( module, "llama_dart_openvino_shim_enumerate"); - const auto selected = symbol(module, "llama_dart_openvino_shim_selected"); + const auto selected = symbol(module, "llama_dart_openvino_shim_selected"); const auto init = symbol(module, "ggml_backend_init"); - const auto runtime_anchor = symbol(module, "llama_dart_openvino_shim_runtime_anchor"); - const auto ggml_anchor = symbol(module, "llama_dart_openvino_shim_ggml_anchor"); + const auto runtime_anchor = symbol( + module, "llama_dart_openvino_shim_runtime_anchor"); + const auto ggml_anchor = symbol( + module, "llama_dart_openvino_shim_ggml_anchor"); if (!abi || !identity || !get_layout || !enumerate || !selected || !init || !runtime_anchor || !ggml_anchor || abi() != shim_abi) { return result(info, LLAMA_DART_OPENVINO_VERSION_MISMATCH, "shim ABI"); diff --git a/src/llama_dart_openvino_internal.h b/src/llama_dart_openvino_internal.h index 91127b0a..999a1fb8 100644 --- a/src/llama_dart_openvino_internal.h +++ b/src/llama_dart_openvino_internal.h @@ -28,3 +28,15 @@ void copy_text(char (&output)[N], const char * value) noexcept { } } // namespace llamadart_openvino + +struct llama_dart_openvino_info; + +extern "C" { +uint32_t llama_dart_openvino_shim_abi() noexcept; +const char * llama_dart_openvino_shim_identity() noexcept; +llamadart_openvino::layout llama_dart_openvino_shim_layout() noexcept; +const void * llama_dart_openvino_shim_runtime_anchor() noexcept; +const void * llama_dart_openvino_shim_ggml_anchor() noexcept; +int32_t llama_dart_openvino_shim_enumerate(const char * device, llama_dart_openvino_info * info) noexcept; +const char * llama_dart_openvino_shim_selected() noexcept; +} diff --git a/src/llama_dart_openvino_plugins.h b/src/llama_dart_openvino_plugins.h index 6ffbe999..a3d631d1 100644 --- a/src/llama_dart_openvino_plugins.h +++ b/src/llama_dart_openvino_plugins.h @@ -1,6 +1,6 @@ #pragma once -inline constexpr char llama_dart_openvino_plugins_xml[] = R"xml( +constexpr char llama_dart_openvino_plugins_xml[] = R"xml( diff --git a/tests/test_validate_openvino_sidecar.py b/tests/test_validate_openvino_sidecar.py index 2709979c..270f3925 100644 --- a/tests/test_validate_openvino_sidecar.py +++ b/tests/test_validate_openvino_sidecar.py @@ -6,7 +6,7 @@ from test_package_openvino_sidecar import OpenVINOPackageTest from validate_openvino_sidecar import ( - MODULE, RUNTIME, RUNTIME_NEEDED, validate, validate_pair, + MODULE, OWNER_EXPORTS, RUNTIME, RUNTIME_NEEDED, validate, validate_pair, ) from test_mutate_embedded_identity import IDENTITY @@ -78,7 +78,7 @@ def test_paired_core_rejects_same_identity_and_mismatched_fields(self): needed = self.dynamic["NEEDED"] with patch("validate_openvino_sidecar.dynamic", return_value={"SONAME": ["libggml-base.so.1"]}), \ patch("validate_openvino_sidecar.symbols", side_effect=[ - ({"ggml_time_us"}, set()), (set(), {"ggml_time_us"}), + (set(), OWNER_EXPORTS), ({"ggml_time_us"}, set()), (set(), {"ggml_time_us"}), ]): validate_pair(self.payload, core, needed) library.write_bytes(IDENTITY) @@ -91,3 +91,9 @@ def test_paired_core_rejects_same_identity_and_mismatched_fields(self): with patch("validate_openvino_sidecar.dynamic", return_value={"SONAME": ["libggml-base.so.1"]}), \ self.assertRaisesRegex(ValueError, "ggml-base dependency"): validate_pair(self.payload, core, []) + + with patch("validate_openvino_sidecar.dynamic", return_value={"SONAME": ["libggml-base.so.1"]}), \ + patch("validate_openvino_sidecar.symbols", return_value=( + set(), OWNER_EXPORTS | {"llama_dart_openvino_plugins_xml"})), \ + self.assertRaisesRegex(ValueError, "llama_dart_openvino_plugins_xml"): + validate_pair(self.payload, core, needed) diff --git a/tools/validate_openvino_sidecar.py b/tools/validate_openvino_sidecar.py index ed4e148d..4222e339 100644 --- a/tools/validate_openvino_sidecar.py +++ b/tools/validate_openvino_sidecar.py @@ -19,6 +19,9 @@ ) PAIRED_FIELDS = ("owner", "llama.cpp", "ggml", "patches", "target") +OWNER_EXPORTS = { + "llama_dart_openvino_api_version", "llama_dart_openvino_probe", "llama_dart_openvino_open", +} RUNTIME_NEEDED = {RUNTIME, "libtbb.so.12", "libOpenCL.so.1"} PLUGIN_NAME = re.compile(rb"libopenvino_[a-z0-9_]+_plugin\.so") EXPECTED_DEVICES = {"NPU", "CPU", "GPU", "AUTO", "MULTI", "HETERO", "BATCH"} @@ -40,14 +43,14 @@ def dynamic(path: Path) -> dict[str, list[str]]: return values -def symbols(path: Path) -> tuple[set[str], set[str]]: +def symbols(path: Path, prefixes: tuple[str, ...] = ("ggml_", "gguf_")) -> tuple[set[str], set[str]]: imports, exports = set(), set() for line in elf(path, "--dyn-syms").splitlines(): fields = line.split() if len(fields) < 8 or not fields[0].endswith(":"): continue name = fields[7].split("@", 1)[0] - if name.startswith(("ggml_", "gguf_")): + if name.startswith(prefixes): (imports if fields[6] == "UND" else exports).add(name) return imports, exports @@ -68,7 +71,8 @@ def licenses_match(directory: Path, sdk: Path) -> None: def validate_pair(directory: Path, core: Path, needed: list[str]) -> None: - _, _, core_id = read_identity((core / "libllamadart.so").read_bytes()) + library = core / "libllamadart.so" + _, _, core_id = read_identity(library.read_bytes()) _, _, module_id = read_identity((directory / MODULE).read_bytes()) require(core_id != module_id and "openvino" not in core_id["backends"].split(","), "Expected the independently built release core") @@ -79,6 +83,9 @@ def validate_pair(directory: Path, core: Path, needed: list[str]) -> None: soname = dynamic(base).get("SONAME", []) ggml_base = [name for name in needed if name.startswith("libggml-base.so")] require(len(soname) == 1 and ggml_base == soname, "Module ggml-base dependency differs from the core SONAME") + _, owner_exports = symbols(library, ("llama_dart_openvino_",)) + require(owner_exports == OWNER_EXPORTS, + f"Unexpected OpenVINO owner exports: {sorted(owner_exports ^ OWNER_EXPORTS)}") imported, exported = symbols(directory / MODULE) _, core_exports = symbols(base) require(bool(imported) and imported <= core_exports, f"Missing ggml-base exports: {sorted(imported - core_exports)}") From b23270717074655d5881da7d90f273be77184d14 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Tue, 1 Dec 2026 19:40:25 -0500 Subject: [PATCH 5/5] Record OpenVINO sidecar approvals and close audit test gaps Document the approved oneTBB redistribution and the release dependency on the Intel SDK host and pair job. Add a same-length plugins.xml refusal case, check every layout field in the comparator test, and note the non-Intel accel diagnosis in the community checklist. --- docs/openvino_sidecar.md | 21 ++++++++++++++++++++- tests/openvino_identity_test.cpp | 14 +++++++++++--- tests/run_openvino_contract.py | 8 +++++++- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/docs/openvino_sidecar.md b/docs/openvino_sidecar.md index 1e6f292c..ab79bbad 100644 --- a/docs/openvino_sidecar.md +++ b/docs/openvino_sidecar.md @@ -14,6 +14,20 @@ notices on to users. The Intel libraries follow the Intel OpenVINO Distribution License. oneTBB and the Khronos OpenCL ICD Loader follow Apache-2.0. The bundle targets the release Linux x64 glibc 2.38 floor. +## Redistribution and release dependencies + +The maintainer approved shipping the Intel SDK's `libtbb.so.12` (oneTBB) under +Apache-2.0 with its notices, copied verbatim with the SDK licensing tree. +This rests on oneTBB's open-source license, not the Intel EULA or `redist.txt`, +which list only the `runtime/lib/intel64` files. A matching oneTBB source build +is the fallback if that decision changes. + +The maintainer also accepted that native releases depend on the Intel SDK +download host (`storage.openvinotoolkit.org`) and on the OpenVINO pair job: +`package-and-release` needs `openvino-sidecar-pair`. A host outage, an +upstream `ggml-openvino` change that breaks the shim build, or a new upstream +`GGML_ABORT` site blocks every native release until it is handled. + ## Owner API `llama_dart_openvino_api_version()` reports ABI 1. Set both `struct_size` @@ -42,7 +56,7 @@ then checks the layout of the structs passed across the boundary. | `FOREIGN_RUNTIME` | The selected OpenVINO, oneTBB, OpenCL loader, ggml binding or plugin configuration conflicts with the sidecar. | | `INVALID_SETTING` | A nonempty `GGML_OPENVINO_*` variable is outside the policy below. | | `UNSUPPORTED_DEVICE` | The request is for a device other than NPU or CPU. | -| `NO_DEVICE` | The device did not enumerate and the NPU diagnosis found no matching hardware. | +| `NO_DEVICE` | The device did not enumerate and the NPU diagnosis found no `/dev/accel/accel*` node or Intel NPU PCI device. | | `MISSING_DRIVER` | NPU enumeration failed and the evidence points to the kernel driver, Level Zero loader, or user-mode driver or firmware. | | `DEVICE_ACCESS_DENIED` | The process lacks read/write access to its NPU device nodes. | | `DEVICE_CONFLICT` | An earlier open selected a different device in this process. | @@ -113,6 +127,11 @@ same llama.cpp and Intel runtime versions as the control. - Check enumeration with the kernel driver absent, with `/dev/accel` access denied, with the Level Zero loader absent, and with a working configuration. +- On a host with another `/dev/accel/accel*` device (for example AMD XDNA) + and no Intel NPU, record the result of an NPU request. The diagnosis treats + any `accel*` node as the NPU, so it can return `MISSING_DRIVER` or + `DEVICE_ACCESS_DENIED` instead of `NO_DEVICE`. The result stays typed and + abort-free. - On a working device, verify actual NPU placement, decoded output against the control, cold and warm start with the cache directory, and a clean exit with a live context after joining the worker. diff --git a/tests/openvino_identity_test.cpp b/tests/openvino_identity_test.cpp index 870ce021..f58ffbda 100644 --- a/tests/openvino_identity_test.cpp +++ b/tests/openvino_identity_test.cpp @@ -3,6 +3,7 @@ #include #include #include +#include using namespace llamadart_openvino; @@ -45,9 +46,16 @@ int main() { const layout core{336, 128, 120, 112, 64, 64}; check(layout_matches(core, core), "same layout"); - check(!layout_matches(core, {336, 128, 120, 112, 64, 128}), "max name"); - check(!layout_matches(core, {328, 128, 120, 112, 64, 64}), "tensor"); - check(!layout_matches(core, {336, 128, 120, 112, 56, 64}), "buffer type"); + const std::pair members[] = { + {"tensor", &layout::tensor}, {"backend", &layout::backend}, + {"device", &layout::device}, {"buffer", &layout::buffer}, + {"buffer type", &layout::buffer_type}, {"max name", &layout::max_name}}; + for (const auto & member : members) { + auto changed = core; + changed.*member.second += 8; + check(!layout_matches(core, changed), member.first); + check(!layout_matches(changed, core), member.first); + } } catch (const std::exception & error) { std::cerr << error.what() << '\n'; return 1; diff --git a/tests/run_openvino_contract.py b/tests/run_openvino_contract.py index 5bcb00c8..727ba139 100644 --- a/tests/run_openvino_contract.py +++ b/tests/run_openvino_contract.py @@ -50,7 +50,8 @@ "planted-plugin", "foreign-tbb", "foreign-opencl", "foreign-runtime-global-symbol", "foreign-runtime-after-load", "foreign-binding-after-load", "foreign-runtime-unchecked", "foreign-ggml-instance", "symlinked-sidecar", "plugin-list-mismatch-missing-device", - "plugin-list-mismatch-dotdot", "plugin-list-mismatch-absolute", "plugin-directory", + "plugin-list-mismatch-dotdot", "plugin-list-mismatch-absolute", "plugin-list-mismatch-same-length", + "plugin-directory", "sidecar-symlinked-file", "sidecar-symlinked-cpu-plugin", "clean-dlopen", "process-exit", ] @@ -195,6 +196,11 @@ def call(scenario: str, *parameters: object) -> list: gpu = '\n' if name.endswith("missing-device"): text = text.replace(gpu, "") + elif name.endswith("same-length"): + original = text + text = text.replace('location="libopenvino_intel_gpu_plugin.so"', 'location="../openvino_intel_gpu_plugin.so"') + if text == original or len(text) != len(original): + raise SystemExit("same-length fixture must change the bytes but not the length") elif name.endswith("dotdot"): text = text.replace('location="libopenvino_intel_gpu_plugin.so"', 'location="../canary/libopenvino_intel_gpu_plugin.so"') else: