From 1eb8d501d1f20e1a0311c1d1727c42d393b5a6a9 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Tue, 1 Dec 2026 17:09:47 -0500 Subject: [PATCH 1/2] Build an opt-in Android arm64 Hexagon candidate --- .github/CODEOWNERS | 4 + .../workflows/android_hexagon_candidate.yml | 103 +++++++ .github/workflows/native_release.yml | 20 ++ README.md | 4 + docs/android_hexagon.md | 60 ++++ docs/platform_backend_strategy.md | 3 + scripts/publish_prepared_release.py | 7 + tests/test_android_hexagon.py | 134 +++++++++ tests/test_publish_prepared.py | 8 + tools/android_hexagon.py | 259 ++++++++++++++++++ tools/build.py | 33 ++- tools/build_android_hexagon_candidate.sh | 54 ++++ tools/validate_android_artifacts.py | 41 ++- 13 files changed, 717 insertions(+), 13 deletions(-) create mode 100644 .github/workflows/android_hexagon_candidate.yml create mode 100644 docs/android_hexagon.md create mode 100644 tests/test_android_hexagon.py create mode 100644 tools/android_hexagon.py create mode 100755 tools/build_android_hexagon_candidate.sh diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 6c31d2f3..0304e37e 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -11,3 +11,7 @@ /.github/workflows/windows_consumer_qualification.yml @leehack /tools/qualification/windows_consumer/ @leehack /tests/test_windows_consumer_qualification.py @leehack +/.github/workflows/android_hexagon_candidate.yml @leehack +/tools/android_hexagon.py @leehack +/tools/build_android_hexagon_candidate.sh @leehack +/tools/validate_android_artifacts.py @leehack diff --git a/.github/workflows/android_hexagon_candidate.yml b/.github/workflows/android_hexagon_candidate.yml new file mode 100644 index 00000000..7782102c --- /dev/null +++ b/.github/workflows/android_hexagon_candidate.yml @@ -0,0 +1,103 @@ +name: Android Hexagon Candidate + +on: + pull_request: + paths: + - '.github/workflows/android_hexagon_candidate.yml' + - 'tests/test_android_hexagon.py' + - 'tools/android_hexagon.py' + - 'tools/build_android_hexagon_candidate.sh' + workflow_call: + inputs: + native_commit: + required: true + type: string + llama_cpp_ref: + required: true + type: string + llama_cpp_commit: + required: true + type: string + native_tag: + required: true + type: string + +permissions: + contents: read + +jobs: + candidate: + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-24.04 + timeout-minutes: 40 + steps: + - uses: actions/checkout@v7 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + submodules: recursive + persist-credentials: false + - name: Checkout llama.cpp ref + if: inputs.llama_cpp_commit != '' + uses: ./.github/actions/checkout-llama-ref + with: + tag: ${{ inputs.llama_cpp_ref }} + expected_commit: ${{ inputs.llama_cpp_commit }} + github_token: ${{ github.token }} + - name: Checkout exact release source + if: inputs.native_commit != '' + uses: ./.github/actions/checkout-native-source + with: + native_commit: ${{ inputs.native_commit }} + llama_cpp_commit: ${{ inputs.llama_cpp_commit }} + - name: Verify the exact source pair + id: source + env: + NATIVE_COMMIT: ${{ inputs.native_commit || github.event.pull_request.head.sha }} + LLAMA_CPP_COMMIT: ${{ inputs.llama_cpp_commit }} + NATIVE_TAG: ${{ inputs.native_tag }} + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$NATIVE_COMMIT" + llama_commit="$(git -C third_party/llama.cpp rev-parse HEAD)" + test "$(git rev-parse HEAD:third_party/llama.cpp)" = "$llama_commit" + test "$llama_commit" = "${LLAMA_CPP_COMMIT:-$llama_commit}" + if [ -z "$NATIVE_TAG" ]; then + git -C third_party/llama.cpp fetch --tags origin + NATIVE_TAG="$(git -C third_party/llama.cpp describe --tags --exact-match --match 'v*' HEAD)" + fi + echo "tag=$NATIVE_TAG" >> "$GITHUB_OUTPUT" + - name: Test Hexagon packaging and artifact validation + run: python3 -m unittest discover -s tests -p 'test_android_hexagon.py' + - id: android-sdk + uses: android-actions/setup-android@v4 + with: + packages: platform-tools ndk;28.2.13676358 + - name: Capture failed Android NDK installation + if: ${{ always() && steps.android-sdk.outcome == 'failure' }} + timeout-minutes: 2 + run: | + python3 tools/android_ndk_install_diagnostics.py \ + --sdk-root "${ANDROID_SDK_ROOT:-${ANDROID_HOME:-/usr/local/lib/android/sdk}}" \ + --setup-outcome failure --output "$RUNNER_TEMP/android-ndk-install-diagnostics.json" + - name: Upload Android NDK installation diagnostics + if: ${{ always() && steps.android-sdk.outcome == 'failure' }} + uses: actions/upload-artifact@v7 + with: + name: android-ndk-setup-hexagon + path: ${{ runner.temp }}/android-ndk-install-diagnostics.json + if-no-files-found: error + retention-days: 7 + - name: Build and verify the release-gated archive + env: + NATIVE_TAG: ${{ steps.source.outputs.tag }} + run: | + set -euo pipefail + export ANDROID_NDK_HOME="${ANDROID_SDK_ROOT:-${ANDROID_HOME:-/usr/local/lib/android/sdk}}/ndk/28.2.13676358" + tools/build_android_hexagon_candidate.sh "$NATIVE_TAG" + - name: Upload qualification archive + uses: actions/upload-artifact@v7 + with: + name: android-arm64-hexagon-candidate + path: artifacts/hexagon-candidate/ + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/native_release.yml b/.github/workflows/native_release.yml index d73b6d7e..a34dcf1d 100644 --- a/.github/workflows/native_release.yml +++ b/.github/workflows/native_release.yml @@ -23,6 +23,10 @@ on: correlation_id: description: 'Stable caller correlation identifier (1-128 safe characters)' required: true + prepare_android_hexagon: + description: 'Build experimental Android arm64 Hexagon for qualification only (#260)' + default: false + type: boolean publish_release: description: 'Publish GitHub release' required: true @@ -76,9 +80,15 @@ jobs: INPUT_SMOKE_POLICY: ${{ github.event.inputs.smoke_policy }} INPUT_CORRELATION_ID: ${{ github.event.inputs.correlation_id }} INPUT_PUBLISH_RELEASE: ${{ github.event.inputs.publish_release }} + INPUT_PREPARE_ANDROID_HEXAGON: ${{ inputs.prepare_android_hexagon }} run: | set -euo pipefail + if [ "$INPUT_PREPARE_ANDROID_HEXAGON" = "true" ] && [ "$INPUT_PUBLISH_RELEASE" != "false" ]; then + echo "Hexagon SDK agreement review is pending (#260). Use publish_release=false." >&2 + exit 1 + fi + TAG="$INPUT_LLAMA_CPP_TAG" EXPECTED_COMMIT="$INPUT_LLAMA_CPP_COMMIT" RELEASE_TAG="$INPUT_NATIVE_RELEASE_TAG" @@ -168,6 +178,16 @@ jobs: if-no-files-found: error retention-days: 7 + build-android-hexagon: + needs: resolve-tag + if: inputs.prepare_android_hexagon + uses: ./.github/workflows/android_hexagon_candidate.yml + with: + native_commit: ${{ needs.resolve-tag.outputs.native_commit }} + llama_cpp_ref: ${{ needs.resolve-tag.outputs.llama_cpp_ref }} + llama_cpp_commit: ${{ needs.resolve-tag.outputs.llama_cpp_commit }} + native_tag: ${{ needs.resolve-tag.outputs.native_release_tag }} + build-android: needs: resolve-tag # Pinned: the Vulkan lanes' glslc comes from this image's apt archive, and a diff --git a/README.md b/README.md index a674104c..d3fea016 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,10 @@ the following per-target bundles: - Windows x64: Vulkan + CUDA + BLAS + CPU - Windows arm64: Vulkan + BLAS + Kleidi + CPU +An experimental [Android arm64 Hexagon candidate](docs/android_hexagon.md) +provides a separate CPU + HTP bundle for qualification. Publication is gated +on review of the Qualcomm SDK agreement. + Non-Apple targets use `GGML_BACKEND_DL=ON`, so backend libs are optional at package/runtime level. ## Runtime Packaging Model diff --git a/docs/android_hexagon.md b/docs/android_hexagon.md new file mode 100644 index 00000000..d14d9437 --- /dev/null +++ b/docs/android_hexagon.md @@ -0,0 +1,60 @@ +# Experimental Android arm64 Hexagon candidate + +Publication is gated on maintainer confirmation of the Qualcomm Hexagon SDK +Community Edition 6.7.0.0 agreement for hosted CI and distribution of the +generated FastRPC stub and DSP skeletons. The maintainer approved the +qualification build in [#260](https://github.com/leehack/llamadart-native/issues/260#issuecomment-7326932721). +The [Qualcomm catalog](https://softwarecenter.qualcomm.com/catalog/item/Hexagon_SDK?version=6.7.0.0) +links the vendor distribution. The [public SDK repack](https://github.com/snapdragon-toolchain/hexagon-sdk/releases/tag/v6.7.0.0) +contains third-party notices that refer Qualcomm terms to a separate agreement. + +The pinned llama.cpp source uses Snapdragon toolchain images in the public +[Snapdragon build](https://github.com/ggml-org/llama.cpp/blob/171527522610996f5f0acf12334e185156ca8f44/.github/workflows/build-and-test-snapdragon.yml) +and [Android build](https://github.com/ggml-org/llama.cpp/blob/171527522610996f5f0acf12334e185156ca8f44/.github/workflows/build-android.yml) +workflows and describes the toolchain in its +[Snapdragon guide](https://github.com/ggml-org/llama.cpp/blob/171527522610996f5f0acf12334e185156ca8f44/docs/backend/snapdragon/README.md). +Upstream describes Hexagon as experimental. + +## Build and layout + +Select Linux Android NDK r28c (`28.2.13676358`) with `ANDROID_NDK_HOME` +and run `tools/build_android_hexagon_candidate.sh ` on a Linux +Docker host with all submodules initialized. The helper selects the pinned +linux/amd64 Snapdragon toolchain image and passes r28c to CMake for Android +arm64/API 28. The image supplies Hexagon SDK CE 6.7.0.0 and tools 21.0.04. + +The helper invokes `tools/build.py android --abi arm64-v8a --backend hexagon`. +Only the primary configure enables HTP. The secondary CPU variants use the +existing isolated configurations. The opt-in build outputs an independent +CPU + HTP bundle at `bin/android/arm64-hexagon`. Select the normal Android +build for Vulkan and OpenCL. + +The arm64 dynamic module `libggml-hexagon.so` loads FastRPC from the device at +runtime. The tarball includes five DSP ELFs, named `libggml-htp-v{73,75,79,81,85}.so` +under `assets/hexagon/`. `hexagon-assets.json` binds each file to its SHA-256 and +records the toolchain identities. `HEXAGON-NOTICES.txt` copies the SDK notices +and Python component licenses byte for byte with source paths and SHA-256 +values. The validator checks the archive and directory layout, shared-library +machines, supported Android API and NDK, 16 KiB host segment alignment, CPU ISA +and C++ runtime sharing, dynamic exports, and the host and DSP dependency sets. + +GitHub Actions stores a tag-coupled candidate and its SHA-256 separately from +the native release assets. The release workflow accepts `prepare_android_hexagon=true` +for qualification with `publish_release=false`. The prepared-release importer +refuses a source run that built a Hexagon candidate. + +## App qualification + +For a target SDK 31+ app, declare `libcdsprpc.so` as an optional +`` under ``. Package the arm64 host module +as a native library. Copy the matching DSP asset to an app-private directory +after verifying its manifest hash. Set `ADSP_LIBRARY_PATH` before loading +FastRPC or registering the HTP backend. Use a fresh process if initialization +must be repeated with different assets. + +Qualification needs signed stock-device APK evidence for both SM8650 (v75) +and SM8750 (v79), including CPU and HTP runs with the same pinned model. Grade +actual FastRPC session and DSP cycles together with completed decode. Check +that missing and stale assets refuse HTP. The presence of a skeleton in the +bundle does not qualify its DSP version. The Dart hook and runtime contract +are tracked in [llamadart#2553](https://github.com/leehack/llamadart/issues/2553). diff --git a/docs/platform_backend_strategy.md b/docs/platform_backend_strategy.md index 56cee26e..5e2aa780 100644 --- a/docs/platform_backend_strategy.md +++ b/docs/platform_backend_strategy.md @@ -13,6 +13,9 @@ | Windows x64 | Vulkan + CUDA + BLAS + CPU | | Windows arm64 | Vulkan + BLAS + Kleidi + CPU | +The experimental [Android arm64 Hexagon candidate](android_hexagon.md) has a +separate opt-in CPU + HTP configuration and qualification archive. + ## Build Model - Release CI builds non-Apple backend lanes separately and merges them into diff --git a/scripts/publish_prepared_release.py b/scripts/publish_prepared_release.py index 2afe0cd8..b5b31a97 100644 --- a/scripts/publish_prepared_release.py +++ b/scripts/publish_prepared_release.py @@ -148,6 +148,13 @@ def validate_run(expected: Expected, run: dict, jobs: list[dict]) -> None: names = [job.get('name') for job in jobs] require(len(names) == len(set(names)), 'ambiguous source job names') for job in jobs: + name = job.get('name') + if (name in ('build-android-hexagon', 'build-android-hexagon / candidate') + and job.get('conclusion') == 'skipped'): + require(job.get('status') == 'completed', 'Hexagon job has not settled') + continue + require(not isinstance(name, str) or not name.startswith('build-android-hexagon'), + 'Hexagon SDK agreement review is pending (#260)') require(job.get('status') == 'completed' and job.get('conclusion') == ('skipped' if job.get('name') in SKIPPED_JOBS else 'success'), 'source job is failed, incomplete or unexpectedly skipped') diff --git a/tests/test_android_hexagon.py b/tests/test_android_hexagon.py new file mode 100644 index 00000000..d80626c4 --- /dev/null +++ b/tests/test_android_hexagon.py @@ -0,0 +1,134 @@ +import io +import json +import struct +import sys +import tarfile +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) + +import android_hexagon as hexagon +import build + + +def elf(elf_class, machine, flags=0): + data = bytearray(64) + data[:6] = b"\x7fELF" + bytes((elf_class, 1)) + struct.pack_into(" dict[str, str]: + properties = ndk / "source.properties" + if not properties.is_file(): + raise ValueError(f"Missing Android NDK version file: {properties}") + properties = properties.read_text().splitlines() + if f"Pkg.Revision = {NDK_VERSION}" not in properties: + raise ValueError(f"Hexagon requires Android NDK r28c ({NDK_VERSION})") + if not env.get("HEXAGON_SDK_ROOT") or not env.get("HEXAGON_TOOLS_ROOT"): + raise ValueError("Hexagon requires HEXAGON_SDK_ROOT and HEXAGON_TOOLS_ROOT from the pinned image") + sdk = Path(env["HEXAGON_SDK_ROOT"]) + tools = Path(env["HEXAGON_TOOLS_ROOT"]) + if sdk.name != SDK_VERSION or tools.resolve() != (sdk / TOOLS_DIR).resolve(): + raise ValueError(f"Hexagon requires SDK {SDK_VERSION} and tools {TOOLS_VERSION}") + if not (sdk / "ipc/fastrpc/qaic/bin/qaic").is_file() or not (tools / "Tools/bin/hexagon-clang").is_file(): + raise ValueError("Hexagon QAIC or Hexagon clang is missing from the pinned toolchain") + return { + "GGML_HEXAGON": "ON", + "CMAKE_MODULE_LINKER_FLAGS": "-s", + "HEXAGON_SDK_ROOT": str(sdk), + "HEXAGON_TOOLS_ROOT": str(tools), + "PREBUILT_LIB_DIR": "android_aarch64", + } + + +def digest(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def notice_marker(path: Path, sha256: str) -> bytes: + return f"\n--- {path.as_posix()} (SHA-256 {sha256}) ---\n".encode() + + +def notices_bytes(sdk: Path) -> bytes: + output = bytearray(NOTICE_HEADER) + for path, sha256 in NOTICE_FILES.items(): + data = (sdk / path).read_bytes() + if digest(data) != sha256: + raise ValueError(f"Hexagon SDK notice differs from the pinned image: {path}") + output.extend(notice_marker(path, sha256)) + output.extend(data) + return bytes(output) + + +def validate_notices(data: bytes) -> None: + parts = data.split(b"\n--- ") + if parts[0] != NOTICE_HEADER or len(parts) != len(NOTICE_FILES) + 1: + raise ValueError("Hexagon notice provenance or inventory differs") + for part, (path, sha256) in zip(parts[1:], NOTICE_FILES.items()): + marker = notice_marker(path, sha256)[5:] + if not part.startswith(marker) or digest(part[len(marker):]) != sha256: + raise ValueError(f"Hexagon SDK notice bytes differ: {path}") + + +def asset_manifest(out_dir: Path) -> dict: + files = sorted( + [path.relative_to(out_dir) for path in out_dir.glob("*.so")] + + [NOTICES, *(ASSET_DIR / name for name in SKELETONS)] + ) + return { + "owner_build_identity": sorted(validate_build_identity.identities(out_dir / "libllamadart.so")), + "toolchain_image": TOOLCHAIN_IMAGE, + "android_ndk": NDK_VERSION, + "hexagon_sdk": SDK_VERSION, + "files": {path.as_posix(): digest((out_dir / path).read_bytes()) for path in files}, + } + + +def stage_assets(build_dir: Path, out_dir: Path, sdk: Path) -> None: + output = build_dir / "third_party/llama.cpp/ggml/src/ggml-hexagon" + if {path.name for path in output.glob("libggml-htp-*.so")} != SKELETONS.keys(): + raise ValueError(f"Unexpected Hexagon skeleton set in {output}") + assets = out_dir / ASSET_DIR + assets.mkdir(parents=True) + for name in SKELETONS: + shutil.copyfile(output / name, assets / name) + (out_dir / NOTICES).write_bytes(notices_bytes(sdk)) + (out_dir / MANIFEST).write_text(json.dumps(asset_manifest(out_dir), indent=2) + "\n") + + +def elf_header(path: Path) -> tuple[int, int, int]: + with path.open("rb") as file: + header = file.read(64) + if len(header) < 52 or header[:4] != b"\x7fELF" or header[5] != 1: + raise ValueError(f"{path.name}: expected a little-endian ELF") + elf_type, machine = struct.unpack_from(" tuple[set[str], str | None]: + output = subprocess.run([str(readelf), "-dW", str(path)], check=True, + capture_output=True, text=True).stdout + needed = set(re.findall(r"\(NEEDED\)[^\n]*\[([^\]]+)\]", output)) + soname = re.search(r"\(SONAME\)[^\n]*\[([^\]]+)\]", output) + return needed, soname[1] if soname else None + + +def check_android_note(readelf: Path, path: Path) -> None: + output = subprocess.run([str(readelf), "-x", ".note.android.ident", str(path)], + check=True, capture_output=True, text=True).stdout + words = "".join( + "".join(words_on_line) + for words_on_line in re.findall(r"^\s*0x[0-9a-fA-F]+((?: [0-9a-fA-F]{8}){1,4})", output, re.M) + ) + note = bytes.fromhex(words) + if (note[:24] != struct.pack(" set[Path]: + return {Path(name) for name in CORE_LIBRARIES | set(cpu_variants)} | { + NOTICES, MANIFEST, *(ASSET_DIR / name for name in SKELETONS), + } + + +def validate(out_dir: Path, readelf: Path, cpu_variants: tuple[str, ...], + symbols: dict[str, tuple[set[str], set[str]]], read_symbols) -> None: + expected = expected_files(cpu_variants) + actual = set() + for path in out_dir.rglob("*"): + if path.is_symlink() or not (path.is_file() or path.is_dir()): + raise ValueError(f"Unexpected link or special file in Hexagon bundle: {path.relative_to(out_dir)}") + if path.is_file(): + actual.add(path.relative_to(out_dir)) + if actual != expected: + raise ValueError( + f"Hexagon bundle contents differ: missing {sorted(expected - actual)}, " + f"unexpected {sorted(actual - expected)}" + ) + + validate_notices((out_dir / NOTICES).read_bytes()) + if json.loads((out_dir / MANIFEST).read_bytes()) != asset_manifest(out_dir): + raise ValueError("Hexagon bundle manifest identity or SHA-256 values differ") + + runtime = CORE_LIBRARIES | set(cpu_variants) + for name in sorted(runtime): + path = out_dir / name + if elf_header(path) != (2, 183, 0): + raise ValueError(f"{name}: expected Android AArch64 ELF64") + check_android_note(readelf, path) + needed, soname = dynamic_tags(readelf, path) + if soname is not None and soname != name: + raise ValueError(f"{name}: unexpected SONAME {soname}") + if missing := needed - runtime - ANDROID_LIBRARIES: + raise ValueError(f"{name}: dependencies outside the Android runtime set: {sorted(missing)}") + if name == HOST_LIBRARY and "libggml-base.so" not in needed: + raise ValueError(f"{name}: missing libggml-base.so dependency") + host = out_dir / HOST_LIBRARY + defined, imported = symbols[HOST_LIBRARY] + if "ggml_backend_init" not in defined or b"libcdsprpc.so\0" not in host.read_bytes(): + raise ValueError(f"{HOST_LIBRARY}: missing backend initializer or FastRPC soname") + if missing := {name for name in imported if name.startswith("ggml_")} - symbols["libggml-base.so"][0]: + raise ValueError(f"{HOST_LIBRARY}: unresolved ggml imports: {sorted(missing)}") + for name in cpu_variants: + if not {"ggml_backend_init", "ggml_backend_score"} <= symbols[name][0]: + raise ValueError(f"{name}: missing CPU backend initializer or score export") + + for name, flags in SKELETONS.items(): + path = out_dir / ASSET_DIR / name + if elf_header(path) != (1, 164, flags): + raise ValueError(f"{name}: expected Hexagon ELF32 with flags 0x{flags:x}") + needed, soname = dynamic_tags(readelf, path) + if soname != name or needed != DSP_LIBRARIES: + raise ValueError(f"{name}: unexpected SONAME or DSP dependencies {sorted(needed)}") + if "htp_iface_skel_handle_invoke" not in read_symbols(readelf, path)[0]: + raise ValueError(f"{name}: missing FastRPC skeleton export") + + +def unpack_archive(archive: Path, out_dir: Path, cpu_variants: tuple[str, ...]) -> None: + expected = expected_files(cpu_variants) + unpacked = set() + with tarfile.open(archive, "r:gz") as tar: + for member in tar: + path = Path(member.name) + if path not in expected or path in unpacked or not member.isfile(): + raise ValueError(f"Unexpected Hexagon archive member: {member.name}") + destination = out_dir / path + destination.parent.mkdir(parents=True, exist_ok=True) + with tar.extractfile(member) as source, destination.open("wb") as file: + shutil.copyfileobj(source, file) + unpacked.add(path) + if unpacked != expected: + raise ValueError(f"Missing Hexagon archive members: {sorted(expected - unpacked)}") + + +def pack_archive(out_dir: Path, archive: Path, cpu_variants: tuple[str, ...]) -> None: + archive.parent.mkdir(parents=True, exist_ok=True) + with tarfile.open(archive, "w:gz") as tar: + for path in sorted(expected_files(cpu_variants)): + tar.add(out_dir / path, arcname=path.as_posix(), recursive=False) diff --git a/tools/build.py b/tools/build.py index 574c53a8..298111c1 100755 --- a/tools/build.py +++ b/tools/build.py @@ -12,6 +12,7 @@ from pathlib import Path from typing import NoReturn +import android_hexagon import windows_runtime REPO_ROOT = Path(__file__).resolve().parents[1] @@ -127,7 +128,7 @@ def linux_arm64_cpu_variant_libs() -> tuple[str, ...]: WINDOWS_VCPKG_TRIPLETS = {"x64": "x64-windows", "arm64": "arm64-windows"} -ANDROID_BACKENDS = ("full", "vulkan", "opencl") +ANDROID_BACKENDS = ("full", "vulkan", "opencl", "hexagon") LINUX_BACKENDS = ("full", "cpu", "vulkan", "cuda", "hip", "blas") WINDOWS_BACKENDS = ("full", "vulkan", "cuda", "blas") @@ -304,6 +305,7 @@ def android_base_cmake_args(abi: str, ndk: Path) -> list[str]: "-DCMAKE_BUILD_TYPE=Release", "-DBUILD_SHARED_LIBS=ON", "-DGGML_BACKEND_DL=ON", + "-DGGML_HEXAGON=OFF", "-DGGML_NATIVE=OFF", "-DCMAKE_SHARED_LINKER_FLAGS=-s", "-DGGML_OPENMP=OFF", @@ -436,6 +438,11 @@ def build_android_arm64_abi(args: argparse.Namespace, env: dict[str, str]) -> No "GGML_CPU_ARM_ARCH": ANDROID_ARM64_CPU_VARIANTS[0][1], "LLAMADART_CPU_REQUIRED_FEATURES": ";".join(ANDROID_ARM64_CPU_VARIANTS[0][2]), } + if backend == "hexagon": + try: + primary_cache_vars.update(android_hexagon.cache_vars(ndk, env)) + except ValueError as error: + fail(str(error)) primary_args = android_configure_args( abi, build_dir=primary_build_dir, @@ -451,8 +458,8 @@ def build_android_arm64_abi(args: argparse.Namespace, env: dict[str, str]) -> No env=env, ) - out_dir = BIN_DIR / f"android/{ANDROID_OUT_ARCH[abi]}" - copy_runtime_libraries(built_dir, out_dir) + out_dir = BIN_DIR / "android" / ("arm64-hexagon" if backend == "hexagon" else "arm64") + copy_runtime_libraries(built_dir, out_dir, exclude_prefixes=("libggml-htp-",)) variant_libs = android_arm64_cpu_variant_libs() @@ -477,6 +484,12 @@ def build_android_arm64_abi(args: argparse.Namespace, env: dict[str, str]) -> No ) copy_output(cpu_lib, out_dir / variant_lib) + if backend == "hexagon": + try: + android_hexagon.stage_assets(built_dir, out_dir, Path(env["HEXAGON_SDK_ROOT"])) + except ValueError as error: + fail(str(error)) + def windows_backend_cache_vars(arch: str, backend: str) -> dict[str, str]: if backend == "cuda" and arch != "x64": @@ -700,10 +713,10 @@ def is_runtime_library(path: Path) -> bool: return any(name.startswith(p) for p in prefixes) -def collect_runtime_libraries(build_dir: Path) -> list[Path]: +def collect_runtime_libraries(build_dir: Path, exclude_prefixes: tuple[str, ...] = ()) -> list[Path]: selected: dict[str, Path] = {} for p in sorted(build_dir.rglob("*")): - if not is_runtime_library(p): + if p.name.startswith(exclude_prefixes) or not is_runtime_library(p): continue selected[p.name] = p @@ -725,8 +738,10 @@ def copy_output(src: Path, dst: Path) -> None: print(f"Built: {dst.relative_to(REPO_ROOT)}") -def copy_runtime_libraries(build_dir: Path, out_dir: Path) -> None: - libs = collect_runtime_libraries(build_dir) +def copy_runtime_libraries( + build_dir: Path, out_dir: Path, *, exclude_prefixes: tuple[str, ...] = () +) -> None: + libs = collect_runtime_libraries(build_dir, exclude_prefixes) libs.extend(collect_windows_runtime_dependencies(libs)) unique: dict[str, Path] = {} for lib in libs: @@ -1047,6 +1062,8 @@ def build_android_abi(abi: str, args: argparse.Namespace, env: dict[str, str]) - def build_android(args: argparse.Namespace) -> None: + if args.backend == "hexagon" and ANDROID_ABI_ALIASES.get(args.abi) != "arm64-v8a": + fail("The experimental Hexagon backend requires --abi arm64-v8a") ensure_submodule( THIRD_PARTY_DIR / "llama.cpp/CMakeLists.txt", "Missing submodule: third_party/llama.cpp. Run: git submodule update --init --recursive", @@ -1126,7 +1143,7 @@ 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)", - "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)", + "android: abi=arm64-v8a|x86_64|all backend=full|vulkan|opencl|hexagon (Hexagon is opt-in on arm64; 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)", ] for p in presets: diff --git a/tools/build_android_hexagon_candidate.sh b/tools/build_android_hexagon_candidate.sh new file mode 100755 index 00000000..af9a112f --- /dev/null +++ b/tools/build_android_hexagon_candidate.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." +ndk_version="$(python3 -c 'import sys; sys.path.insert(0, "tools"); import android_hexagon as h; print(h.NDK_VERSION)')" +image="$(python3 -c 'import sys; sys.path.insert(0, "tools"); import android_hexagon as h; print(h.TOOLCHAIN_IMAGE)')" +ndk="${ANDROID_NDK_HOME:?Select the Linux Android NDK r28c directory}" +tag="${1:?Pass the version associated with the candidate archive}" +[[ "$tag" =~ ^(v[0-9]+\.[0-9]+\.[0-9]+|b[1-9][0-9]*)(-[1-9][0-9]*)?$ ]] +grep -Fx "Pkg.Revision = $ndk_version" "$ndk/source.properties" + +docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" \ + --mount "type=bind,src=$PWD,dst=/workspace" \ + --mount "type=bind,src=$ndk,dst=/owner-ndk,readonly" \ + --workdir /workspace --entrypoint /bin/bash \ + --env HOME=/tmp --env ANDROID_NDK_HOME=/owner-ndk \ + --env ANDROID_NDK_ROOT=/owner-ndk --env ANDROID_NDK=/owner-ndk \ + --env "HEXAGON_CANDIDATE_TAG=$tag" --env "HEXAGON_BUILD_JOBS=${HEXAGON_BUILD_JOBS:-4}" \ + "$image" -c ' + set -euo pipefail + python3 tools/build.py android --abi arm64-v8a --backend hexagon --jobs "$HEXAGON_BUILD_JOBS" + llvm="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin" + out="bin/android/arm64-hexagon" + python3 tools/validate_android_artifacts.py --readelf "$llvm/llvm-readelf" --hexagon "$out" + python3 tools/validate_exports.py --format readelf --tool "$llvm/llvm-readelf" "$out/libllamadart.so" + python3 tools/validate_build_identity.py "$out/libllamadart.so" + python3 tools/validate_android_cpu_isa.py --objdump "$llvm/llvm-objdump" --readelf "$llvm/llvm-readelf" \ + --llama-source third_party/llama.cpp \ + --kleidiai-source build/android-arm64-v8a-hexagon-android_armv8.2_2/_deps/kleidiai-src \ + "$out/libggml-cpu-android_armv8.2_2.so" + disassembly="$(mktemp)" + trap "rm -f -- \"$disassembly\"" EXIT + "$llvm/llvm-objdump" -d "$out/libggml-cpu-android_armv8.0_1.so" > "$disassembly" + if grep -Eiq "stlurh?|stlurb" "$disassembly"; then + echo "Found unsupported armv8.4-a LRCPC2 STLUR instructions in the baseline CPU module" >&2 + exit 1 + fi + + archive="artifacts/hexagon-candidate/llamadart-native-android-arm64-hexagon-$HEXAGON_CANDIDATE_TAG.tar.gz" + PYTHONPATH=tools python3 - "$out" "$archive" <<\PY +from pathlib import Path +import sys + +import android_hexagon +import build + +android_hexagon.pack_archive(Path(sys.argv[1]), Path(sys.argv[2]), build.android_arm64_cpu_variant_libs()) +PY + python3 tools/validate_android_artifacts.py --readelf "$llvm/llvm-readelf" --hexagon-archive "$archive" + ( + cd "$(dirname "$archive")" + sha256sum "$(basename "$archive")" > SHA256SUMS + ) + ' diff --git a/tools/validate_android_artifacts.py b/tools/validate_android_artifacts.py index 0202a247..ce036065 100644 --- a/tools/validate_android_artifacts.py +++ b/tools/validate_android_artifacts.py @@ -3,8 +3,11 @@ import argparse import subprocess +import tarfile +import tempfile from pathlib import Path +import android_hexagon import build import llama_cpp_patches @@ -16,7 +19,14 @@ def parse_args() -> argparse.Namespace: parser.add_argument("--backend-only", action="store_true", help="skip CPU packaging checks for a backend-only payload") parser.add_argument("--min-load-align", type=lambda value: int(value, 0), default=0x4000) - return parser.parse_args() + hexagon = parser.add_mutually_exclusive_group() + hexagon.add_argument("--hexagon", action="store_true", help="validate the opt-in Android arm64 bundle") + hexagon.add_argument("--hexagon-archive", action="store_true", + help="validate an opt-in Android arm64 release tar.gz instead of a directory") + args = parser.parse_args() + if args.backend_only and (args.hexagon or args.hexagon_archive): + parser.error("Hexagon validation requires the complete Android arm64 bundle") + return args def read_load_alignments(readelf: Path, library: Path) -> list[int]: @@ -117,10 +127,7 @@ def cpu_variant_errors(libraries: list[Path]) -> list[str]: ] -def main() -> None: - args = parse_args() - if not args.readelf.is_file(): - raise SystemExit(f"Missing llvm-readelf binary: {args.readelf}") +def validate_directory(args: argparse.Namespace) -> None: if not args.out_dir.is_dir(): raise SystemExit(f"Missing Android artifact directory: {args.out_dir}") @@ -130,6 +137,13 @@ def main() -> None: errors: list[str] = [] symbols = {library.name: read_dynamic_symbols(args.readelf, library) for library in libraries} + if args.hexagon or args.hexagon_archive: + android_hexagon.validate(args.out_dir, args.readelf, build.android_arm64_cpu_variant_libs(), + symbols, read_dynamic_symbols) + elif (args.out_dir / android_hexagon.HOST_LIBRARY).exists() or any( + args.out_dir.rglob("libggml-htp-*.so") + ) or (args.out_dir / android_hexagon.MANIFEST).exists() or (args.out_dir / android_hexagon.NOTICES).exists(): + errors.append("Default Android artifacts must exclude Hexagon host and DSP files") errors.extend(exception_runtime_errors(symbols)) errors.extend(llama_cpp_patches.android_marker_errors( args.out_dir, include_cpu=not args.backend_only)) @@ -164,5 +178,22 @@ def main() -> None: raise SystemExit("\n".join(errors)) +def main() -> None: + args = parse_args() + if not args.readelf.is_file(): + raise SystemExit(f"Missing llvm-readelf binary: {args.readelf}") + try: + if args.hexagon_archive: + with tempfile.TemporaryDirectory() as temp: + archive = args.out_dir + args.out_dir = Path(temp) + android_hexagon.unpack_archive(archive, args.out_dir, build.android_arm64_cpu_variant_libs()) + validate_directory(args) + else: + validate_directory(args) + except (OSError, ValueError, tarfile.TarError) as error: + raise SystemExit(str(error)) from error + + if __name__ == "__main__": main() From e33427477daea711dea18a7605d365644cb4b206 Mon Sep 17 00:00:00 2001 From: Jhin Lee Date: Tue, 1 Dec 2026 17:47:32 -0500 Subject: [PATCH 2/2] Record Hexagon SDK approval and make candidate staging repeatable --- .github/workflows/android_hexagon_candidate.yml | 1 + README.md | 6 ++++-- docs/android_hexagon.md | 8 ++++---- tests/test_android_hexagon.py | 10 ++++++++++ tools/android_hexagon.py | 5 +++-- 5 files changed, 22 insertions(+), 8 deletions(-) diff --git a/.github/workflows/android_hexagon_candidate.yml b/.github/workflows/android_hexagon_candidate.yml index 7782102c..a80b5bb2 100644 --- a/.github/workflows/android_hexagon_candidate.yml +++ b/.github/workflows/android_hexagon_candidate.yml @@ -6,6 +6,7 @@ on: - '.github/workflows/android_hexagon_candidate.yml' - 'tests/test_android_hexagon.py' - 'tools/android_hexagon.py' + - 'tools/build.py' - 'tools/build_android_hexagon_candidate.sh' workflow_call: inputs: diff --git a/README.md b/README.md index d3fea016..84ee7a36 100644 --- a/README.md +++ b/README.md @@ -143,8 +143,10 @@ the following per-target bundles: - Windows arm64: Vulkan + BLAS + Kleidi + CPU An experimental [Android arm64 Hexagon candidate](docs/android_hexagon.md) -provides a separate CPU + HTP bundle for qualification. Publication is gated -on review of the Qualcomm SDK agreement. +provides a separate CPU + HTP bundle for qualification. The maintainer approved +hosted SDK use and redistribution of the generated DSP skeletons in +[#260](https://github.com/leehack/llamadart-native/issues/260#issuecomment-7326932721). +Publishing the candidate requires a separate maintainer decision. Non-Apple targets use `GGML_BACKEND_DL=ON`, so backend libs are optional at package/runtime level. diff --git a/docs/android_hexagon.md b/docs/android_hexagon.md index d14d9437..063837ac 100644 --- a/docs/android_hexagon.md +++ b/docs/android_hexagon.md @@ -1,9 +1,9 @@ # Experimental Android arm64 Hexagon candidate -Publication is gated on maintainer confirmation of the Qualcomm Hexagon SDK -Community Edition 6.7.0.0 agreement for hosted CI and distribution of the -generated FastRPC stub and DSP skeletons. The maintainer approved the -qualification build in [#260](https://github.com/leehack/llamadart-native/issues/260#issuecomment-7326932721). +The maintainer approved use of Qualcomm Hexagon SDK Community Edition 6.7.0.0 +in hosted CI and redistribution of the generated DSP skeletons in +[#260](https://github.com/leehack/llamadart-native/issues/260#issuecomment-7326932721). +Publishing the candidate requires a separate maintainer decision. The [Qualcomm catalog](https://softwarecenter.qualcomm.com/catalog/item/Hexagon_SDK?version=6.7.0.0) links the vendor distribution. The [public SDK repack](https://github.com/snapdragon-toolchain/hexagon-sdk/releases/tag/v6.7.0.0) contains third-party notices that refer Qualcomm terms to a separate agreement. diff --git a/tests/test_android_hexagon.py b/tests/test_android_hexagon.py index d80626c4..3a0dd967 100644 --- a/tests/test_android_hexagon.py +++ b/tests/test_android_hexagon.py @@ -78,6 +78,16 @@ def test_opt_in_archive_round_trips_with_exact_notices_and_assets(self): (self.out / hexagon.NOTICES).read_bytes(), (extracted / hexagon.NOTICES).read_bytes() ) + def test_restaging_refreshes_skeletons_and_manifest(self): + name = next(iter(hexagon.SKELETONS)) + skeleton = self.dsp / name + skeleton.write_bytes(skeleton.read_bytes() + b"rebuilt") + + hexagon.stage_assets(self.build, self.out, self.sdk) + + self.assertEqual((self.out / hexagon.ASSET_DIR / name).read_bytes(), skeleton.read_bytes()) + self.validate() + def test_rejects_skeleton_in_host_library_directory(self): name = next(iter(hexagon.SKELETONS)) (self.out / hexagon.ASSET_DIR / name).rename(self.out / name) diff --git a/tools/android_hexagon.py b/tools/android_hexagon.py index 4ccba904..76b92304 100644 --- a/tools/android_hexagon.py +++ b/tools/android_hexagon.py @@ -60,7 +60,8 @@ f"SDK repack: https://github.com/snapdragon-toolchain/hexagon-sdk/releases/tag/v{SDK_VERSION}\n" f"Linux amd64 SDK repack SHA-256: {SDK_REPACK_SHA256}\n" f"Qualcomm catalog: https://softwarecenter.qualcomm.com/catalog/item/Hexagon_SDK?version={SDK_VERSION}\n" - "The SDK agreement covering the generated binaries is pending maintainer review.\n" + "Maintainer approved SDK use in hosted CI and redistribution of the generated DSP skeletons.\n" + "Approval: https://github.com/leehack/llamadart-native/issues/260#issuecomment-7326932721\n" ).encode() @@ -136,7 +137,7 @@ def stage_assets(build_dir: Path, out_dir: Path, sdk: Path) -> None: if {path.name for path in output.glob("libggml-htp-*.so")} != SKELETONS.keys(): raise ValueError(f"Unexpected Hexagon skeleton set in {output}") assets = out_dir / ASSET_DIR - assets.mkdir(parents=True) + assets.mkdir(parents=True, exist_ok=True) for name in SKELETONS: shutil.copyfile(output / name, assets / name) (out_dir / NOTICES).write_bytes(notices_bytes(sdk))