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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -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
104 changes: 104 additions & 0 deletions .github/workflows/android_hexagon_candidate.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
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.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
20 changes: 20 additions & 0 deletions .github/workflows/native_release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,12 @@ 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. 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.

## Runtime Packaging Model
Expand Down
60 changes: 60 additions & 0 deletions docs/android_hexagon.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Experimental Android arm64 Hexagon candidate

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.

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 <native-tag>` 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
`<uses-native-library>` under `<application>`. 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).
3 changes: 3 additions & 0 deletions docs/platform_backend_strategy.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions scripts/publish_prepared_release.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
144 changes: 144 additions & 0 deletions tests/test_android_hexagon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
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("<HH", data, 16, 3, machine)
struct.pack_into("<I", data, 36 if elf_class == 1 else 48, flags)
return data


class AndroidHexagonTests(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.root = Path(temp.name)
self.sdk = self.root / hexagon.SDK_VERSION
self.variants = build.android_arm64_cpu_variant_libs()
self.runtime_names = hexagon.CORE_LIBRARIES | set(self.variants)
self.out = self.root / "bundle"
self.out.mkdir()
notice_files = {}
for name in hexagon.NOTICE_FILES:
notice = f"{name}\r\n\xff\r\n".encode("latin-1")
path = self.sdk / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(notice)
notice_files[name] = hexagon.digest(notice)
patch = mock.patch.object(hexagon, "NOTICE_FILES", notice_files)
patch.start()
self.addCleanup(patch.stop)

for name in self.runtime_names:
(self.out / name).write_bytes(elf(2, 183))
(self.out / hexagon.HOST_LIBRARY).write_bytes(elf(2, 183) + b"libcdsprpc.so\0")

self.build = self.root / "build"
self.dsp = self.build / "third_party/llama.cpp/ggml/src/ggml-hexagon"
self.dsp.mkdir(parents=True)
for name, flags in hexagon.SKELETONS.items():
(self.dsp / name).write_bytes(elf(1, 164, flags))
hexagon.stage_assets(self.build, self.out, self.sdk)
self.symbols = {name: ({"ggml_backend_init", "ggml_backend_score"}, set())
for name in self.runtime_names}
self.dependencies = {name: ({"libc.so"}, name) for name in self.runtime_names}
self.dependencies[hexagon.HOST_LIBRARY] = ({"libc.so", "libggml-base.so"}, None)
self.dependencies.update({name: (hexagon.DSP_LIBRARIES, name) for name in hexagon.SKELETONS})

def validate(self, out=None):
with mock.patch.object(hexagon, "dynamic_tags", side_effect=lambda tool, path: self.dependencies[path.name]), \
mock.patch.object(hexagon, "check_android_note"):
hexagon.validate(out or self.out, Path("readelf"), self.variants, self.symbols,
lambda tool, path: ({"htp_iface_skel_handle_invoke"}, set()))

def refresh_manifest(self):
(self.out / hexagon.MANIFEST).write_text(json.dumps(hexagon.asset_manifest(self.out)))

def test_opt_in_archive_round_trips_with_exact_notices_and_assets(self):
archive = self.root / "bundle.tar.gz"
hexagon.pack_archive(self.out, archive, self.variants)
extracted = self.root / "extracted"
hexagon.unpack_archive(archive, extracted, self.variants)
self.validate(extracted)
self.assertEqual(
(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)
with self.assertRaisesRegex(ValueError, "bundle contents differ"):
self.validate()

def test_rejects_stale_skeleton(self):
name = next(iter(hexagon.SKELETONS))
(self.out / hexagon.ASSET_DIR / name).write_bytes(elf(1, 164, 0x75))
with self.assertRaisesRegex(ValueError, "SHA-256"):
self.validate()

self.refresh_manifest()
with self.assertRaisesRegex(ValueError, "expected Hexagon ELF32 with flags 0x73"):
self.validate()

def test_rejects_non_aarch64_host(self):
(self.out / hexagon.HOST_LIBRARY).write_bytes(elf(2, 62))
self.refresh_manifest()
with self.assertRaisesRegex(ValueError, "expected Android AArch64 ELF64"):
self.validate()

def test_checks_transitive_dependencies_in_core(self):
self.dependencies["libggml-base.so"] = ({"libc++_shared.so"}, "libggml-base.so")
with self.assertRaisesRegex(ValueError, "dependencies outside the Android runtime set"):
self.validate()

def test_requires_host_backend_init_export(self):
self.symbols[hexagon.HOST_LIBRARY] = (set(), set())
with self.assertRaisesRegex(ValueError, "missing backend initializer"):
self.validate()

def test_rejects_notice_mutation_even_with_updated_bundle_hash(self):
path = self.out / hexagon.NOTICES
path.write_bytes(path.read_bytes().replace(b"\r\n", b"\n"))
self.refresh_manifest()
with self.assertRaisesRegex(ValueError, "notice bytes differ"):
self.validate()

def test_rejects_extra_archive_entries(self):
archive = self.root / "unexpected.tar.gz"
with tarfile.open(archive, "w:gz") as tar:
member = tarfile.TarInfo("../wrong.so")
member.size = 1
tar.addfile(member, io.BytesIO(b"x"))
with self.assertRaisesRegex(ValueError, "Unexpected Hexagon archive member"):
hexagon.unpack_archive(archive, self.root / "extracted", self.variants)

def test_rejects_r29_ndk_even_when_sdk_is_installed(self):
ndk = self.root / "ndk"
ndk.mkdir()
(ndk / "source.properties").write_text("Pkg.Revision = 29.0.14206865\n")
with self.assertRaisesRegex(ValueError, "NDK r28c"):
hexagon.cache_vars(ndk, {})
Loading
Loading