diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..d16cb6c0e0e864ea67d887d482162301788ce608 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +app/src/main/res/drawable-nodpi/bonsai_launcher.png filter=lfs diff=lfs merge=lfs -text +bonsai-icon-source.png filter=lfs diff=lfs merge=lfs -text +release/BonsaiLocal-debug.apk filter=lfs diff=lfs merge=lfs -text +screenshots/01-start.png filter=lfs diff=lfs merge=lfs -text +screenshots/02-model-loaded.png filter=lfs diff=lfs merge=lfs -text +screenshots/03-benchmark.png filter=lfs diff=lfs merge=lfs -text +screenshots/04-reasoning.png filter=lfs diff=lfs merge=lfs -text +screenshots/05-russian-kotlin.png filter=lfs diff=lfs merge=lfs -text +screenshots/06-final-installed.png filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6f1ca992faaa7f4372c8104d014d648e97208a5a --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/.gradle/ +/.idea/ +/**/build/ +/**/.cxx/ +/models/ +/local.properties +*.iml +*.log diff --git a/BENCHMARKS.md b/BENCHMARKS.md new file mode 100644 index 0000000000000000000000000000000000000000..d0c0c67f0ee97bf4bdc9893474461ed54295bd53 --- /dev/null +++ b/BENCHMARKS.md @@ -0,0 +1,58 @@ +# Android benchmark results / Результаты Android-бенчмарка + +[English](#english) · [Русский](#русский) + +## English + +These measurements were produced inside the `Bonsai_27B_Test` Android emulator +by the JNI runtime packaged in the APK. They are not desktop `llama-cli` +measurements. + +| Metric | Result | +|---|---:| +| Prompt processing, 64 tokens | **2.89 tokens/s** | +| Token generation, 32 tokens | **1.79 tokens/s** | +| Arithmetic prompt | `37 × 19` → **703** | +| Model | Bonsai-27B Q1_0, 26.9B parameters, 3.53 GiB | +| Backend | Android x86_64 CPU | +| Context / batch | 8,192 / 512 | +| Fatal exceptions | 0 observed | + +Runtime activation observed in Android logcat: automatic Flash Attention, +fused Gated Delta Net autoregressive and chunked paths, 3,703 graph nodes, one +graph split, 149.62 MiB recurrent buffer, and 523.02 MiB CPU compute buffer. + +The Russian/Kotlin prompt reached the configured 512-token generation limit in +thinking mode. It demonstrated prompt comprehension but did not produce a clean +final answer, so it is marked as a failed instruction-following case. + +## Русский + +Эти замеры выполнены внутри Android-эмулятора `Bonsai_27B_Test` через JNI +runtime из APK. Это не результаты настольного `llama-cli`. + +| Метрика | Результат | +|---|---:| +| Обработка prompt, 64 токена | **2,89 токена/с** | +| Генерация, 32 токена | **1,79 токена/с** | +| Арифметическая задача | `37 × 19` → **703** | +| Модель | Bonsai-27B Q1_0, 26,9B параметров, 3,53 GiB | +| Backend | Android x86_64 CPU | +| Контекст / batch | 8 192 / 512 | +| FATAL EXCEPTION | 0 обнаружено | + +В Android logcat подтверждены автоматический Flash Attention, fused Gated Delta +Net для autoregressive и chunked путей, 3 703 узла графа, один split, recurrent +buffer 149,62 MiB и CPU compute buffer 523,02 MiB. + +Русско-Kotlin запрос достиг лимита генерации 512 токенов в thinking-mode. +Модель поняла условия, но не вывела чистый финальный ответ, поэтому этот тест +отмечен как неуспешный instruction-following, а не как пройденный. + +## Evidence / Скриншоты + +- [`02-model-loaded.png`](screenshots/02-model-loaded.png) +- [`03-benchmark.png`](screenshots/03-benchmark.png) +- [`04-reasoning.png`](screenshots/04-reasoning.png) +- [`05-russian-kotlin.png`](screenshots/05-russian-kotlin.png) +- [`06-final-installed.png`](screenshots/06-final-installed.png) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..857203e8967df46a4a6fff1883f424cb8cb8e924 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 livadies + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..55b2d631a5435334fcaa7481acd8addccc457604 --- /dev/null +++ b/README.md @@ -0,0 +1,410 @@ +--- +license: mit +pipeline_tag: text-generation +language: +- ru +- en +tags: +- android +- gguf +- llama-cpp +- on-device +- bonsai-27b +--- + +# Bonsai Local for Android + +**Русский** · [English](README_EN.md) · [Структурированные результаты](BENCHMARKS.md) + +Исследовательское Android-приложение для полностью локального запуска +[Prism ML Bonsai-27B GGUF](https://huggingface.co/prism-ml/Bonsai-27B-gguf) +через JNI и специальный форк `llama.cpp`. После помещения GGUF на устройство +диалог не использует сервер, облачный API или интернет. + +![Bonsai Local с загруженной моделью](screenshots/02-model-loaded.png) + +## Что уже работает + +- полноценная загрузка `Bonsai-27B-Q1_0.gguf` размером 3 803 452 480 байт; +- inference внутри Android-процесса, без сервера на ПК; +- потоковый чат и thinking-mode; +- автообнаружение GGUF в приватной и app-specific external папках; +- ручной импорт любого совместимого GGUF через Android Storage Access Framework; +- встроенный benchmark prompt processing / token generation; +- APK для `arm64-v8a` реального телефона и `x86_64` эмулятора; +- Android adaptive icon и отдельные raster mipmaps; +- debug-вход `prompt_b64` для воспроизводимых автоматических тестов Unicode prompts. + +## Проверенная конфигурация + +| Компонент | Значение | +|---|---| +| ОС хоста | Windows 11 | +| CPU хоста | Intel Core Ultra 5 125H | +| Android Studio | 2025.2 | +| Android Gradle Plugin | 8.13.2 | +| Gradle | 8.14.3 | +| JDK сборки | JetBrains Runtime 21.0.9 | +| compileSdk / targetSdk | 36 / 36 | +| minSdk | 30 (Android 11) | +| Android NDK | 28.2.13676358 | +| CMake | 3.22.1 | +| ABI | `arm64-v8a`, `x86_64` | +| Тестовый AVD | Android 17 preview, x86_64, 8 ГБ RAM, 16 ГБ data | +| PrismML llama.cpp commit | `62061f91088281e65071cc38c5f69ee95c39f14e` | + +## Результаты локальных тестов + +Все числа ниже получены внутри Android-эмулятора, а не настольным +`llama-cli`. + +| Проверка | Результат | +|---|---| +| Сборка debug APK | успешно | +| Установка и запуск Android | успешно | +| Распознавание модели | `qwen35 27B Q1_0`, 26.9B params, 3.53 GiB | +| Backend | CPU, динамически выбранный x86_64 variant | +| Prompt processing, pp64 | **2.89 tok/s** | +| Token generation, tg32 | **1.79 tok/s** | +| Арифметика `37 × 19` | корректный результат **703** | +| Thinking trace | работает | +| Русский + Kotlin, лимит 512 токенов | prompt понят, но весь лимит ушёл на thinking; чистый финальный код не выведен | +| Полностью offline после импорта | да | +| Крэши / FATAL EXCEPTION | не обнаружены | + +Скриншоты: + +- [`02-model-loaded.png`](screenshots/02-model-loaded.png) — модель загружена; +- [`03-benchmark.png`](screenshots/03-benchmark.png) — benchmark; +- [`04-reasoning.png`](screenshots/04-reasoning.png) — реальная генерация и ответ 703; +- [`05-russian-kotlin.png`](screenshots/05-russian-kotlin.png) — негативный capability-тест: + модель поняла русский Kotlin prompt, но исчерпала лимит в thinking-mode. + +Скорость эмулятора нельзя переносить на физический телефон: виртуализированный +CPU, thermal policy и доступные SIMD-инструкции отличаются. В карточке модели +Prism ML публикует существенно более высокие результаты для нативного MLX на +современном iPhone; этот проект использует Android/llama.cpp CPU backend. + +## Архитектура + +```mermaid +flowchart TD + UI["Android UI · MainActivity"] --> API["InferenceEngine Kotlin API"] + API --> DISP["Single-thread coroutine dispatcher"] + DISP --> JNI["JNI · libai-chat.so"] + JNI --> COMMON["llama-common · chat template · sampler"] + JNI --> LLAMA["PrismML llama.cpp"] + LLAMA --> GGML["GGML CPU backend loader"] + GGML --> ABI{"Device ABI / CPU features"} + ABI --> ARM["ARM variants · NEON / DOTPROD / I8MM / SVE / SME"] + ABI --> X86["x86_64 variants · SSE4 / AVX2 / AVX512 / AMX"] + GGUF["Bonsai-27B-Q1_0.gguf · 3.80 GB"] --> LLAMA +``` + +### Модули + +- `app/` — UI, импорт модели, чат, benchmark и тестовый Base64 intent. +- `lib/` — Android-friendly Kotlin API и JNI wrapper. +- `third_party/llama.cpp/` — форк PrismML с Q1_0 и hybrid-attention kernels; + находится рядом с проектом, на уровень выше `BonsaiAndroid`. +- `models/` — локальная копия GGUF для исследования; модель не упаковывается + в APK. +- `screenshots/` — фактические результаты запуска в эмуляторе. + +### Поток загрузки + +1. `MainActivity` ждёт состояния `InferenceEngine.State.Initialized`. +2. Ищет `.gguf` в `files/models` и `getExternalFilesDir()/models`. +3. Передаёт абсолютный путь в `InferenceEngine.loadModel()`. +4. Kotlin сериализует все вызовы через один `Dispatchers.IO` dispatcher. +5. JNI вызывает `llama_model_load_from_file()`, затем создаёт контекст 8192 + токенов, batch 512 и sampler. +6. GGML выбирает подходящую CPU-библиотеку из `nativeLibraryDir`. +7. Chat template формирует сообщения Qwen, а JNI возвращает token pieces как + Kotlin `Flow`. + +Критический фрагмент JNI: + +```cpp +llama_model_params model_params = llama_model_default_params(); +g_model = llama_model_load_from_file(model_path, model_params); + +llama_context_params ctx_params = llama_context_default_params(); +ctx_params.n_ctx = 8192; +ctx_params.n_batch = 512; +ctx_params.n_threads = n_threads; +g_context = llama_init_from_model(g_model, ctx_params); +``` + +Сериализация native calls важна: глобальные `llama_model`, `llama_context`, +`llama_batch` и sampler не должны одновременно изменяться UI и benchmark +корутинами. + +```kotlin +private val llamaDispatcher = Dispatchers.IO.limitedParallelism(1) + +override suspend fun loadModel(pathToModel: String) = + withContext(llamaDispatcher) { + load(pathToModel) + prepare() + } +``` + +## Что подтверждено в native runtime + +При фактической загрузке полного GGUF runtime сообщил: + +- 64 transformer blocks; +- Q1_0 binary tensors; +- recurrent state около 149.62 MiB; +- CPU compute buffer около 523.02 MiB; +- Flash Attention включён автоматически; +- fused Gated Delta Net работает в autoregressive и chunked режимах; +- graph содержит около 3703 nodes и один split. + +Bonsai-27B **не MoE-модель**. У неё нет набора экспертов и router, поэтому +проверка «всех экспертов» неприменима. Это dense 27B hybrid-attention model: +примерно 75% слоёв используют linear/recurrent attention и 25% — full +attention. + +Текущий APK текстовый. Дополнительные компоненты из репозитория модели не +подключены: + +- `Bonsai-27B-mmproj-Q8_0.gguf` — vision tower; +- `Bonsai-27B-dspark-Q4_1.gguf` — speculative decoding drafter. + +## Требования к устройству + +- Android 11 или новее; +- 64-bit ARM или x86_64; +- минимум 5 ГБ свободного места только под GGUF, комфортно 8+ ГБ; +- рекомендуется 8 ГБ RAM или больше; +- для импорта через picker временно может потребоваться место для копии; +- первый старт модели может занимать десятки секунд. + +Вес модели не включён в APK, потому что обычный APK с asset размером 3.8 ГБ +непрактичен и превышает типичный delivery budget. SHA-256 проверенной модели: + +```text +17EF842E47450CAEB8EAA3EBFBBAB5D2F2278B62B79BE107985FB69A2F819AA0 +``` + +Официальная карточка указывает около 5.2 ГБ peak memory при 4K context без +KV-cache compression. Android `dumpsys meminfo` показывает для процесса +меньше, потому что memory-mapped страницы GGUF и page cache учитываются не так, +как private native heap. + +## Сборка в Android Studio + +1. Открыть папку `BonsaiAndroid` в Android Studio. +2. Убедиться, что рядом есть `third_party/llama.cpp`: + + ```text + gpt/ + ├── BonsaiAndroid/ + └── third_party/llama.cpp/ + ``` + +3. Установить SDK 36, NDK `28.2.13676358` и CMake `3.22.1`. +4. Проверить путь SDK в `local.properties`. +5. Выполнить `Build > Make Project` или из PowerShell: + + ```powershell + $env:JAVA_HOME = 'C:\Program Files\Android\Android Studio1\jbr' + java -classpath gradle\wrapper\gradle-wrapper.jar ` + org.gradle.wrapper.GradleWrapperMain :app:assembleDebug + ``` + +Debug APK появляется в: + +```text +app/build/outputs/apk/debug/app-debug.apk +``` + +Проверенный итоговый артефакт дополнительно скопирован в: + +```text +release/BonsaiLocal-debug.apk +``` + +Его размер — 120 762 843 байта, SHA-256: + +```text +BDAF2D9EE7EE1BBB2A424242678D75AC35F2B770973E3F4C9E58639CE8F93E5C +``` + +Первая сборка долгая: генерируются сотни C/C++ объектов и несколько CPU +variants для двух ABI. Инкрементальные сборки значительно быстрее. + +### Привязка llama.cpp в CMake + +Проект был вынесен из `examples/llama.android`, поэтому относительный путь +исходников пришлось изменить: + +```cmake +set(LLAMA_SRC ${CMAKE_CURRENT_LIST_DIR}/../../../../../third_party/llama.cpp) +add_subdirectory(${LLAMA_SRC} build-llama) +``` + +Для Android компилируются обе ABI: + +```kotlin +ndk { + abiFilters += listOf("arm64-v8a", "x86_64") +} +``` + +## Установка модели + +### Обычный пользовательский путь + +1. Скопировать `Bonsai-27B-Q1_0.gguf` на телефон. +2. Открыть приложение. +3. Нажать **Выбрать GGUF** и выбрать файл. +4. Дождаться копирования и загрузки. + +### Воспроизводимый путь для эмулятора + +После первой установки APK: + +```powershell +adb -s emulator-5556 shell mkdir -p ` + /sdcard/Android/data/com.prismml.bonsailocal/files/models + +adb -s emulator-5556 push .\models\Bonsai-27B-Q1_0.gguf ` + /sdcard/Android/data/com.prismml.bonsailocal/files/models/ +``` + +После перезапуска приложение найдёт модель автоматически. + +## Воспроизводимые тесты Unicode + +Debug Activity принимает Base64 UTF-8 prompt. Это обход нестабильного Unicode +input у ADB-клавиатуры preview-эмулятора и не участвует в обычном UI. + +```powershell +$prompt = 'Ответь по-русски одним предложением.' +$b64 = [Convert]::ToBase64String( + [Text.Encoding]::UTF8.GetBytes($prompt) +) + +adb shell am start ` + -n com.prismml.bonsailocal/.MainActivity ` + --es prompt_b64 $b64 +``` + +В коде extra декодируется без сетевых вызовов: + +```kotlin +String(Base64.decode(encoded, Base64.NO_WRAP), Charsets.UTF_8) +``` + +## Проблемы, встреченные при разработке + +### 1. Готового Android runtime у коллекции нет + +Коллекция публикует GGUF и специальный PrismML fork, но не готовый AAR/APK. +Решение: официальный `examples/llama.android` из форка использован как база, +а CMake собирает runtime прямо внутри Gradle. + +### 2. Стандартный llama.cpp недостаточен + +Модель использует Q1_0 и Qwen 3.5/3.6 hybrid architecture. Решение: закреплён +именно PrismML fork commit `62061f9`, содержащий нужные quantization и Gated +Delta Net paths. + +### 3. JDK 17 toolchain отсутствовал + +Gradle запускался на JBR 21, а исходный sample требовал установленный JDK 17 +через `jvmToolchain(17)`. Gradle не имел repository для автоматической загрузки. +Решение: убрать принудительный поиск отдельного toolchain и явно компилировать +Java/Kotlin bytecode target 17: + +```kotlin +kotlin { + compilerOptions { jvmTarget.set(JvmTarget.JVM_17) } +} +``` + +### 4. Android logging API + +`__android_log_is_loggable()` доступен только с API 30, а ранняя конфигурация +использовала minSdk 28. Решение: локальный фильтр log level и итоговый minSdk +30. + +### 5. Эмулятор был слишком маленьким + +Существующий Pixel_7 имел 2 ГБ RAM и раздел data 6 ГБ, из которых свободно +около 1.1 ГБ. Модель туда не помещалась. Создан отдельный AVD +`Bonsai_27B_Test` с 8 ГБ RAM и 16 ГБ data, не затрагивающий пользовательский +Pixel_7. + +### 6. 16 KB memory pages + +Android 15+ требует 16 KB-compatible native libraries. Проект использует NDK +r28 и AGP 8.13.2. Проверено: + +- ELF `LOAD` alignment: `2**14` для native `.so`; +- `zipalign -v -c -P 16 4 app-debug.apk`: `Verification successful`. + +Android 17 preview system image дополнительно показывает экспериментальный +RELRO compatibility dialog для части динамически загружаемых CPU variants. +Неиспользуемый `androidx.datastore` был удалён из общего dependency bundle, +что исключило `libdatastore_shared_counter.so` из APK. После этого в APK +осталось 32 целевых native-библиотеки вместо 36. +APK продолжает работать в page-size compatibility mode. Для production перед +публикацией нужно повторить проверку на стабильном Android 15/16 16 KB image и +обновить NDK/PrismML fork, если preview-проверка станет обязательной. + +### 7. Большой GGUF нельзя дублировать бездумно + +Импорт в private storage может временно требовать две копии. Для тестового AVD +модель отправлялась сразу в app-specific external directory, которую приложение +сканирует при старте. + +### 8. Thinking mode делает даже короткие тесты долгими + +Запрос с требованием вернуть одно число всё равно сгенерировал подробный +`` блок. Это ожидаемое поведение модели и полезная проверка reasoning, +но на CPU-эмуляторе занимает минуты. UI генерирует асинхронно и не блокирует +main thread. Более сложный русский Kotlin prompt подтвердил понимание задачи, +но за 512 токенов модель не вышла из thinking в финальный ответ. Это не падение +runtime, а ограничение текущей политики генерации; для прикладного UI нужны +отдельная панель reasoning, больший лимит или поддерживаемое моделью отключение +thinking-mode. + +## Ограничения текущей версии + +- только text-to-text; vision projection не загружается; +- только CPU backend в протестированном AVD; +- нет встроенного resumable downloader и проверки SHA-256 в UI; +- модель не включена в APK; +- история чата живёт в памяти Activity и не сохраняется после полного restart; +- контекст приложения ограничен 8192 токенами, хотя модель обучена на гораздо + более длинный контекст; +- thinking-теги показываются как обычный текст; +- на устройствах с 6 ГБ RAM возможен LMK/OOM; +- DSpark speculative decoding не подключён. + +## Куда развивать исследование + +1. Отделить `` в сворачиваемую UI-панель. +2. Добавить resumable WorkManager/foreground download с SHA-256. +3. Подключить `mmproj` и Android Photo Picker для vision. +4. Исследовать Vulkan backend на Android GPU и сравнить CPU/Vulkan. +5. Подключить Q4 KV cache и замерить RAM на 8K/32K/100K. +6. Проверить DSpark drafter, когда Android path будет поддержан форком. +7. Добавить Room для истории диалогов и export/import sessions. +8. Собрать per-ABI APK/AAB, чтобы не поставлять обе native архитектуры каждому + устройству. +9. Добавить macrobenchmark: cold load, first-token latency, sustained tok/s, + thermal throttling и energy usage. +10. Запустить тот же test suite на физическом Snapdragon/Dimensity и сравнить + NEON, DOTPROD, I8MM и SVE variants. + +## Лицензии + +- Bonsai-27B GGUF: Apache-2.0 согласно карточке модели. +- llama.cpp / PrismML fork: см. лицензии в `third_party/llama.cpp`. +- При распространении APK и модели необходимо сохранить соответствующие + `LICENSE` и `NOTICE` файлов upstream-проектов. diff --git a/README_EN.md b/README_EN.md new file mode 100644 index 0000000000000000000000000000000000000000..f14fee9b4c69ae3e8d28af281eb58b532755dea9 --- /dev/null +++ b/README_EN.md @@ -0,0 +1,276 @@ +--- +license: mit +pipeline_tag: text-generation +language: +- en +- ru +tags: +- android +- gguf +- llama-cpp +- on-device +- bonsai-27b +--- + +# Bonsai Local for Android + +[Русский](README.md) · **English** · [Benchmarks / Замеры](BENCHMARKS.md) + +Research Android application that runs +[Prism ML Bonsai-27B GGUF](https://huggingface.co/prism-ml/Bonsai-27B-gguf) +fully on-device through JNI and the PrismML `llama.cpp` fork. Once the GGUF is +copied to the device, chat inference does not use a PC server, cloud API, or +internet connection. + +![Bonsai Local with the model loaded](screenshots/02-model-loaded.png) + +## What works + +- Loads the complete 3,803,452,480-byte `Bonsai-27B-Q1_0.gguf`. +- Performs inference inside the Android application process. +- Streams chat output and exposes the model's thinking trace. +- Auto-discovers GGUF files in private and app-specific external storage. +- Imports compatible GGUF files through Android Storage Access Framework. +- Includes an on-device prompt-processing/token-generation benchmark. +- Builds for physical `arm64-v8a` devices and `x86_64` emulators. +- Includes an adaptive Android launcher icon and raster mipmaps. +- Provides a debug-only Base64 UTF-8 prompt intent for reproducible tests. + +The model file is deliberately not embedded in the APK. It remains available +from the upstream model repository and would make application delivery +impractical. + +## Verified setup + +| Component | Value | +|---|---| +| Host | Windows 11, Intel Core Ultra 5 125H | +| Android Studio | 2025.2 | +| AGP / Gradle | 8.13.2 / 8.14.3 | +| Build JDK | JetBrains Runtime 21.0.9 | +| compileSdk / targetSdk / minSdk | 36 / 36 / 30 | +| Android NDK / CMake | 28.2.13676358 / 3.22.1 | +| APK ABIs | `arm64-v8a`, `x86_64` | +| Test AVD | Android 17 preview, x86_64, 8 GB RAM, 16 GB data | +| PrismML fork commit | `62061f91088281e65071cc38c5f69ee95c39f14e` | + +## Measured Android results + +All measurements below came from the Android emulator and the application JNI +runtime, not from desktop `llama-cli`. + +| Check | Result | +|---|---| +| Debug APK build, install, launch | passed | +| Recognized model | `qwen35 27B Q1_0`, 26.9B parameters, 3.53 GiB | +| Backend | CPU, dynamically selected x86_64 variant | +| Prompt processing, pp64 | **2.89 tokens/s** | +| Token generation, tg32 | **1.79 tokens/s** | +| Arithmetic prompt `37 × 19` | correct final answer: **703** | +| Thinking trace | operational | +| Offline inference after import | confirmed | +| Fatal exceptions | none observed | + +The Russian/Kotlin instruction-following test also produced a useful negative +result: the model understood the requested language, signature, and validation +constraints, but spent the complete 512-token limit in visible reasoning and +did not reach a clean final code answer. This is recorded rather than presented +as a successful result. + +Screenshots: + +- [`02-model-loaded.png`](screenshots/02-model-loaded.png) — final installed APK + with the local model loaded; +- [`03-benchmark.png`](screenshots/03-benchmark.png) — on-device benchmark; +- [`04-reasoning.png`](screenshots/04-reasoning.png) — live generation and 703; +- [`05-russian-kotlin.png`](screenshots/05-russian-kotlin.png) — 512-token + thinking-limit result. + +Emulator throughput should not be treated as a phone prediction. A physical +device has different SIMD support, thermal limits, memory bandwidth, and power +management. + +## Architecture + +```mermaid +flowchart TD + UI["Android UI · MainActivity"] --> API["InferenceEngine Kotlin API"] + API --> DISP["Single-thread coroutine dispatcher"] + DISP --> JNI["JNI · libai-chat.so"] + JNI --> COMMON["llama-common · chat template · sampler"] + JNI --> LLAMA["PrismML llama.cpp"] + LLAMA --> GGML["GGML CPU backend loader"] + GGML --> ABI{"Device ABI and CPU features"} + ABI --> ARM["ARM · NEON / DOTPROD / I8MM / SVE / SME"] + ABI --> X86["x86_64 · SSE4 / AVX2 / AVX512 / AMX"] + GGUF["Bonsai-27B-Q1_0.gguf · 3.80 GB"] --> LLAMA +``` + +Project modules: + +- `app/` — UI, model import, chat, benchmark, and Base64 test intent. +- `lib/` — Kotlin API, GGUF metadata reader, JNI, and native build. +- `third_party/llama.cpp/` — PrismML fork, kept next to this project when + building locally and not duplicated in this repository. +- `models/` — optional local research copy, excluded from publication. +- `screenshots/` — evidence captured from the Android emulator. +- `release/` — verified debug APK and checksum. + +Model load flow: + +1. `MainActivity` waits for the native engine to initialize. +2. It searches private and app-specific external `models` directories. +3. Kotlin passes the absolute GGUF path to `loadModel()`. +4. Native calls are serialized through one IO dispatcher. +5. JNI creates an 8,192-token context, batch size 512, and sampler. +6. GGML selects the best packaged CPU backend for the current ABI/features. +7. The Qwen chat template is applied and token pieces stream as `Flow`. + +Critical JNI setup: + +```cpp +llama_model_params model_params = llama_model_default_params(); +g_model = llama_model_load_from_file(model_path, model_params); + +llama_context_params ctx_params = llama_context_default_params(); +ctx_params.n_ctx = 8192; +ctx_params.n_batch = 512; +ctx_params.n_threads = n_threads; +g_context = llama_init_from_model(g_model, ctx_params); +``` + +Native state is serialized because model, context, batch, and sampler are +global native resources: + +```kotlin +private val llamaDispatcher = Dispatchers.IO.limitedParallelism(1) + +override suspend fun loadModel(pathToModel: String) = + withContext(llamaDispatcher) { + load(pathToModel) + prepare() + } +``` + +## Runtime capabilities verified + +The real full-GGUF load reported: + +- 64 transformer blocks and Q1_0 tensors; +- approximately 149.62 MiB recurrent state; +- approximately 523.02 MiB CPU compute buffer; +- automatic Flash Attention; +- fused Gated Delta Net in autoregressive and chunked paths; +- approximately 3,703 graph nodes and one split. + +Bonsai-27B is not a Mixture-of-Experts model. It is a dense 27B hybrid-attention +model, so there are no experts or routing network to enumerate. Roughly 75% of +its blocks use linear/recurrent attention and 25% full attention. + +This APK is text-only. The optional upstream vision projection +`Bonsai-27B-mmproj-Q8_0.gguf` and DSpark speculative drafter +`Bonsai-27B-dspark-Q4_1.gguf` are not integrated. + +## Build + +Place the pinned PrismML fork next to this project: + +```text +gpt/ +├── BonsaiAndroid/ +└── third_party/llama.cpp/ +``` + +Install SDK 36, NDK `28.2.13676358`, and CMake `3.22.1`, then open +`BonsaiAndroid` in Android Studio or run: + +```powershell +$env:JAVA_HOME = 'C:\Program Files\Android\Android Studio1\jbr' +java -classpath gradle\wrapper\gradle-wrapper.jar ` + org.gradle.wrapper.GradleWrapperMain :app:assembleDebug +``` + +The build output is `app/build/outputs/apk/debug/app-debug.apk`. The tested copy +is published as `release/BonsaiLocal-debug.apk`: + +```text +size: 120762843 bytes +SHA256: BDAF2D9EE7EE1BBB2A424242678D75AC35F2B770973E3F4C9E58639CE8F93E5C +``` + +The native runtime is wired through: + +```cmake +set(LLAMA_SRC ${CMAKE_CURRENT_LIST_DIR}/../../../../../third_party/llama.cpp) +add_subdirectory(${LLAMA_SRC} build-llama) +``` + +## Install the model + +Normal path: + +1. Copy `Bonsai-27B-Q1_0.gguf` to the Android device. +2. Open Bonsai Local. +3. Tap **Choose GGUF**. +4. Select the file and wait for import/load. + +Reproducible emulator path: + +```powershell +adb shell mkdir -p ` + /sdcard/Android/data/com.prismml.bonsailocal/files/models +adb push .\models\Bonsai-27B-Q1_0.gguf ` + /sdcard/Android/data/com.prismml.bonsailocal/files/models/ +``` + +Verified model checksum: + +```text +17EF842E47450CAEB8EAA3EBFBBAB5D2F2278B62B79BE107985FB69A2F819AA0 +``` + +## Problems encountered and fixes + +1. **No ready Android runtime in the collection.** The upstream Android sample + was adapted and the native runtime is built inside Gradle. +2. **Mainline llama.cpp was insufficient.** Q1_0 and the hybrid architecture + require the pinned PrismML fork. +3. **A separate JDK 17 toolchain was unavailable.** The project builds on JBR + 21 while explicitly targeting JVM bytecode 17. +4. **Android logging API level mismatch.** A local priority filter was used and + minSdk was finalized at API 30. +5. **The existing AVD had insufficient RAM/storage.** A dedicated 8 GB RAM, + 16 GB data AVD was created without modifying the user's existing Pixel AVD. +6. **16 KB page-size checks.** NDK r28 and AGP 8.13.2 are used; ELF LOAD + alignment is `2**14` and `zipalign -P 16` passes. An unused DataStore bundle + and its `libdatastore_shared_counter.so` were removed. Android 17 preview may + still report experimental RELRO compatibility warnings for dynamically + loaded CPU variants; verify again on stable Android 15/16 before publishing + to production. +7. **A 3.8 GB GGUF is easy to duplicate accidentally.** The test model was + pushed directly into app-specific external storage. +8. **Thinking mode makes short CPU tests take minutes.** Generation remains + asynchronous, but production UI should separate/hide thinking and expose a + configurable token limit. + +## Current limitations and next work + +- Text-only and CPU-only in the tested AVD. +- No resumable model downloader or in-app SHA-256 verification. +- Chat history is in-memory. +- Application context is currently 8,192 tokens. +- Thinking tags are displayed as normal text. +- 6 GB devices may be killed by Android LMK or run out of memory. +- Vision, Vulkan, compressed KV cache, and DSpark remain research tasks. + +Recommended next experiments: physical Snapdragon/Dimensity benchmarks, +first-token latency and thermal tests, Vulkan comparison, collapsible thinking +UI, WorkManager download/resume, vision `mmproj`, speculative decoding, and +per-ABI AAB delivery. + +## Licenses + +- Bonsai-27B GGUF: Apache-2.0 according to the upstream model card. +- PrismML fork / llama.cpp: see the upstream repository licenses. +- Preserve all applicable upstream `LICENSE` and `NOTICE` files when + redistributing the APK or model. diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md new file mode 100644 index 0000000000000000000000000000000000000000..8b6f5a2bba4dd5c221150ac550da6ce8a35b7b7d --- /dev/null +++ b/THIRD_PARTY.md @@ -0,0 +1,25 @@ +# Third-party components / Сторонние компоненты + +## English + +- The Android/JNI runtime is based on the `examples/llama.android` sample and + PrismML fork of `llama.cpp`, pinned to commit + `62061f91088281e65071cc38c5f69ee95c39f14e`. Preserve the upstream MIT license + when redistributing the native runtime. +- Bonsai-27B GGUF is not included in this repository. Obtain it from + and follow its Apache-2.0 + license/model-card conditions. +- AndroidX, Material Components, Kotlin, Gradle, NDK, and CMake retain their + respective upstream licenses. + +## Русский + +- Android/JNI runtime основан на примере `examples/llama.android` и форке + PrismML `llama.cpp`, закреплённом на commit + `62061f91088281e65071cc38c5f69ee95c39f14e`. При распространении native + runtime необходимо сохранить MIT-лицензию upstream. +- GGUF Bonsai-27B в этот репозиторий не включён. Он загружается из + и распространяется по + условиям Apache-2.0 и model card. +- AndroidX, Material Components, Kotlin, Gradle, NDK и CMake сохраняют свои + upstream-лицензии. diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3543521e9fef8e7322940a87c2b45dd0061b0f45 --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000000000000000000000000000000000000..f2952d75e0428419da05545793b0798c3783386d --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,66 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.jetbrains.kotlin.android) +} + +android { + namespace = "com.prismml.bonsailocal" + compileSdk = 36 + + defaultConfig { + applicationId = "com.prismml.bonsailocal" + + minSdk = 30 + targetSdk = 36 + + versionCode = 1 + versionName = "1.0" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + vectorDrawables { + useSupportLibrary = true + } + } + + buildTypes { + debug { + isMinifyEnabled = false + isShrinkResources = false + proguardFiles( + getDefaultProguardFile("proguard-android.txt"), + "proguard-rules.pro" + ) + } + release { + isMinifyEnabled = true + isShrinkResources = true + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } +} + +kotlin { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_17) + } +} + +dependencies { + implementation(libs.bundles.androidx) + implementation(libs.material) + + implementation(project(":lib")) + + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) + androidTestImplementation(libs.androidx.espresso.core) +} diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000000000000000000000000000000000000..c68150c41ce7512525e2dd8374fdc5c6c30dcf11 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,29 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile + +-keep class com.arm.aichat.* { *; } +-keep class com.arm.aichat.gguf.* { *; } + +-assumenosideeffects class android.util.Log { + public static int v(...); + public static int d(...); +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..6c8a1ddf682709bf8d6670e9dbf1d90bcd022e5b --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + diff --git a/app/src/main/java/com/example/llama/MainActivity.kt b/app/src/main/java/com/example/llama/MainActivity.kt new file mode 100644 index 0000000000000000000000000000000000000000..afcd242e74e1776391ab3668ddbfa5badafc9b17 --- /dev/null +++ b/app/src/main/java/com/example/llama/MainActivity.kt @@ -0,0 +1,329 @@ +package com.prismml.bonsailocal + +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.util.Log +import android.util.Base64 +import android.view.View +import android.view.inputmethod.EditorInfo +import android.widget.EditText +import android.widget.ProgressBar +import android.widget.TextView +import android.widget.Toast +import androidx.activity.addCallback +import androidx.activity.result.contract.ActivityResultContracts +import androidx.appcompat.app.AppCompatActivity +import androidx.lifecycle.lifecycleScope +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import com.arm.aichat.AiChat +import com.arm.aichat.InferenceEngine +import com.arm.aichat.gguf.GgufMetadata +import com.arm.aichat.gguf.GgufMetadataReader +import com.google.android.material.button.MaterialButton +import com.google.android.material.floatingactionbutton.FloatingActionButton +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.onCompletion +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.io.FileOutputStream +import java.io.InputStream +import java.util.UUID + +class MainActivity : AppCompatActivity() { + + private lateinit var statusTv: TextView + private lateinit var messagesRv: RecyclerView + private lateinit var userInputEt: EditText + private lateinit var userActionFab: FloatingActionButton + private lateinit var pickModelButton: MaterialButton + private lateinit var benchmarkButton: MaterialButton + private lateinit var progress: ProgressBar + + private lateinit var engine: InferenceEngine + private var generationJob: Job? = null + private var isModelReady = false + private var loadedModel: File? = null + private var pendingPrompt: String? = null + + private val messages = mutableListOf() + private val lastAssistantMsg = StringBuilder() + private val messageAdapter = MessageAdapter(messages) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + pendingPrompt = decodePrompt(intent) + onBackPressedDispatcher.addCallback { moveTaskToBack(true) } + + statusTv = findViewById(R.id.gguf) + messagesRv = findViewById(R.id.messages) + messagesRv.layoutManager = LinearLayoutManager(this).apply { stackFromEnd = true } + messagesRv.adapter = messageAdapter + userInputEt = findViewById(R.id.user_input) + userActionFab = findViewById(R.id.fab) + pickModelButton = findViewById(R.id.pick_model) + benchmarkButton = findViewById(R.id.benchmark) + progress = findViewById(R.id.progress) + + ensureModelsDirectory() + ensureExternalModelsDirectory() + + userActionFab.setOnClickListener { if (isModelReady) handleUserInput() } + pickModelButton.setOnClickListener { getContent.launch(arrayOf("*/*")) } + benchmarkButton.setOnClickListener { if (isModelReady) runBenchmark() } + userInputEt.setOnEditorActionListener { _, actionId, _ -> + if (actionId == EditorInfo.IME_ACTION_SEND && isModelReady) { + handleUserInput() + true + } else false + } + + lifecycleScope.launch(Dispatchers.Default) { + try { + engine = AiChat.getInferenceEngine(applicationContext) + val initialState = engine.state.first { + it is InferenceEngine.State.Initialized || it is InferenceEngine.State.Error + } + if (initialState is InferenceEngine.State.Error) throw initialState.exception + + val existing = discoverExistingModel() + if (existing != null) { + loadModel(existing.name, existing) + } else { + withContext(Dispatchers.Main) { + setBusy(false) + statusTv.text = "Движок готов. Выберите Bonsai-27B-Q1_0.gguf (3,80 ГБ)." + } + } + } catch (e: Exception) { + showError("Ошибка инициализации", e) + } + } + } + + private val getContent = registerForActivityResult( + ActivityResultContracts.OpenDocument() + ) { uri -> + Log.i(TAG, "Selected file uri: $uri") + uri?.let { handleSelectedModel(it) } + } + + private fun handleSelectedModel(uri: Uri) { + setBusy(true, "Проверяю GGUF…") + lifecycleScope.launch(Dispatchers.IO) { + try { + val metadata = contentResolver.openInputStream(uri)?.use { + GgufMetadataReader.create().readStructuredMetadata(it) + } ?: error("Не удалось открыть выбранный файл") + + val modelName = metadata.filename() + FILE_EXTENSION_GGUF + val modelFile = contentResolver.openInputStream(uri)?.use { input -> + ensureModelFile(modelName, input) + } ?: error("Не удалось скопировать модель") + loadModel(modelName, modelFile) + } catch (e: Exception) { + showError("Не удалось загрузить GGUF", e) + } + } + } + + private suspend fun ensureModelFile(modelName: String, input: InputStream) = + withContext(Dispatchers.IO) { + File(ensureModelsDirectory(), modelName).also { file -> + if (!file.exists() || file.length() == 0L) { + withContext(Dispatchers.Main) { + setBusy(true, "Копирую модель во внутреннее хранилище…") + } + FileOutputStream(file).use { output -> input.copyTo(output, 8 * 1024 * 1024) } + } + } + } + + private suspend fun loadModel(modelName: String, modelFile: File) { + withContext(Dispatchers.Main) { + setBusy(true, "Загружаю $modelName в память…") + } + engine.loadModel(modelFile.absolutePath) + engine.setSystemPrompt( + "You are Bonsai, a helpful on-device assistant. Answer clearly and use the user's language." + ) + loadedModel = modelFile + isModelReady = true + withContext(Dispatchers.Main) { + val gib = modelFile.length().toDouble() / (1024.0 * 1024.0 * 1024.0) + statusTv.text = "● Локально · $modelName · %.2f GiB · ${Build.SUPPORTED_ABIS.first()}".format(gib) + userInputEt.hint = "Сообщение для Bonsai…" + userInputEt.isEnabled = true + userActionFab.isEnabled = true + benchmarkButton.isEnabled = true + setBusy(false) + addAssistantMessage("Модель загружена на устройстве. Интернет для диалога не используется.") + pendingPrompt?.let { prompt -> + pendingPrompt = null + userInputEt.setText(prompt) + handleUserInput() + } + } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + decodePrompt(intent)?.let { prompt -> + if (isModelReady) { + userInputEt.setText(prompt) + handleUserInput() + } else { + pendingPrompt = prompt + } + } + } + + private fun decodePrompt(intent: Intent): String? = + intent.getStringExtra(EXTRA_PROMPT_BASE64)?.let { encoded -> + runCatching { + String(Base64.decode(encoded, Base64.NO_WRAP), Charsets.UTF_8) + }.getOrNull() + } + + private fun handleUserInput() { + val userMsg = userInputEt.text.toString().trim() + if (userMsg.isEmpty()) { + Toast.makeText(this, "Введите сообщение", Toast.LENGTH_SHORT).show() + return + } + + userInputEt.text = null + userInputEt.isEnabled = false + userActionFab.isEnabled = false + benchmarkButton.isEnabled = false + messages.add(Message(UUID.randomUUID().toString(), userMsg, true)) + lastAssistantMsg.clear() + messages.add(Message(UUID.randomUUID().toString(), "", false)) + messageAdapter.notifyItemRangeInserted(messages.size - 2, 2) + messagesRv.scrollToPosition(messages.size - 1) + + generationJob = lifecycleScope.launch(Dispatchers.Default) { + engine.sendUserPrompt(userMsg, predictLength = 512) + .onCompletion { + withContext(Dispatchers.Main) { + userInputEt.isEnabled = true + userActionFab.isEnabled = true + benchmarkButton.isEnabled = true + } + } + .collect { token -> + withContext(Dispatchers.Main) { + val last = messages.lastIndex + messages[last] = messages[last].copy( + content = lastAssistantMsg.append(token).toString() + ) + messageAdapter.notifyItemChanged(last) + messagesRv.scrollToPosition(last) + } + } + } + } + + private fun runBenchmark() { + setBusy(true, "Измеряю скорость на этом Android-устройстве…") + userInputEt.isEnabled = false + userActionFab.isEnabled = false + benchmarkButton.isEnabled = false + lifecycleScope.launch(Dispatchers.Default) { + try { + val result = engine.bench(pp = 64, tg = 32, pl = 1, nr = 1) + withContext(Dispatchers.Main) { + addAssistantMessage("Тест скорости (pp64 / tg32):\n\n$result") + } + } catch (e: Exception) { + showError("Тест скорости завершился с ошибкой", e) + } finally { + withContext(Dispatchers.Main) { + setBusy(false) + userInputEt.isEnabled = true + userActionFab.isEnabled = true + benchmarkButton.isEnabled = true + loadedModel?.let { statusTv.text = "● Локально · ${it.name} · готово" } + } + } + } + } + + private fun discoverExistingModel(): File? { + val candidates = buildList { + add(ensureModelsDirectory()) + add(ensureExternalModelsDirectory()) + } + return candidates.asSequence() + .flatMap { it.listFiles().orEmpty().asSequence() } + .filter { it.isFile && it.extension.equals("gguf", ignoreCase = true) } + .sortedByDescending { + if (it.name.contains("Bonsai-27B-Q1_0", ignoreCase = true)) 1 else 0 + } + .firstOrNull() + } + + private fun ensureModelsDirectory() = + File(filesDir, DIRECTORY_MODELS).also { if (!it.exists()) it.mkdirs() } + + private fun ensureExternalModelsDirectory() = + File(getExternalFilesDir(null) ?: filesDir, DIRECTORY_MODELS).also { + if (!it.exists()) it.mkdirs() + } + + private fun setBusy(busy: Boolean, message: String? = null) { + progress.visibility = if (busy) View.VISIBLE else View.INVISIBLE + pickModelButton.isEnabled = !busy + message?.let { statusTv.text = it } + } + + private fun addAssistantMessage(text: String) { + messages.add(Message(UUID.randomUUID().toString(), text, false)) + messageAdapter.notifyItemInserted(messages.lastIndex) + messagesRv.scrollToPosition(messages.lastIndex) + } + + private suspend fun showError(title: String, error: Throwable) { + Log.e(TAG, title, error) + withContext(Dispatchers.Main) { + isModelReady = false + setBusy(false) + statusTv.text = "$title: ${error.message ?: error.javaClass.simpleName}" + Toast.makeText(this@MainActivity, statusTv.text, Toast.LENGTH_LONG).show() + } + } + + override fun onStop() { + generationJob?.cancel() + super.onStop() + } + + override fun onDestroy() { + if (::engine.isInitialized) engine.destroy() + super.onDestroy() + } + + companion object { + private val TAG = MainActivity::class.java.simpleName + private const val DIRECTORY_MODELS = "models" + private const val FILE_EXTENSION_GGUF = ".gguf" + private const val EXTRA_PROMPT_BASE64 = "prompt_b64" + } +} + +fun GgufMetadata.filename() = when { + basic.name != null -> basic.name?.let { name -> + basic.sizeLabel?.let { size -> "$name-$size" } ?: name + } + architecture?.architecture != null -> architecture?.architecture?.let { arch -> + basic.uuid?.let { uuid -> "$arch-$uuid" } ?: "$arch-${System.currentTimeMillis()}" + } + else -> "model-${System.currentTimeMillis()}" +} diff --git a/app/src/main/java/com/example/llama/MessageAdapter.kt b/app/src/main/java/com/example/llama/MessageAdapter.kt new file mode 100644 index 0000000000000000000000000000000000000000..3d7166d3b0d1af22f3d598841c46b28dee6d3401 --- /dev/null +++ b/app/src/main/java/com/example/llama/MessageAdapter.kt @@ -0,0 +1,51 @@ +package com.prismml.bonsailocal + +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.recyclerview.widget.RecyclerView + +data class Message( + val id: String, + val content: String, + val isUser: Boolean +) + +class MessageAdapter( + private val messages: List +) : RecyclerView.Adapter() { + + companion object { + private const val VIEW_TYPE_USER = 1 + private const val VIEW_TYPE_ASSISTANT = 2 + } + + override fun getItemViewType(position: Int): Int { + return if (messages[position].isUser) VIEW_TYPE_USER else VIEW_TYPE_ASSISTANT + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + val layoutInflater = LayoutInflater.from(parent.context) + return if (viewType == VIEW_TYPE_USER) { + val view = layoutInflater.inflate(R.layout.item_message_user, parent, false) + UserMessageViewHolder(view) + } else { + val view = layoutInflater.inflate(R.layout.item_message_assistant, parent, false) + AssistantMessageViewHolder(view) + } + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val message = messages[position] + if (holder is UserMessageViewHolder || holder is AssistantMessageViewHolder) { + val textView = holder.itemView.findViewById(R.id.msg_content) + textView.text = message.content + } + } + + override fun getItemCount(): Int = messages.size + + class UserMessageViewHolder(view: View) : RecyclerView.ViewHolder(view) + class AssistantMessageViewHolder(view: View) : RecyclerView.ViewHolder(view) +} diff --git a/app/src/main/res/drawable-nodpi/bonsai_launcher.png b/app/src/main/res/drawable-nodpi/bonsai_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..5e4c447023a55a640722f78b593aa2372ec3edee --- /dev/null +++ b/app/src/main/res/drawable-nodpi/bonsai_launcher.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ff9392343b0d8f88f44282ebb5e726d8d76ab2c6b9c486c4c3a5204415f6e01b +size 1464965 diff --git a/app/src/main/res/drawable/bg_assistant_message.xml b/app/src/main/res/drawable/bg_assistant_message.xml new file mode 100644 index 0000000000000000000000000000000000000000..d591e1df47525a2f5e337882428f921878c3dfff --- /dev/null +++ b/app/src/main/res/drawable/bg_assistant_message.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/drawable/bg_user_message.xml b/app/src/main/res/drawable/bg_user_message.xml new file mode 100644 index 0000000000000000000000000000000000000000..a0d43cdbf6c88a9cc4c8622125d43bc9eef850bd --- /dev/null +++ b/app/src/main/res/drawable/bg_user_message.xml @@ -0,0 +1,4 @@ + + + + diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000000000000000000000000000000000000..4f3204ff7e34e599a4bee7ed7907d54725c5887e --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + + diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000000000000000000000000000000000000..e9d5d0a6a0a5f2b83fb1d482462a0b62999ff615 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,12 @@ + + + + + + diff --git a/app/src/main/res/drawable/outline_folder_open_24.xml b/app/src/main/res/drawable/outline_folder_open_24.xml new file mode 100644 index 0000000000000000000000000000000000000000..1ba07a05a76860c438a6a03d09878d6e5a417c5f --- /dev/null +++ b/app/src/main/res/drawable/outline_folder_open_24.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/outline_send_24.xml b/app/src/main/res/drawable/outline_send_24.xml new file mode 100644 index 0000000000000000000000000000000000000000..2d06ba751e07da6ea708d74765e8ff23f7b647f9 --- /dev/null +++ b/app/src/main/res/drawable/outline_send_24.xml @@ -0,0 +1,11 @@ + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000000000000000000000000000000000000..6c49377434d8d5949f67a3dad9b9788db690b079 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/item_message_assistant.xml b/app/src/main/res/layout/item_message_assistant.xml new file mode 100644 index 0000000000000000000000000000000000000000..518a6371ee83f2192fa93bac19997b5bc292ec0b --- /dev/null +++ b/app/src/main/res/layout/item_message_assistant.xml @@ -0,0 +1,19 @@ + + + + + diff --git a/app/src/main/res/layout/item_message_user.xml b/app/src/main/res/layout/item_message_user.xml new file mode 100644 index 0000000000000000000000000000000000000000..03b685cb8e7dfcd8927159441145c03238576bc2 --- /dev/null +++ b/app/src/main/res/layout/item_message_user.xml @@ -0,0 +1,18 @@ + + + + + diff --git a/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/app/src/main/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 0000000000000000000000000000000000000000..3314280a8998ee94a7cc0c724cf53d25ace19abb --- /dev/null +++ b/app/src/main/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml new file mode 100644 index 0000000000000000000000000000000000000000..3314280a8998ee94a7cc0c724cf53d25ace19abb --- /dev/null +++ b/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..841739e7b91774b9ef6f3c63ae6dfc0a2c7f5718 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000000000000000000000000000000000000..841739e7b91774b9ef6f3c63ae6dfc0a2c7f5718 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..c78b4e7ceebef4be6c2ac1d3d9580801efeb4437 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000000000000000000000000000000000000..c78b4e7ceebef4be6c2ac1d3d9580801efeb4437 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..af4510bb6554c29fb4cc1b45dd8ab2d58c611224 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000000000000000000000000000000000000..af4510bb6554c29fb4cc1b45dd8ab2d58c611224 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..12449ff0f928897ddab279de58f36698a6beff5e Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000000000000000000000000000000000000..12449ff0f928897ddab279de58f36698a6beff5e Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..a035c225290a1379363aa334b09149624ac4880f Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000000000000000000000000000000000000..a035c225290a1379363aa334b09149624ac4880f Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000000000000000000000000000000000000..0cdc781c60bf085c81ae666daf64e5580bd4fcbc --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,13 @@ + + + #071628 + #10243A + #19334E + #40D39C + #8AF5CF + #55E6EB + #F3FAF8 + #A9C1C6 + #FF000000 + #FFFFFFFF + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000000000000000000000000000000000000..047a6f716b0c777aa550eb45f498f4624f517456 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Bonsai Local + diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000000000000000000000000000000000000..4229b8ffe5b16eb8bbc915db9d4d750050978faf --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,15 @@ + + + + + + + + Gradle Configuration Cache + + + +
+ +
+ Loading... +
+ + + + + + diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000000000000000000000000000000000000..2bc8aeadb474b490a67f656968cae1616693e9fb --- /dev/null +++ b/gradle.properties @@ -0,0 +1,24 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official +# Enables namespacing of each library's R class so that its R class includes only the +# resources declared in the library itself and none from the library's dependencies, +# thereby reducing the size of the R class for that library +android.nonTransitiveRClass=true +android.native.buildOutput=verbose diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000000000000000000000000000000000000..46330000a6521a90a2602d6d8eac3587bdc7b59d --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,50 @@ +[versions] + +# Plugins +agp = "8.13.2" +kotlin = "2.3.0" + +# AndroidX +activity = "1.12.2" +appcompat = "1.7.1" +core-ktx = "1.17.0" +constraint-layout = "2.2.1" + +# Material +material = "1.13.0" + +# Testing +espresso-core = "3.7.0" +androidx-junit = "1.3.0" +junit = "4.13.2" + + +[plugins] +android-application = { id = "com.android.application", version.ref = "agp" } +android-library = { id = "com.android.library", version.ref = "agp" } +jetbrains-kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } + + +[libraries] + +# AndroidX +androidx-activity = { group = "androidx.activity", name = "activity", version.ref = "activity" } +androidx-appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" } +androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraint-layout" } +androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "core-ktx" } + +#Material +material = { group = "com.google.android.material", name = "material", version.ref = "material" } + +# Testing +androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espresso-core" } +androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "androidx-junit" } +junit = { group = "junit", name = "junit", version.ref = "junit" } + +[bundles] +androidx = [ + "androidx-activity", + "androidx-appcompat", + "androidx-constraintlayout", + "androidx-core-ktx", +] diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..e708b1c023ec8b20f512888fe07c5bd3ff77bb8f Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..533f43dd710a6924ba3de2e69d5d1611a1e0fa28 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue Apr 01 11:15:06 PDT 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000000000000000000000000000000000000..02640cba68b8881cb234133808bb8fa88db5856c --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/lib/.gitignore b/lib/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3543521e9fef8e7322940a87c2b45dd0061b0f45 --- /dev/null +++ b/lib/.gitignore @@ -0,0 +1 @@ +/build diff --git a/lib/build.gradle.kts b/lib/build.gradle.kts new file mode 100644 index 0000000000000000000000000000000000000000..6738f8f4edc7360d74d5c15b04efc6cac4d1d6e8 --- /dev/null +++ b/lib/build.gradle.kts @@ -0,0 +1,78 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmTarget + +plugins { + alias(libs.plugins.android.library) + alias(libs.plugins.jetbrains.kotlin.android) +} + +android { + namespace = "com.arm.aichat" + compileSdk = 36 + + ndkVersion = "28.2.13676358" + + defaultConfig { + minSdk = 30 + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + consumerProguardFiles("consumer-rules.pro") + + ndk { + abiFilters += listOf("arm64-v8a", "x86_64") + } + externalNativeBuild { + cmake { + arguments += "-DCMAKE_BUILD_TYPE=Release" + arguments += "-DCMAKE_MESSAGE_LOG_LEVEL=DEBUG" + arguments += "-DCMAKE_VERBOSE_MAKEFILE=ON" + + arguments += "-DBUILD_SHARED_LIBS=ON" + arguments += "-DLLAMA_BUILD_APP=OFF" + arguments += "-DLLAMA_BUILD_COMMON=ON" + arguments += "-DLLAMA_OPENSSL=OFF" + + arguments += "-DGGML_NATIVE=OFF" + arguments += "-DGGML_BACKEND_DL=ON" + arguments += "-DGGML_CPU_ALL_VARIANTS=ON" + arguments += "-DGGML_LLAMAFILE=OFF" + } + } + aarMetadata { + minCompileSdk = 35 + } + } + externalNativeBuild { + cmake { + path("src/main/cpp/CMakeLists.txt") + version = "3.22.1" + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + kotlin { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_17) + } + } + + packaging { + resources { + excludes += "/META-INF/{AL2.0,LGPL2.1}" + } + } + + publishing { + singleVariant("release") { + withJavadocJar() + } + } +} + +dependencies { + implementation(libs.androidx.core.ktx) + + testImplementation(libs.junit) + androidTestImplementation(libs.androidx.junit) +} diff --git a/lib/consumer-rules.pro b/lib/consumer-rules.pro new file mode 100644 index 0000000000000000000000000000000000000000..5867f6f65ede15107bb4012b3c6f9816d06ceedc --- /dev/null +++ b/lib/consumer-rules.pro @@ -0,0 +1,8 @@ +-keep class com.arm.aichat.* { *; } +-keep class com.arm.aichat.gguf.* { *; } + +-keepclasseswithmembernames class * { + native ; +} + +-keep class kotlin.Metadata { *; } diff --git a/lib/proguard-rules.pro b/lib/proguard-rules.pro new file mode 100644 index 0000000000000000000000000000000000000000..6e7ffa997ebe9c6370c559dda6ddfcd0d9d7f74c --- /dev/null +++ b/lib/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/lib/src/androidTest/java/android/llama/cpp/ExampleInstrumentedTest.kt b/lib/src/androidTest/java/android/llama/cpp/ExampleInstrumentedTest.kt new file mode 100644 index 0000000000000000000000000000000000000000..1675e82dcac31222370013c9f06a4dde9eaf7c11 --- /dev/null +++ b/lib/src/androidTest/java/android/llama/cpp/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package android.llama.cpp + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("android.llama.cpp.test", appContext.packageName) + } +} diff --git a/lib/src/main/AndroidManifest.xml b/lib/src/main/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..a2ae229b77ace65118e80b2c8e9bbbb06c280511 --- /dev/null +++ b/lib/src/main/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + + diff --git a/lib/src/main/cpp/CMakeLists.txt b/lib/src/main/cpp/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..0c6c7a2d78c5193fda684aa41fcf9e59efed7bc5 --- /dev/null +++ b/lib/src/main/cpp/CMakeLists.txt @@ -0,0 +1,56 @@ +cmake_minimum_required(VERSION 3.22.1) + +project("ai-chat" VERSION 1.0.0 LANGUAGES C CXX) + +set(CMAKE_C_STANDARD 11) +set(CMAKE_C_STANDARD_REQUIRED true) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED true) + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS}" CACHE STRING "" FORCE) +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}" CACHE STRING "" FORCE) + +# -------------------------------------------------------------------------- +# AI Chat library +# -------------------------------------------------------------------------- + +if(DEFINED ANDROID_ABI) + message(STATUS "Detected Android ABI: ${ANDROID_ABI}") + if(ANDROID_ABI STREQUAL "arm64-v8a") + set(GGML_SYSTEM_ARCH "ARM") + set(GGML_CPU_KLEIDIAI ON) + set(GGML_OPENMP ON) + elseif(ANDROID_ABI STREQUAL "x86_64") + set(GGML_SYSTEM_ARCH "x86") + set(GGML_CPU_KLEIDIAI OFF) + set(GGML_OPENMP OFF) + else() + message(FATAL_ERROR "Unsupported ABI: ${ANDROID_ABI}") + endif() +endif() + +set(LLAMA_SRC ${CMAKE_CURRENT_LIST_DIR}/../../../../../third_party/llama.cpp) +add_subdirectory(${LLAMA_SRC} build-llama) + +add_library(${CMAKE_PROJECT_NAME} SHARED + ai_chat.cpp) + +target_compile_definitions(${CMAKE_PROJECT_NAME} PRIVATE + GGML_SYSTEM_ARCH=${GGML_SYSTEM_ARCH} + GGML_CPU_KLEIDIAI=$ + GGML_OPENMP=$ +) + +target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE + ${LLAMA_SRC} + ${LLAMA_SRC}/common + ${LLAMA_SRC}/include + ${LLAMA_SRC}/ggml/include + ${LLAMA_SRC}/ggml/src) + +target_link_libraries(${CMAKE_PROJECT_NAME} + llama + llama-common + android + log) diff --git a/lib/src/main/cpp/ai_chat.cpp b/lib/src/main/cpp/ai_chat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6623eb25804622aa834bf48f2462c76d2a82d88f --- /dev/null +++ b/lib/src/main/cpp/ai_chat.cpp @@ -0,0 +1,565 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "logging.h" +#include "chat.h" +#include "common.h" +#include "llama.h" + +template +static std::string join(const std::vector &values, const std::string &delim) { + std::ostringstream str; + for (size_t i = 0; i < values.size(); i++) { + str << values[i]; + if (i < values.size() - 1) { str << delim; } + } + return str.str(); +} + +/** + * LLama resources: context, model, batch and sampler + */ +constexpr int N_THREADS_MIN = 2; +constexpr int N_THREADS_MAX = 4; +constexpr int N_THREADS_HEADROOM = 2; + +constexpr int DEFAULT_CONTEXT_SIZE = 8192; +constexpr int OVERFLOW_HEADROOM = 4; +constexpr int BATCH_SIZE = 512; +constexpr float DEFAULT_SAMPLER_TEMP = 0.3f; + +static llama_model * g_model; +static llama_context * g_context; +static llama_batch g_batch; +static common_chat_templates_ptr g_chat_templates; +static common_sampler * g_sampler; + +extern "C" +JNIEXPORT void JNICALL +Java_com_arm_aichat_internal_InferenceEngineImpl_init(JNIEnv *env, jobject /*unused*/, jstring nativeLibDir) { + // Set llama log handler to Android + llama_log_set(aichat_android_log_callback, nullptr); + + // Loading all CPU backend variants + const auto *path_to_backend = env->GetStringUTFChars(nativeLibDir, 0); + LOGi("Loading backends from %s", path_to_backend); + ggml_backend_load_all_from_path(path_to_backend); + env->ReleaseStringUTFChars(nativeLibDir, path_to_backend); + + // Initialize backends + llama_backend_init(); + LOGi("Backend initiated; Log handler set."); +} + +extern "C" +JNIEXPORT jint JNICALL +Java_com_arm_aichat_internal_InferenceEngineImpl_load(JNIEnv *env, jobject, jstring jmodel_path) { + llama_model_params model_params = llama_model_default_params(); + + const auto *model_path = env->GetStringUTFChars(jmodel_path, 0); + LOGd("%s: Loading model from: \n%s\n", __func__, model_path); + + auto *model = llama_model_load_from_file(model_path, model_params); + env->ReleaseStringUTFChars(jmodel_path, model_path); + if (!model) { + return 1; + } + g_model = model; + return 0; +} + +static llama_context *init_context(llama_model *model, const int n_ctx = DEFAULT_CONTEXT_SIZE) { + if (!model) { + LOGe("%s: model cannot be null", __func__); + return nullptr; + } + + // Multi-threading setup + const int n_threads = std::max(N_THREADS_MIN, std::min(N_THREADS_MAX, + (int) sysconf(_SC_NPROCESSORS_ONLN) - + N_THREADS_HEADROOM)); + LOGi("%s: Using %d threads", __func__, n_threads); + + // Context parameters setup + llama_context_params ctx_params = llama_context_default_params(); + const int trained_context_size = llama_model_n_ctx_train(model); + if (n_ctx > trained_context_size) { + LOGw("%s: Model was trained with only %d context size! Enforcing %d context size...", + __func__, trained_context_size, n_ctx); + } + ctx_params.n_ctx = n_ctx; + ctx_params.n_batch = BATCH_SIZE; + ctx_params.n_ubatch = BATCH_SIZE; + ctx_params.n_threads = n_threads; + ctx_params.n_threads_batch = n_threads; + auto *context = llama_init_from_model(g_model, ctx_params); + if (context == nullptr) { + LOGe("%s: llama_new_context_with_model() returned null)", __func__); + } + return context; +} + +static common_sampler *new_sampler(float temp) { + common_params_sampling sparams; + sparams.temp = temp; + return common_sampler_init(g_model, sparams); +} + +extern "C" +JNIEXPORT jint JNICALL +Java_com_arm_aichat_internal_InferenceEngineImpl_prepare(JNIEnv * /*env*/, jobject /*unused*/) { + auto *context = init_context(g_model); + if (!context) { return 1; } + g_context = context; + g_batch = llama_batch_init(BATCH_SIZE, 0, 1); + g_chat_templates = common_chat_templates_init(g_model, ""); + g_sampler = new_sampler(DEFAULT_SAMPLER_TEMP); + return 0; +} + +static std::string get_backend() { + std::vector backends; + for (size_t i = 0; i < ggml_backend_reg_count(); i++) { + auto *reg = ggml_backend_reg_get(i); + std::string name = ggml_backend_reg_name(reg); + if (name != "CPU") { + backends.push_back(ggml_backend_reg_name(reg)); + } + } + return backends.empty() ? "CPU" : join(backends, ","); +} + +extern "C" +JNIEXPORT jstring JNICALL +Java_com_arm_aichat_internal_InferenceEngineImpl_systemInfo(JNIEnv *env, jobject /*unused*/) { + return env->NewStringUTF(llama_print_system_info()); +} + +extern "C" +JNIEXPORT jstring JNICALL +Java_com_arm_aichat_internal_InferenceEngineImpl_benchModel(JNIEnv *env, jobject /*unused*/, jint pp, jint tg, + jint pl, jint nr) { + auto *context = init_context(g_model, pp); + if (!context) { + const auto *const err_msg = "Fail to init_context! Bench aborted."; + LOGe(err_msg); + return env->NewStringUTF(err_msg); + } + + auto pp_avg = 0.0; + auto tg_avg = 0.0; + auto pp_std = 0.0; + auto tg_std = 0.0; + + const uint32_t n_ctx = llama_n_ctx(context); + LOGi("n_ctx = %d", n_ctx); + + int i, j; + int nri; + for (nri = 0; nri < nr; nri++) { + LOGi("Benchmark prompt processing (pp = %d)", pp); + + common_batch_clear(g_batch); + + const int n_tokens = pp; + for (i = 0; i < n_tokens; i++) { + common_batch_add(g_batch, 0, i, {0}, false); + } + + g_batch.logits[g_batch.n_tokens - 1] = true; + llama_memory_clear(llama_get_memory(context), false); + + const auto t_pp_start = ggml_time_us(); + if (llama_decode(context, g_batch) != 0) { + LOGe("llama_decode() failed during prompt processing"); + } + const auto t_pp_end = ggml_time_us(); + + // bench text generation + + LOGi("Benchmark text generation (tg = %d)", tg); + + llama_memory_clear(llama_get_memory(context), false); + const auto t_tg_start = ggml_time_us(); + for (i = 0; i < tg; i++) { + common_batch_clear(g_batch); + for (j = 0; j < pl; j++) { + common_batch_add(g_batch, 0, i, {j}, true); + } + + if (llama_decode(context, g_batch) != 0) { + LOGe("llama_decode() failed during text generation"); + } + } + const auto t_tg_end = ggml_time_us(); + + llama_memory_clear(llama_get_memory(context), false); + + const auto t_pp = double(t_pp_end - t_pp_start) / 1000000.0; + const auto t_tg = double(t_tg_end - t_tg_start) / 1000000.0; + + const auto speed_pp = double(pp) / t_pp; + const auto speed_tg = double(pl * tg) / t_tg; + + pp_avg += speed_pp; + tg_avg += speed_tg; + + pp_std += speed_pp * speed_pp; + tg_std += speed_tg * speed_tg; + + LOGi("pp %f t/s, tg %f t/s", speed_pp, speed_tg); + } + + llama_free(context); + + pp_avg /= double(nr); + tg_avg /= double(nr); + + if (nr > 1) { + pp_std = sqrt(pp_std / double(nr - 1) - pp_avg * pp_avg * double(nr) / double(nr - 1)); + tg_std = sqrt(tg_std / double(nr - 1) - tg_avg * tg_avg * double(nr) / double(nr - 1)); + } else { + pp_std = 0; + tg_std = 0; + } + + char model_desc[128]; + llama_model_desc(g_model, model_desc, sizeof(model_desc)); + + const auto model_size = double(llama_model_size(g_model)) / 1024.0 / 1024.0 / 1024.0; + const auto model_n_params = double(llama_model_n_params(g_model)) / 1e9; + + const auto backend = get_backend(); + std::stringstream result; + result << std::setprecision(3); + result << "| model | size | params | backend | test | t/s |\n"; + result << "| --- | --- | --- | --- | --- | --- |\n"; + result << "| " << model_desc << " | " << model_size << "GiB | " << model_n_params << "B | " + << backend << " | pp " << pp << " | " << pp_avg << " ± " << pp_std << " |\n"; + result << "| " << model_desc << " | " << model_size << "GiB | " << model_n_params << "B | " + << backend << " | tg " << tg << " | " << tg_avg << " ± " << tg_std << " |\n"; + return env->NewStringUTF(result.str().c_str()); +} + + +/** + * Completion loop's long-term states: + * - chat management + * - position tracking + */ +constexpr const char *ROLE_SYSTEM = "system"; +constexpr const char *ROLE_USER = "user"; +constexpr const char *ROLE_ASSISTANT = "assistant"; + +static std::vector chat_msgs; +static llama_pos system_prompt_position; +static llama_pos current_position; + +static void reset_long_term_states(const bool clear_kv_cache = true) { + chat_msgs.clear(); + system_prompt_position = 0; + current_position = 0; + + if (clear_kv_cache) + llama_memory_clear(llama_get_memory(g_context), false); +} + +/** + * TODO-hyin: implement sliding-window version as a better alternative + * + * Context shifting by discarding the older half of the tokens appended after system prompt: + * - take the [system_prompt_position] first tokens from the original prompt + * - take half of the last (system_prompt_position - system_prompt_position) tokens + * - recompute the logits in batches + */ +static void shift_context() { + const int n_discard = (current_position - system_prompt_position) / 2; + LOGi("%s: Discarding %d tokens", __func__, n_discard); + llama_memory_seq_rm(llama_get_memory(g_context), 0, system_prompt_position, system_prompt_position + n_discard); + llama_memory_seq_add(llama_get_memory(g_context), 0, system_prompt_position + n_discard, current_position, -n_discard); + current_position -= n_discard; + LOGi("%s: Context shifting done! Current position: %d", __func__, current_position); +} + +static std::string chat_add_and_format(const std::string &role, const std::string &content) { + common_chat_msg new_msg; + new_msg.role = role; + new_msg.content = content; + auto formatted = common_chat_format_single( + g_chat_templates.get(), chat_msgs, new_msg, role == ROLE_USER, /* use_jinja */ false); + chat_msgs.push_back(new_msg); + LOGi("%s: Formatted and added %s message: \n%s\n", __func__, role.c_str(), formatted.c_str()); + return formatted; +} + +/** + * Completion loop's short-term states: + * - stop generation position + * - token chars caching + * - current assistant message being generated + */ +static llama_pos stop_generation_position; +static std::string cached_token_chars; +static std::ostringstream assistant_ss; + +static void reset_short_term_states() { + stop_generation_position = 0; + cached_token_chars.clear(); + assistant_ss.str(""); +} + +static int decode_tokens_in_batches( + llama_context *context, + llama_batch &batch, + const llama_tokens &tokens, + const llama_pos start_pos, + const bool compute_last_logit = false) { + // Process tokens in batches using the global batch + LOGd("%s: Decode %d tokens starting at position %d", __func__, (int) tokens.size(), start_pos); + for (int i = 0; i < (int) tokens.size(); i += BATCH_SIZE) { + const int cur_batch_size = std::min((int) tokens.size() - i, BATCH_SIZE); + common_batch_clear(batch); + LOGv("%s: Preparing a batch size of %d starting at: %d", __func__, cur_batch_size, i); + + // Shift context if current batch cannot fit into the context + if (start_pos + i + cur_batch_size >= DEFAULT_CONTEXT_SIZE - OVERFLOW_HEADROOM) { + LOGw("%s: Current batch won't fit into context! Shifting...", __func__); + shift_context(); + } + + // Add tokens to the batch with proper positions + for (int j = 0; j < cur_batch_size; j++) { + const llama_token token_id = tokens[i + j]; + const llama_pos position = start_pos + i + j; + const bool want_logit = compute_last_logit && (i + j == tokens.size() - 1); + common_batch_add(batch, token_id, position, {0}, want_logit); + } + + // Decode this batch + const int decode_result = llama_decode(context, batch); + if (decode_result) { + LOGe("%s: llama_decode failed w/ %d", __func__, decode_result); + return 1; + } + } + return 0; +} + +extern "C" +JNIEXPORT jint JNICALL +Java_com_arm_aichat_internal_InferenceEngineImpl_processSystemPrompt( + JNIEnv *env, + jobject /*unused*/, + jstring jsystem_prompt +) { + // Reset long-term & short-term states + reset_long_term_states(); + reset_short_term_states(); + + // Obtain system prompt from JEnv + const auto *system_prompt = env->GetStringUTFChars(jsystem_prompt, nullptr); + LOGd("%s: System prompt received: \n%s", __func__, system_prompt); + std::string formatted_system_prompt(system_prompt); + + // Format system prompt if applicable + const bool has_chat_template = common_chat_templates_was_explicit(g_chat_templates.get()); + if (has_chat_template) { + formatted_system_prompt = chat_add_and_format(ROLE_SYSTEM, system_prompt); + } + env->ReleaseStringUTFChars(jsystem_prompt, system_prompt); + + // Tokenize system prompt + const auto system_tokens = common_tokenize(g_context, formatted_system_prompt, + has_chat_template, has_chat_template); + for (auto id: system_tokens) { + LOGv("token: `%s`\t -> `%d`", common_token_to_piece(g_context, id).c_str(), id); + } + + // Handle context overflow + const int max_batch_size = DEFAULT_CONTEXT_SIZE - OVERFLOW_HEADROOM; + if ((int) system_tokens.size() > max_batch_size) { + LOGe("%s: System prompt too long for context! %d tokens, max: %d", + __func__, (int) system_tokens.size(), max_batch_size); + return 1; + } + + // Decode system tokens in batches + if (decode_tokens_in_batches(g_context, g_batch, system_tokens, current_position)) { + LOGe("%s: llama_decode() failed!", __func__); + return 2; + } + + // Update position + system_prompt_position = current_position = (int) system_tokens.size(); + return 0; +} + +extern "C" +JNIEXPORT jint JNICALL +Java_com_arm_aichat_internal_InferenceEngineImpl_processUserPrompt( + JNIEnv *env, + jobject /*unused*/, + jstring juser_prompt, + jint n_predict +) { + // Reset short-term states + reset_short_term_states(); + + // Obtain and tokenize user prompt + const auto *const user_prompt = env->GetStringUTFChars(juser_prompt, nullptr); + LOGd("%s: User prompt received: \n%s", __func__, user_prompt); + std::string formatted_user_prompt(user_prompt); + + // Format user prompt if applicable + const bool has_chat_template = common_chat_templates_was_explicit(g_chat_templates.get()); + if (has_chat_template) { + formatted_user_prompt = chat_add_and_format(ROLE_USER, user_prompt); + } + env->ReleaseStringUTFChars(juser_prompt, user_prompt); + + // Decode formatted user prompts + auto user_tokens = common_tokenize(g_context, formatted_user_prompt, has_chat_template, has_chat_template); + for (auto id: user_tokens) { + LOGv("token: `%s`\t -> `%d`", common_token_to_piece(g_context, id).c_str(), id); + } + + // Ensure user prompt doesn't exceed the context size by truncating if necessary. + const int user_prompt_size = (int) user_tokens.size(); + const int max_batch_size = DEFAULT_CONTEXT_SIZE - OVERFLOW_HEADROOM; + if (user_prompt_size > max_batch_size) { + const int skipped_tokens = user_prompt_size - max_batch_size; + user_tokens.resize(max_batch_size); + LOGw("%s: User prompt too long! Skipped %d tokens!", __func__, skipped_tokens); + } + + // Decode user tokens in batches + if (decode_tokens_in_batches(g_context, g_batch, user_tokens, current_position, true)) { + LOGe("%s: llama_decode() failed!", __func__); + return 2; + } + + // Update position + current_position += user_prompt_size; + stop_generation_position = current_position + user_prompt_size + n_predict; + return 0; +} + +static bool is_valid_utf8(const char *string) { + if (!string) { return true; } + + const auto *bytes = (const unsigned char *) string; + int num; + + while (*bytes != 0x00) { + if ((*bytes & 0x80) == 0x00) { + // U+0000 to U+007F + num = 1; + } else if ((*bytes & 0xE0) == 0xC0) { + // U+0080 to U+07FF + num = 2; + } else if ((*bytes & 0xF0) == 0xE0) { + // U+0800 to U+FFFF + num = 3; + } else if ((*bytes & 0xF8) == 0xF0) { + // U+10000 to U+10FFFF + num = 4; + } else { + return false; + } + + bytes += 1; + for (int i = 1; i < num; ++i) { + if ((*bytes & 0xC0) != 0x80) { + return false; + } + bytes += 1; + } + } + return true; +} + +extern "C" +JNIEXPORT jstring JNICALL +Java_com_arm_aichat_internal_InferenceEngineImpl_generateNextToken( + JNIEnv *env, + jobject /*unused*/ +) { + // Infinite text generation via context shifting + if (current_position >= DEFAULT_CONTEXT_SIZE - OVERFLOW_HEADROOM) { + LOGw("%s: Context full! Shifting...", __func__); + shift_context(); + } + + // Stop if reaching the marked position + if (current_position >= stop_generation_position) { + LOGw("%s: STOP: hitting stop position: %d", __func__, stop_generation_position); + return nullptr; + } + + // Sample next token + const auto new_token_id = common_sampler_sample(g_sampler, g_context, -1); + common_sampler_accept(g_sampler, new_token_id, true); + + // Populate the batch with new token, then decode + common_batch_clear(g_batch); + common_batch_add(g_batch, new_token_id, current_position, {0}, true); + if (llama_decode(g_context, g_batch) != 0) { + LOGe("%s: llama_decode() failed for generated token", __func__); + return nullptr; + } + + // Update position + current_position++; + + // Stop if next token is EOG + if (llama_vocab_is_eog(llama_model_get_vocab(g_model), new_token_id)) { + LOGd("id: %d,\tIS EOG!\nSTOP.", new_token_id); + chat_add_and_format(ROLE_ASSISTANT, assistant_ss.str()); + return nullptr; + } + + // If not EOG, convert to text + auto new_token_chars = common_token_to_piece(g_context, new_token_id); + cached_token_chars += new_token_chars; + + // Create and return a valid UTF-8 Java string + jstring result = nullptr; + if (is_valid_utf8(cached_token_chars.c_str())) { + result = env->NewStringUTF(cached_token_chars.c_str()); + LOGv("id: %d,\tcached: `%s`,\tnew: `%s`", new_token_id, cached_token_chars.c_str(), new_token_chars.c_str()); + + assistant_ss << cached_token_chars; + cached_token_chars.clear(); + } else { + LOGv("id: %d,\tappend to cache", new_token_id); + result = env->NewStringUTF(""); + } + return result; +} + + +extern "C" +JNIEXPORT void JNICALL +Java_com_arm_aichat_internal_InferenceEngineImpl_unload(JNIEnv * /*unused*/, jobject /*unused*/) { + // Reset long-term & short-term states + reset_long_term_states(); + reset_short_term_states(); + + // Free up resources + common_sampler_free(g_sampler); + g_chat_templates.reset(); + llama_batch_free(g_batch); + llama_free(g_context); + llama_model_free(g_model); +} + +extern "C" +JNIEXPORT void JNICALL +Java_com_arm_aichat_internal_InferenceEngineImpl_shutdown(JNIEnv *, jobject /*unused*/) { + llama_backend_free(); +} diff --git a/lib/src/main/cpp/logging.h b/lib/src/main/cpp/logging.h new file mode 100644 index 0000000000000000000000000000000000000000..4879c6785c75a30128abe0ea5fa9931040d69e1b --- /dev/null +++ b/lib/src/main/cpp/logging.h @@ -0,0 +1,62 @@ +// +// Created by Han Yin on 10/31/25. +// + +#ifndef AICHAT_LOGGING_H +#define AICHAT_LOGGING_H + +#endif //AICHAT_LOGGING_H + +#pragma once +#include + +#ifndef LOG_TAG +#define LOG_TAG "ai-chat" +#endif + +#ifndef LOG_MIN_LEVEL +#if defined(NDEBUG) +#define LOG_MIN_LEVEL ANDROID_LOG_INFO +#else +#define LOG_MIN_LEVEL ANDROID_LOG_VERBOSE +#endif +#endif + +static inline int ai_should_log(int prio) { + // Keep log filtering deterministic across emulator and physical devices. + return prio >= LOG_MIN_LEVEL; +} + +#if LOG_MIN_LEVEL <= ANDROID_LOG_VERBOSE +#define LOGv(...) do { if (ai_should_log(ANDROID_LOG_VERBOSE)) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__); } while (0) +#else +#define LOGv(...) ((void)0) +#endif + +#if LOG_MIN_LEVEL <= ANDROID_LOG_DEBUG +#define LOGd(...) do { if (ai_should_log(ANDROID_LOG_DEBUG)) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__); } while (0) +#else +#define LOGd(...) ((void)0) +#endif + +#define LOGi(...) do { if (ai_should_log(ANDROID_LOG_INFO )) __android_log_print(ANDROID_LOG_INFO , LOG_TAG, __VA_ARGS__); } while (0) +#define LOGw(...) do { if (ai_should_log(ANDROID_LOG_WARN )) __android_log_print(ANDROID_LOG_WARN , LOG_TAG, __VA_ARGS__); } while (0) +#define LOGe(...) do { if (ai_should_log(ANDROID_LOG_ERROR)) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__); } while (0) + +static inline int android_log_prio_from_ggml(enum ggml_log_level level) { + switch (level) { + case GGML_LOG_LEVEL_ERROR: return ANDROID_LOG_ERROR; + case GGML_LOG_LEVEL_WARN: return ANDROID_LOG_WARN; + case GGML_LOG_LEVEL_INFO: return ANDROID_LOG_INFO; + case GGML_LOG_LEVEL_DEBUG: return ANDROID_LOG_DEBUG; + default: return ANDROID_LOG_DEFAULT; + } +} + +static inline void aichat_android_log_callback(enum ggml_log_level level, + const char* text, + void* /*user*/) { + const int prio = android_log_prio_from_ggml(level); + if (!ai_should_log(prio)) return; + __android_log_write(prio, LOG_TAG, text); +} diff --git a/lib/src/main/java/com/arm/aichat/AiChat.kt b/lib/src/main/java/com/arm/aichat/AiChat.kt new file mode 100644 index 0000000000000000000000000000000000000000..9d709f7164d3ceb6a34d5d5cf8637f515a0e2967 --- /dev/null +++ b/lib/src/main/java/com/arm/aichat/AiChat.kt @@ -0,0 +1,14 @@ +package com.arm.aichat + +import android.content.Context +import com.arm.aichat.internal.InferenceEngineImpl + +/** + * Main entry point for Arm's AI Chat library. + */ +object AiChat { + /** + * Get the inference engine single instance. + */ + fun getInferenceEngine(context: Context) = InferenceEngineImpl.getInstance(context) +} diff --git a/lib/src/main/java/com/arm/aichat/InferenceEngine.kt b/lib/src/main/java/com/arm/aichat/InferenceEngine.kt new file mode 100644 index 0000000000000000000000000000000000000000..c3b6813e3051f4ea029fe3133a4ddbb2060b8c71 --- /dev/null +++ b/lib/src/main/java/com/arm/aichat/InferenceEngine.kt @@ -0,0 +1,89 @@ +package com.arm.aichat + +import com.arm.aichat.InferenceEngine.State +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.StateFlow + +/** + * Interface defining the core LLM inference operations. + */ +interface InferenceEngine { + /** + * Current state of the inference engine + */ + val state: StateFlow + + /** + * Load a model from the given path. + * + * @throws UnsupportedArchitectureException if model architecture not supported + */ + suspend fun loadModel(pathToModel: String) + + /** + * Sends a system prompt to the loaded model + */ + suspend fun setSystemPrompt(systemPrompt: String) + + /** + * Sends a user prompt to the loaded model and returns a Flow of generated tokens. + */ + fun sendUserPrompt(message: String, predictLength: Int = DEFAULT_PREDICT_LENGTH): Flow + + /** + * Runs a benchmark with the specified parameters. + */ + suspend fun bench(pp: Int, tg: Int, pl: Int, nr: Int = 1): String + + /** + * Unloads the currently loaded model. + */ + fun cleanUp() + + /** + * Cleans up resources when the engine is no longer needed. + */ + fun destroy() + + /** + * States of the inference engine + */ + sealed class State { + object Uninitialized : State() + object Initializing : State() + object Initialized : State() + + object LoadingModel : State() + object UnloadingModel : State() + object ModelReady : State() + + object Benchmarking : State() + object ProcessingSystemPrompt : State() + object ProcessingUserPrompt : State() + + object Generating : State() + + data class Error(val exception: Exception) : State() + } + + companion object { + const val DEFAULT_PREDICT_LENGTH = 1024 + } +} + +val State.isUninterruptible + get() = this is State.Initializing || + this is State.LoadingModel || + this is State.UnloadingModel || + this is State.Benchmarking || + this is State.ProcessingSystemPrompt || + this is State.ProcessingUserPrompt + +val State.isModelLoaded: Boolean + get() = this is State.ModelReady || + this is State.Benchmarking || + this is State.ProcessingSystemPrompt || + this is State.ProcessingUserPrompt || + this is State.Generating + +class UnsupportedArchitectureException : Exception() diff --git a/lib/src/main/java/com/arm/aichat/gguf/FileType.kt b/lib/src/main/java/com/arm/aichat/gguf/FileType.kt new file mode 100644 index 0000000000000000000000000000000000000000..4222e2513b746d0c035815f559c1fdb1f152450c --- /dev/null +++ b/lib/src/main/java/com/arm/aichat/gguf/FileType.kt @@ -0,0 +1,61 @@ +package com.arm.aichat.gguf + +import kotlin.collections.get + + +/** + * Numerical codes used by `general.file_type` (see llama.cpp repo's `constants.py`). + * The `label` matches what llama‑cli prints. + */ +enum class FileType(val code: Int, val label: String) { + ALL_F32(0, "all F32"), + MOSTLY_F16(1, "F16"), + MOSTLY_Q4_0(2, "Q4_0"), + MOSTLY_Q4_1(3, "Q4_1"), + // 4 removed + MOSTLY_Q8_0(7, "Q8_0"), + MOSTLY_Q5_0(8, "Q5_0"), + MOSTLY_Q5_1(9, "Q5_1"), + + /* K‑quants ------------------------------------------------------------ */ + MOSTLY_Q2_K (10, "Q2_K - Medium"), + MOSTLY_Q3_K_S (11, "Q3_K - Small"), + MOSTLY_Q3_K_M (12, "Q3_K - Medium"), + MOSTLY_Q3_K_L (13, "Q3_K - Large"), + MOSTLY_Q4_K_S (14, "Q4_K - Small"), + MOSTLY_Q4_K_M (15, "Q4_K - Medium"), + MOSTLY_Q5_K_S (16, "Q5_K - Small"), + MOSTLY_Q5_K_M (17, "Q5_K - Medium"), + MOSTLY_Q6_K (18, "Q6_K"), + + /* IQ quants ----------------------------------------------------------- */ + MOSTLY_IQ2_XXS (19, "IQ2_XXS - 2.06 bpw"), + MOSTLY_IQ2_XS (20, "IQ2_XS - 2.31 bpw"), + MOSTLY_Q2_K_S (21, "Q2_K - Small"), + MOSTLY_IQ3_XS (22, "IQ3_XS - 3.30 bpw"), + MOSTLY_IQ3_XXS (23, "IQ3_XXS - 3.06 bpw"), + MOSTLY_IQ1_S (24, "IQ1_S - 1.56 bpw"), + MOSTLY_IQ4_NL (25, "IQ4_NL - 4.5 bpw"), + MOSTLY_IQ3_S (26, "IQ3_S - 3.44 bpw"), + MOSTLY_IQ3_M (27, "IQ3_M - 3.66 bpw"), + MOSTLY_IQ2_S (28, "IQ2_S - 2.50 bpw"), + MOSTLY_IQ2_M (29, "IQ2_M - 2.70 bpw"), + MOSTLY_IQ4_XS (30, "IQ4_XS - 4.25 bpw"), + MOSTLY_IQ1_M (31, "IQ1_M - 1.75 bpw"), + + /* BF16 & Ternary ------------------------------------------------------ */ + MOSTLY_BF16 (32, "BF16"), + MOSTLY_TQ1_0 (36, "TQ1_0 - 1.69 bpw ternary"), + MOSTLY_TQ2_0 (37, "TQ2_0 - 2.06 bpw ternary"), + + /* Special flag -------------------------------------------------------- */ + GUESSED(1024, "(guessed)"), + + UNKNOWN(-1, "unknown"); + + companion object { + private val map = entries.associateBy(FileType::code) + + fun fromCode(code: Int?): FileType = map[code] ?: UNKNOWN + } +} diff --git a/lib/src/main/java/com/arm/aichat/gguf/GgufMetadata.kt b/lib/src/main/java/com/arm/aichat/gguf/GgufMetadata.kt new file mode 100644 index 0000000000000000000000000000000000000000..ecb9bfc9e0db697f9ddeff2e70c78831258cdf31 --- /dev/null +++ b/lib/src/main/java/com/arm/aichat/gguf/GgufMetadata.kt @@ -0,0 +1,132 @@ +package com.arm.aichat.gguf + +import java.io.IOException + + +/** + * Structured metadata of GGUF + */ +data class GgufMetadata( + // Basic file info + val version: GgufVersion, + val tensorCount: Long, + val kvCount: Long, + + // General info + val basic: BasicInfo, + val author: AuthorInfo? = null, + val additional: AdditionalInfo? = null, + val architecture: ArchitectureInfo? = null, + val baseModels: List? = null, + val tokenizer: TokenizerInfo? = null, + + // Derivative info + val dimensions: DimensionsInfo? = null, + val attention: AttentionInfo? = null, + val rope: RopeInfo? = null, + val experts: ExpertsInfo? = null +) { + enum class GgufVersion(val code: Int, val label: String) { + /** First public draft; little‑endian only, no alignment key. */ + LEGACY_V1(1, "Legacy v1"), + + /** Added split‑file support and some extra metadata keys. */ + EXTENDED_V2(2, "Extended v2"), + + /** Current spec: endian‑aware, mandatory alignment, fully validated. */ + VALIDATED_V3(3, "Validated v3"); + + companion object { + fun fromCode(code: Int): GgufVersion = + entries.firstOrNull { it.code == code } + ?: throw IOException("Unknown GGUF version code $code") + } + + override fun toString(): String = "$label (code=$code)" + } + + data class BasicInfo( + val uuid: String? = null, + val name: String? = null, + val nameLabel: String? = null, + val sizeLabel: String? = null, // Size label like "7B" + ) + + data class AuthorInfo( + val organization: String? = null, + val author: String? = null, + val doi: String? = null, + val url: String? = null, + val repoUrl: String? = null, + val license: String? = null, + val licenseLink: String? = null, + ) + + data class AdditionalInfo( + val type: String? = null, + val description: String? = null, + val tags: List? = null, + val languages: List? = null, + ) + + data class ArchitectureInfo( + val architecture: String? = null, + val fileType: Int? = null, + val vocabSize: Int? = null, + val finetune: String? = null, + val quantizationVersion: Int? = null, + ) + + data class BaseModelInfo( + val name: String? = null, + val author: String? = null, + val version: String? = null, + val organization: String? = null, + val url: String? = null, + val doi: String? = null, + val uuid: String? = null, + val repoUrl: String? = null, + ) + + data class TokenizerInfo( + val model: String? = null, + val bosTokenId: Int? = null, + val eosTokenId: Int? = null, + val unknownTokenId: Int? = null, + val paddingTokenId: Int? = null, + val addBosToken: Boolean? = null, + val addEosToken: Boolean? = null, + val chatTemplate: String? = null, + ) + + data class DimensionsInfo( + val contextLength: Int? = null, + val embeddingSize: Int? = null, + val blockCount: Int? = null, + val feedForwardSize: Int? = null, + ) + + data class AttentionInfo( + val headCount: Int? = null, + val headCountKv: Int? = null, + val keyLength: Int? = null, + val valueLength: Int? = null, + val layerNormEpsilon: Float? = null, + val layerNormRmsEpsilon: Float? = null, + ) + + data class RopeInfo( + val frequencyBase: Float? = null, + val dimensionCount: Int? = null, + val scalingType: String? = null, + val scalingFactor: Float? = null, + val attnFactor: Float? = null, + val originalContextLength: Int? = null, + val finetuned: Boolean? = null, + ) + + data class ExpertsInfo( + val count: Int? = null, + val usedCount: Int? = null, + ) +} diff --git a/lib/src/main/java/com/arm/aichat/gguf/GgufMetadataReader.kt b/lib/src/main/java/com/arm/aichat/gguf/GgufMetadataReader.kt new file mode 100644 index 0000000000000000000000000000000000000000..b933aa85b0335193c9b2322a8553a37b16a38d01 --- /dev/null +++ b/lib/src/main/java/com/arm/aichat/gguf/GgufMetadataReader.kt @@ -0,0 +1,77 @@ +package com.arm.aichat.gguf + +import android.content.Context +import android.net.Uri +import com.arm.aichat.internal.gguf.GgufMetadataReaderImpl +import java.io.File +import java.io.IOException +import java.io.InputStream + +/** + * Interface for reading GGUF metadata from model files. + * Use `GgufMetadataReader.create()` to get an instance. + */ +interface GgufMetadataReader { + /** + * Reads the magic number from the specified file path. + * + * @param file Java File to the GGUF file with absolute path + * @return true if file is valid GGUF, otherwise false + * @throws InvalidFileFormatException if file format is invalid + */ + suspend fun ensureSourceFileFormat(file: File): Boolean + + /** + * Reads the magic number from the specified file path. + * + * @param context Context for obtaining [android.content.ContentProvider] + * @param uri Uri to the GGUF file provided by [android.content.ContentProvider] + * @return true if file is valid GGUF, otherwise false + * @throws InvalidFileFormatException if file format is invalid + */ + suspend fun ensureSourceFileFormat(context: Context, uri: Uri): Boolean + + /** + * Reads and parses GGUF metadata from the specified file path. + * + * @param input the [InputStream] obtained from a readable file or content + * @return Structured metadata extracted from the file + * @throws IOException if file is damaged or cannot be read + * @throws InvalidFileFormatException if file format is invalid + */ + suspend fun readStructuredMetadata(input: InputStream): GgufMetadata + + companion object { + private val DEFAULT_SKIP_KEYS = setOf( + "tokenizer.chat_template", + "tokenizer.ggml.scores", + "tokenizer.ggml.tokens", + "tokenizer.ggml.token_type" + ) + + /** + * Creates a default GgufMetadataReader instance + */ + fun create(): GgufMetadataReader = GgufMetadataReaderImpl( + skipKeys = DEFAULT_SKIP_KEYS, + arraySummariseThreshold = 1_000 + ) + + /** + * Creates a GgufMetadataReader with custom configuration + * + * @param skipKeys Keys whose value should be skipped entirely (not kept in the result map) + * @param arraySummariseThreshold If ≥0, arrays longer get summarised, not materialised; + * If -1, never summarise. + */ + fun create( + skipKeys: Set = DEFAULT_SKIP_KEYS, + arraySummariseThreshold: Int = 1_000 + ): GgufMetadataReader = GgufMetadataReaderImpl( + skipKeys = skipKeys, + arraySummariseThreshold = arraySummariseThreshold + ) + } +} + +class InvalidFileFormatException : IOException() diff --git a/lib/src/main/java/com/arm/aichat/internal/InferenceEngineImpl.kt b/lib/src/main/java/com/arm/aichat/internal/InferenceEngineImpl.kt new file mode 100644 index 0000000000000000000000000000000000000000..cb63c26c2a629d2c775b8df5cf35557e51064242 --- /dev/null +++ b/lib/src/main/java/com/arm/aichat/internal/InferenceEngineImpl.kt @@ -0,0 +1,324 @@ +package com.arm.aichat.internal + +import android.content.Context +import android.util.Log +import com.arm.aichat.InferenceEngine +import com.arm.aichat.UnsupportedArchitectureException +import com.arm.aichat.internal.InferenceEngineImpl.Companion.getInstance +import dalvik.annotation.optimization.FastNative +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOn +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext +import java.io.File +import java.io.IOException + +/** + * JNI wrapper for the llama.cpp library providing Android-friendly access to large language models. + * + * This class implements a singleton pattern for managing the lifecycle of a single LLM instance. + * All operations are executed on a dedicated single-threaded dispatcher to ensure thread safety + * with the underlying C++ native code. + * + * The typical usage flow is: + * 1. Get instance via [getInstance] + * 2. Load a model with [loadModel] + * 3. Send prompts with [sendUserPrompt] + * 4. Generate responses as token streams + * 5. Perform [cleanUp] when done with a model + * 6. Properly [destroy] when completely done + * + * State transitions are managed automatically and validated at each operation. + * + * @see ai_chat.cpp for the native implementation details + */ +internal class InferenceEngineImpl private constructor( + private val nativeLibDir: String +) : InferenceEngine { + + companion object { + private val TAG = InferenceEngineImpl::class.java.simpleName + + @Volatile + private var instance: InferenceEngine? = null + + /** + * Create or obtain [InferenceEngineImpl]'s single instance. + * + * @param Context for obtaining native library directory + * @throws IllegalArgumentException if native library path is invalid + * @throws UnsatisfiedLinkError if library failed to load + */ + internal fun getInstance(context: Context) = + instance ?: synchronized(this) { + val nativeLibDir = context.applicationInfo.nativeLibraryDir + require(nativeLibDir.isNotBlank()) { "Expected a valid native library path!" } + + try { + Log.i(TAG, "Instantiating InferenceEngineImpl,,,") + InferenceEngineImpl(nativeLibDir).also { instance = it } + } catch (e: UnsatisfiedLinkError) { + Log.e(TAG, "Failed to load native library from $nativeLibDir", e) + throw e + } + } + } + + /** + * JNI methods + * @see ai_chat.cpp + */ + @FastNative + private external fun init(nativeLibDir: String) + + @FastNative + private external fun load(modelPath: String): Int + + @FastNative + private external fun prepare(): Int + + @FastNative + private external fun systemInfo(): String + + @FastNative + private external fun benchModel(pp: Int, tg: Int, pl: Int, nr: Int): String + + @FastNative + private external fun processSystemPrompt(systemPrompt: String): Int + + @FastNative + private external fun processUserPrompt(userPrompt: String, predictLength: Int): Int + + @FastNative + private external fun generateNextToken(): String? + + @FastNative + private external fun unload() + + @FastNative + private external fun shutdown() + + private val _state = + MutableStateFlow(InferenceEngine.State.Uninitialized) + override val state: StateFlow = _state.asStateFlow() + + private var _readyForSystemPrompt = false + @Volatile + private var _cancelGeneration = false + + /** + * Single-threaded coroutine dispatcher & scope for LLama asynchronous operations + */ + @OptIn(ExperimentalCoroutinesApi::class) + private val llamaDispatcher = Dispatchers.IO.limitedParallelism(1) + private val llamaScope = CoroutineScope(llamaDispatcher + SupervisorJob()) + + init { + llamaScope.launch { + try { + check(_state.value is InferenceEngine.State.Uninitialized) { + "Cannot load native library in ${_state.value.javaClass.simpleName}!" + } + _state.value = InferenceEngine.State.Initializing + Log.i(TAG, "Loading native library...") + System.loadLibrary("ai-chat") + init(nativeLibDir) + _state.value = InferenceEngine.State.Initialized + Log.i(TAG, "Native library loaded! System info: \n${systemInfo()}") + + } catch (e: Exception) { + Log.e(TAG, "Failed to load native library", e) + throw e + } + } + } + + /** + * Load the LLM + */ + override suspend fun loadModel(pathToModel: String) = + withContext(llamaDispatcher) { + check(_state.value is InferenceEngine.State.Initialized) { + "Cannot load model in ${_state.value.javaClass.simpleName}!" + } + + try { + Log.i(TAG, "Checking access to model file... \n$pathToModel") + File(pathToModel).let { + require(it.exists()) { "File not found" } + require(it.isFile) { "Not a valid file" } + require(it.canRead()) { "Cannot read file" } + } + + Log.i(TAG, "Loading model... \n$pathToModel") + _readyForSystemPrompt = false + _state.value = InferenceEngine.State.LoadingModel + load(pathToModel).let { + // TODO-han.yin: find a better way to pass other error codes + if (it != 0) throw UnsupportedArchitectureException() + } + prepare().let { + if (it != 0) throw IOException("Failed to prepare resources") + } + Log.i(TAG, "Model loaded!") + _readyForSystemPrompt = true + + _cancelGeneration = false + _state.value = InferenceEngine.State.ModelReady + } catch (e: Exception) { + Log.e(TAG, (e.message ?: "Error loading model") + "\n" + pathToModel, e) + _state.value = InferenceEngine.State.Error(e) + throw e + } + } + + /** + * Process the plain text system prompt + * + * TODO-han.yin: return error code if system prompt not correct processed? + */ + override suspend fun setSystemPrompt(prompt: String) = + withContext(llamaDispatcher) { + require(prompt.isNotBlank()) { "Cannot process empty system prompt!" } + check(_readyForSystemPrompt) { "System prompt must be set ** RIGHT AFTER ** model loaded!" } + check(_state.value is InferenceEngine.State.ModelReady) { + "Cannot process system prompt in ${_state.value.javaClass.simpleName}!" + } + + Log.i(TAG, "Sending system prompt...") + _readyForSystemPrompt = false + _state.value = InferenceEngine.State.ProcessingSystemPrompt + processSystemPrompt(prompt).let { result -> + if (result != 0) { + RuntimeException("Failed to process system prompt: $result").also { + _state.value = InferenceEngine.State.Error(it) + throw it + } + } + } + Log.i(TAG, "System prompt processed! Awaiting user prompt...") + _state.value = InferenceEngine.State.ModelReady + } + + /** + * Send plain text user prompt to LLM, which starts generating tokens in a [Flow] + */ + override fun sendUserPrompt( + message: String, + predictLength: Int, + ): Flow = flow { + require(message.isNotEmpty()) { "User prompt discarded due to being empty!" } + check(_state.value is InferenceEngine.State.ModelReady) { + "User prompt discarded due to: ${_state.value.javaClass.simpleName}" + } + + try { + Log.i(TAG, "Sending user prompt...") + _readyForSystemPrompt = false + _state.value = InferenceEngine.State.ProcessingUserPrompt + + processUserPrompt(message, predictLength).let { result -> + if (result != 0) { + Log.e(TAG, "Failed to process user prompt: $result") + return@flow + } + } + + Log.i(TAG, "User prompt processed. Generating assistant prompt...") + _state.value = InferenceEngine.State.Generating + while (!_cancelGeneration) { + generateNextToken()?.let { utf8token -> + if (utf8token.isNotEmpty()) emit(utf8token) + } ?: break + } + if (_cancelGeneration) { + Log.i(TAG, "Assistant generation aborted per requested.") + } else { + Log.i(TAG, "Assistant generation complete. Awaiting user prompt...") + } + _state.value = InferenceEngine.State.ModelReady + } catch (e: CancellationException) { + Log.i(TAG, "Assistant generation's flow collection cancelled.") + _state.value = InferenceEngine.State.ModelReady + throw e + } catch (e: Exception) { + Log.e(TAG, "Error during generation!", e) + _state.value = InferenceEngine.State.Error(e) + throw e + } + }.flowOn(llamaDispatcher) + + /** + * Benchmark the model + */ + override suspend fun bench(pp: Int, tg: Int, pl: Int, nr: Int): String = + withContext(llamaDispatcher) { + check(_state.value is InferenceEngine.State.ModelReady) { + "Benchmark request discarded due to: $state" + } + Log.i(TAG, "Start benchmark (pp: $pp, tg: $tg, pl: $pl, nr: $nr)") + _readyForSystemPrompt = false // Just to be safe + _state.value = InferenceEngine.State.Benchmarking + benchModel(pp, tg, pl, nr).also { + _state.value = InferenceEngine.State.ModelReady + } + } + + /** + * Unloads the model and frees resources, or reset error states + */ + override fun cleanUp() { + _cancelGeneration = true + runBlocking(llamaDispatcher) { + when (val state = _state.value) { + is InferenceEngine.State.ModelReady -> { + Log.i(TAG, "Unloading model and free resources...") + _readyForSystemPrompt = false + _state.value = InferenceEngine.State.UnloadingModel + + unload() + + _state.value = InferenceEngine.State.Initialized + Log.i(TAG, "Model unloaded!") + Unit + } + + is InferenceEngine.State.Error -> { + Log.i(TAG, "Resetting error states...") + _state.value = InferenceEngine.State.Initialized + Log.i(TAG, "States reset!") + Unit + } + + else -> throw IllegalStateException("Cannot unload model in ${state.javaClass.simpleName}") + } + } + } + + /** + * Cancel all ongoing coroutines and free GGML backends + */ + override fun destroy() { + _cancelGeneration = true + runBlocking(llamaDispatcher) { + _readyForSystemPrompt = false + when(_state.value) { + is InferenceEngine.State.Uninitialized -> {} + is InferenceEngine.State.Initialized -> shutdown() + else -> { unload(); shutdown() } + } + } + llamaScope.cancel() + } +} diff --git a/lib/src/main/java/com/arm/aichat/internal/gguf/GgufMetadataReaderImpl.kt b/lib/src/main/java/com/arm/aichat/internal/gguf/GgufMetadataReaderImpl.kt new file mode 100644 index 0000000000000000000000000000000000000000..60d1ebfe11cb75cadb5ac0729d926cfabae9177f --- /dev/null +++ b/lib/src/main/java/com/arm/aichat/internal/gguf/GgufMetadataReaderImpl.kt @@ -0,0 +1,590 @@ +package com.arm.aichat.internal.gguf + +import android.content.Context +import android.net.Uri +import com.arm.aichat.gguf.GgufMetadata +import com.arm.aichat.gguf.GgufMetadataReader +import com.arm.aichat.gguf.InvalidFileFormatException +import java.io.File +import java.io.IOException +import java.io.InputStream + + +/** + * Utility class to read GGUF model files and extract metadata key-value pairs. + * This parser reads the header and metadata of a GGUF v3 file (little-endian) and skips tensor data. + */ +internal class GgufMetadataReaderImpl( + private val skipKeys: Set, + private val arraySummariseThreshold: Int, +) : GgufMetadataReader { + companion object { + private const val ARCH_LLAMA = "llama" + } + + /** Enum corresponding to GGUF metadata value types (for convenience and array element typing). */ + enum class MetadataType(val code: Int) { + UINT8(0), INT8(1), UINT16(2), INT16(3), + UINT32(4), INT32(5), FLOAT32(6), BOOL(7), + STRING(8), ARRAY(9), UINT64(10), INT64(11), FLOAT64(12); + companion object { + private val codeMap = entries.associateBy(MetadataType::code) + fun fromCode(code: Int): MetadataType = codeMap[code] + ?: throw IOException("Unknown metadata value type code: $code") + } + } + + /** Sealed class hierarchy for metadata values, providing type-safe representations for each GGUF metadata type. */ + sealed class MetadataValue { + data class UInt8(val value: UByte) : MetadataValue() // 0: 8-bit unsigned int + data class Int8(val value: Byte) : MetadataValue() // 1: 8-bit signed int + data class UInt16(val value: UShort) : MetadataValue() // 2: 16-bit unsigned int (little-endian) + data class Int16(val value: Short) : MetadataValue() // 3: 16-bit signed int (little-endian) + data class UInt32(val value: UInt) : MetadataValue() // 4: 32-bit unsigned int (little-endian) + data class Int32(val value: Int) : MetadataValue() // 5: 32-bit signed int (little-endian) + data class Float32(val value: Float) : MetadataValue() // 6: 32-bit IEEE754 float + data class Bool(val value: Boolean) : MetadataValue() // 7: Boolean (1-byte, 0=false, 1=true) + data class StringVal(val value: String) : MetadataValue() // 8: UTF-8 string (length-prefixed) + data class ArrayVal(val elementType: MetadataType, val elements: List) : MetadataValue() + data class UInt64(val value: ULong) : MetadataValue() // 10: 64-bit unsigned int (little-endian) + data class Int64(val value: Long) : MetadataValue() // 11: 64-bit signed int (little-endian) + data class Float64(val value: Double) : MetadataValue() // 12: 64-bit IEEE754 double + } + + /* Convert MetadataValue to plain Kotlin primitives for allMetadata map */ + private fun MetadataValue.toPrimitive(): Any = when (this) { + is MetadataValue.UInt8 -> value + is MetadataValue.Int8 -> value + is MetadataValue.UInt16 -> value + is MetadataValue.Int16 -> value + is MetadataValue.UInt32 -> value + is MetadataValue.Int32 -> value + is MetadataValue.Float32 -> value + is MetadataValue.Bool -> value + is MetadataValue.StringVal -> value + is MetadataValue.UInt64 -> value + is MetadataValue.Int64 -> value + is MetadataValue.Float64 -> value + is MetadataValue.ArrayVal -> elements.map { it.toPrimitive() } + } + + /** + * Reads the magic number from the specified file path. + * + * @param context Context for obtaining ContentResolver + * @param uri Uri to the GGUF file provided by ContentProvider + * @return true if file is valid GGUF, otherwise false + */ + override suspend fun ensureSourceFileFormat(file: File): Boolean = + file.inputStream().buffered().use { ensureMagic(it) } + + /** + * Reads the magic number from the specified file path. + * + * @param context Context for obtaining ContentResolver + * @param uri Uri to the GGUF file provided by ContentProvider + * @return true if file is valid GGUF, otherwise false + */ + override suspend fun ensureSourceFileFormat(context: Context, uri: Uri): Boolean = + context.contentResolver.openInputStream(uri)?.buffered()?.use { ensureMagic(it) } == true + + /** Reads the 4‑byte magic; throws if magic ≠ "GGUF". */ + private fun ensureMagic(input: InputStream): Boolean = + ByteArray(4).let { + if (input.read(it) != 4) throw IOException("Not a valid file!") + it.contentEquals(byteArrayOf(0x47, 0x47, 0x55, 0x46)) // "GGUF" + } + + /** + * High‑level entry point: parses a `.gguf` file on disk and returns the fully + * populated [GgufMetadata] tree. + * + * Steps performed internally: + * 1. Reads and validates the 8‑byte header (`"GGUF"` magic + version). + * 2. Streams through the key‑value section, skipping large blobs if the key + * appears in [skipKeys] or if an array exceeds [arraySummariseThreshold]. + * 3. Converts the resulting raw map into strongly‑typed sub‑structures + * (basic info, tokenizer, rope, etc.). + * + * The method is STREAMING‑ONLY: tensors are never mapped or loaded into + * memory, so even multi‑GB model files can be processed in < 50 ms. + * + * @param path Absolute or relative filesystem path to a `.gguf` file. + * @return A [GgufMetadata] instance containing all recognised metadata plus + * an `allMetadata` map with any keys that were not given a dedicated + * field. + * @throws IOException if the file is not GGUF, the version is unsupported, + * or the metadata block is truncated / corrupt. + */ + override suspend fun readStructuredMetadata(input: InputStream): GgufMetadata { + // ── 1. header ────────────────────────────────────────────────────────── + // throws on mismatch + val version = ensureMagicAndVersion(input) + val tensorCount = readLittleLong(input) + val kvCount = readLittleLong(input) + + // ── 2. metadata map (reuse our raw parser, but we need access to the stream) ── + val meta = readMetaMap(input, kvCount) // + + // ── 3. build structured object ──────────────────────────────────────── + return buildStructured(meta, version, tensorCount, kvCount) + } + + /** Reads the 4‑byte magic + 4‑byte version; throws if magic ≠ "GGUF". */ + private fun ensureMagicAndVersion(input: InputStream): GgufMetadata.GgufVersion { + if (!ensureMagic(input)) throw InvalidFileFormatException() + return GgufMetadata.GgufVersion.fromCode(readLEUInt32(input)) + } + + /** + * Read an unsigned 32‑bit little‑endian integer. + * + * @throws IOException if fewer than four bytes are available. + */ + private fun readLEUInt32(input: InputStream): Int { + val b0 = input.read(); val b1 = input.read(); val b2 = input.read(); val b3 = input.read() + if (b3 == -1) throw IOException("Unexpected EOF while reading UInt32") + return (b3 and 0xFF shl 24) or + (b2 and 0xFF shl 16) or + (b1 and 0xFF shl 8) or + (b0 and 0xFF) + } + + /** + * Low‑level helper that reads the entire “key-value” section from the current + * stream position. + * + * @param input Open stream positioned JUST AFTER the header. + * @param kvCnt Number of key‑value pairs (taken from the header). + * @return Mutable map with one [MetadataValue] for every key that is NOT skipped. + * + * The function honours [skipKeys] and [arraySummariseThreshold] by invoking + * [skipValue] or [parseValue] accordingly. + */ + private fun readMetaMap(input: InputStream, kvCnt: Long): Map = + mutableMapOf().apply { + repeat(kvCnt.toInt()) { + val key = readString(input) + val valueT = MetadataType.fromCode(littleEndianBytesToInt(input.readNBytesExact(4))) + if (key in skipKeys) { + skipValue(input, valueT) + } else { + this[key] = parseValue(input, valueT) + } + } + } + + /** + * Converts a flat [Map]<[String], [MetadataValue]> into the strongly‑typed + * [GgufMetadata] tree used by the rest of the app. + * + * Only the keys listed in the spec are copied into dedicated data classes; + * everything else is preserved in `GgufMetadata.allMetadata`. + * + * @param m Raw key/value map. + * @param version GGUF file‑format version (enum). + * @param tensorCnt Number of tensors (from the header). + * @param kvCnt Total metadata pair count (from the header). + */ + private fun buildStructured( + m: Map, + version: GgufMetadata.GgufVersion, + tensorCnt: Long, + kvCnt: Long + ): GgufMetadata { + // ---------- helpers ---------- + fun String.str() = (m[this] as? MetadataValue.StringVal)?.value + fun String.bool() = (m[this] as? MetadataValue.Bool)?.value + fun String.i32() = (m[this] as? MetadataValue.Int32)?.value + fun String.u32() = (m[this] as? MetadataValue.UInt32)?.value?.toInt() + fun String.f32() = (m[this] as? MetadataValue.Float32)?.value + fun String.f64() = (m[this] as? MetadataValue.Float64)?.value?.toFloat() + fun String.strList(): List? = + (m[this] as? MetadataValue.ArrayVal) + ?.elements + ?.mapNotNull { (it as? MetadataValue.StringVal)?.value } + + val arch = "general.architecture".str() ?: ARCH_LLAMA + + // -------------- populate sections ---------------- + val basic = GgufMetadata.BasicInfo( + uuid = "general.uuid".str(), + name = "general.basename".str(), + nameLabel = "general.name".str(), + sizeLabel = "general.size_label".str() + ) + + val author = GgufMetadata.AuthorInfo( + organization = "general.organization".str(), + author = "general.author".str(), + doi = "general.doi".str(), + url = "general.url".str(), + repoUrl = "general.repo_url".str(), + license = "general.license".str(), + licenseLink = "general.license.link".str() + ).takeUnless { + organization == null && author == null && doi == null && + url == null && repoUrl == null && license == null && licenseLink == null + } + + val additional = GgufMetadata.AdditionalInfo( + type = "general.type".str(), + description = "general.description".str(), + tags = "general.tags".strList(), + languages = "general.languages".strList() + ).takeUnless { + type == null && description == null && tags == null && languages == null + } + + val architectureInfo = GgufMetadata.ArchitectureInfo( + architecture = arch, + fileType = "general.file_type".u32(), + vocabSize = "$arch.vocab_size".u32(), + finetune = "general.finetune".str(), + quantizationVersion = "general.quantization_version".u32() + ).takeUnless { fileType == null && vocabSize == null && finetune == null && quantizationVersion == null } + + val baseModels = buildList { + val n = "general.base_model.count".u32() ?: 0 + for (i in 0 until n) { + fun k(s: String) = "general.base_model.$i.$s" + add( + GgufMetadata.BaseModelInfo( + name = k("name").str(), + author = k("author").str(), + version = k("version").str(), + organization = k("organization").str(), + url = k("url").str(), + doi = k("doi").str(), + uuid = k("uuid").str(), + repoUrl = k("repo_url").str(), + ) + ) + } + }.takeIf { it.isNotEmpty() } + + val tokenizer = GgufMetadata.TokenizerInfo( + model = "tokenizer.ggml.model".str(), + bosTokenId = "tokenizer.ggml.bos_token_id".u32(), + eosTokenId = "tokenizer.ggml.eos_token_id".u32(), + unknownTokenId = "tokenizer.ggml.unknown_token_id".u32(), + paddingTokenId = "tokenizer.ggml.padding_token_id".u32(), + addBosToken = "tokenizer.ggml.add_bos_token".bool(), + addEosToken = "tokenizer.ggml.add_eos_token".bool(), + chatTemplate = "tokenizer.chat_template".str() + ).takeUnless { model == null && bosTokenId == null && eosTokenId == null && + unknownTokenId == null && paddingTokenId == null && + addBosToken == null && addEosToken == null && chatTemplate == null + } + + val dimensions = GgufMetadata.DimensionsInfo( + contextLength = "$arch.context_length".u32(), + embeddingSize = "$arch.embedding_length".u32(), + blockCount = "$arch.block_count".u32(), + feedForwardSize = "$arch.feed_forward_length".u32() + ).takeUnless { contextLength == null && embeddingSize == null && blockCount == null && feedForwardSize == null } + + val attention = GgufMetadata.AttentionInfo( + headCount = "$arch.attention.head_count".u32(), + headCountKv = "$arch.attention.head_count_kv".u32(), + keyLength = "$arch.attention.key_length".u32(), + valueLength = "$arch.attention.value_length".u32(), + layerNormEpsilon = "$arch.attention.layer_norm_epsilon".f32(), + layerNormRmsEpsilon = "$arch.attention.layer_norm_rms_epsilon".f32(), + ).takeUnless { headCount == null && headCountKv == null && keyLength == null && valueLength == null && + layerNormEpsilon == null && layerNormRmsEpsilon == null + } + + val rope = GgufMetadata.RopeInfo( + frequencyBase = "$arch.rope.freq_base".f32(), + dimensionCount = "$arch.rope.dimension_count".u32(), + scalingType = "$arch.rope.scaling.type".str(), + scalingFactor = "$arch.rope.scaling.factor".f32(), + attnFactor = "$arch.rope.scaling.attn_factor".f32(), + originalContextLength = "$arch.rope.scaling.original_context_length".u32(), + finetuned = "$arch.rope.scaling.finetuned".bool() + ).takeUnless { frequencyBase == null && dimensionCount == null && + scalingType == null && scalingFactor == null && attnFactor == null && + originalContextLength == null && finetuned == null + } + + val experts = GgufMetadata.ExpertsInfo( + count = "$arch.expert_count".u32(), + usedCount = "$arch.expert_used_count".u32() + ).takeUnless { count == null && usedCount == null } + + return GgufMetadata( + version = version, + tensorCount = tensorCnt, + kvCount = kvCnt, + basic = basic, + author = author, + additional = additional, + architecture = architectureInfo, + baseModels = baseModels, + tokenizer = tokenizer, + dimensions = dimensions, + attention = attention, + rope = rope, + experts = experts + ) + } + + /** + * Recursively parses a metadata value of the given type from the input stream. + * @param input The input stream positioned at the start of the value. + * @param type The metadata value type to parse. + */ + private fun parseValue(input: InputStream, type: MetadataType): MetadataValue = when (type) { + MetadataType.UINT8 -> { + // 1-byte unsigned integer + val byteVal = input.read() + if (byteVal == -1) throw IOException("Unexpected EOF while reading uint8 value.") + MetadataValue.UInt8(byteVal.toUByte()) + } + MetadataType.INT8 -> { + // 1-byte signed integer + val byteVal = input.read() + if (byteVal == -1) throw IOException("Unexpected EOF while reading int8 value.") + MetadataValue.Int8(byteVal.toByte()) + } + MetadataType.UINT16 -> { + // 2-byte unsigned integer (little-endian) + val bytes = ByteArray(2) + if (input.read(bytes) != 2) throw IOException("Unexpected EOF while reading uint16 value.") + // Combine two bytes (little-endian) into an unsigned 16-bit value + val u16 = ((bytes[1].toInt() and 0xFF) shl 8) or (bytes[0].toInt() and 0xFF) + MetadataValue.UInt16(u16.toUShort()) + } + MetadataType.INT16 -> { + // 2-byte signed integer (little-endian) + val bytes = ByteArray(2) + if (input.read(bytes) != 2) throw IOException("Unexpected EOF while reading int16 value.") + // Combine to 16-bit and interpret as signed + val i16 = ((bytes[1].toInt() and 0xFF) shl 8) or (bytes[0].toInt() and 0xFF) + MetadataValue.Int16(i16.toShort()) + } + MetadataType.UINT32 -> { + // 4-byte unsigned integer (little-endian) + val bytes = ByteArray(4) + if (input.read(bytes) != 4) throw IOException("Unexpected EOF while reading uint32 value.") + // Combine four bytes into a 32-bit value (as Long to avoid overflow), then convert to UInt + val u32 = (bytes[3].toLong() and 0xFFL shl 24) or + (bytes[2].toLong() and 0xFFL shl 16) or + (bytes[1].toLong() and 0xFFL shl 8) or + (bytes[0].toLong() and 0xFFL) + MetadataValue.UInt32(u32.toUInt()) + } + MetadataType.INT32 -> { + // 4-byte signed integer (little-endian) + val bytes = ByteArray(4) + if (input.read(bytes) != 4) throw IOException("Unexpected EOF while reading int32 value.") + // Combine four bytes into a 32-bit signed int + val i32 = (bytes[3].toInt() and 0xFF shl 24) or + (bytes[2].toInt() and 0xFF shl 16) or + (bytes[1].toInt() and 0xFF shl 8) or + (bytes[0].toInt() and 0xFF) + MetadataValue.Int32(i32) + } + MetadataType.FLOAT32 -> { + // 4-byte IEEE 754 float (little-endian) + val bytes = ByteArray(4) + if (input.read(bytes) != 4) throw IOException("Unexpected EOF while reading float32 value.") + // Assemble 4 bytes into a 32-bit int bit-pattern, then convert to Float + val bits = (bytes[3].toInt() and 0xFF shl 24) or + (bytes[2].toInt() and 0xFF shl 16) or + (bytes[1].toInt() and 0xFF shl 8) or + (bytes[0].toInt() and 0xFF) + val floatVal = Float.fromBits(bits) + MetadataValue.Float32(floatVal) + } + MetadataType.BOOL -> { + // 1-byte boolean (0 = false, 1 = true) + val byteVal = input.read() + if (byteVal == -1) throw IOException("Unexpected EOF while reading boolean value.") + if (byteVal != 0 && byteVal != 1) { + throw IOException("Invalid boolean value: $byteVal (must be 0 or 1).") + } + MetadataValue.Bool(byteVal != 0) + } + MetadataType.STRING -> { + // UTF-8 string (length-prefixed with 8-byte length) + val str = readString(input) + MetadataValue.StringVal(str) + } + MetadataType.ARRAY -> { + val elemType = MetadataType.fromCode(littleEndianBytesToInt(input.readNBytesExact(4))) + val len = readLittleLong(input) + val count = len.toInt() + + if (arraySummariseThreshold >= 0 && count > arraySummariseThreshold) { + // fast‑forward without allocation + repeat(count) { skipValue(input, elemType) } + MetadataValue.StringVal("Array($elemType, $count items) /* summarised */") + } else { + val list = ArrayList(count) + repeat(count) { list += parseValue(input, elemType) } + MetadataValue.ArrayVal(elemType, list) + } + } + MetadataType.UINT64 -> { + // 8-byte unsigned integer (little-endian) + val bytes = ByteArray(8) + if (input.read(bytes) != 8) throw IOException("Unexpected EOF while reading uint64 value.") + // Combine 8 bytes into an unsigned 64-bit (ULong). Use ULong for full 0 to 2^64-1 range. + val u64 = (bytes[7].toULong() and 0xFFuL shl 56) or + (bytes[6].toULong() and 0xFFuL shl 48) or + (bytes[5].toULong() and 0xFFuL shl 40) or + (bytes[4].toULong() and 0xFFuL shl 32) or + (bytes[3].toULong() and 0xFFuL shl 24) or + (bytes[2].toULong() and 0xFFuL shl 16) or + (bytes[1].toULong() and 0xFFuL shl 8) or + (bytes[0].toULong() and 0xFFuL) + MetadataValue.UInt64(u64) + } + MetadataType.INT64 -> { + // 8-byte signed integer (little-endian) + val bytes = ByteArray(8) + if (input.read(bytes) != 8) throw IOException("Unexpected EOF while reading int64 value.") + // Combine 8 bytes into a signed 64-bit value (Long) + val i64 = (bytes[7].toLong() and 0xFFL shl 56) or + (bytes[6].toLong() and 0xFFL shl 48) or + (bytes[5].toLong() and 0xFFL shl 40) or + (bytes[4].toLong() and 0xFFL shl 32) or + (bytes[3].toLong() and 0xFFL shl 24) or + (bytes[2].toLong() and 0xFFL shl 16) or + (bytes[1].toLong() and 0xFFL shl 8) or + (bytes[0].toLong() and 0xFFL) + MetadataValue.Int64(i64) + } + MetadataType.FLOAT64 -> { + // 8-byte IEEE 754 double (little-endian) + val bytes = ByteArray(8) + if (input.read(bytes) != 8) throw IOException("Unexpected EOF while reading float64 value.") + // Assemble 8 bytes into a 64-bit bit-pattern, then convert to Double + val bits = (bytes[7].toLong() and 0xFFL shl 56) or + (bytes[6].toLong() and 0xFFL shl 48) or + (bytes[5].toLong() and 0xFFL shl 40) or + (bytes[4].toLong() and 0xFFL shl 32) or + (bytes[3].toLong() and 0xFFL shl 24) or + (bytes[2].toLong() and 0xFFL shl 16) or + (bytes[1].toLong() and 0xFFL shl 8) or + (bytes[0].toLong() and 0xFFL) + val doubleVal = Double.fromBits(bits) + MetadataValue.Float64(doubleVal) + } + } + + + private fun T?.takeUnless(check: T.() -> Boolean): T? = + this?.takeIf { !it.check() } + + /** Helper: Skip a value in the stream without storing it (still maintains pointer). */ + private fun skipValue(input: InputStream, type: MetadataType) { + when (type) { + MetadataType.UINT8, MetadataType.INT8, MetadataType.BOOL -> input.skipFully(1) + MetadataType.UINT16, MetadataType.INT16 -> input.skipFully(2) + MetadataType.UINT32, MetadataType.INT32, MetadataType.FLOAT32 -> input.skipFully(4) + MetadataType.UINT64, MetadataType.INT64, MetadataType.FLOAT64 -> input.skipFully(8) + MetadataType.STRING -> { + val len = readLittleLong(input); input.skipFully(len) + } + MetadataType.ARRAY -> { + val elemType = MetadataType.fromCode(littleEndianBytesToInt(input.readNBytesExact(4))) + val len = readLittleLong(input) + repeat(len.toInt()) { skipValue(input, elemType) } // recursive skip + } + } + } + + /** Helper: Read an 8-byte little-endian unsigned value and return it as a signed Long (assuming it fits in 63 bits). */ + private fun readLittleLong(input: InputStream): Long { + val bytes = ByteArray(8) + input.readFully(bytes) + + // Combine 8 bytes into a 64-bit value (Little Endian). + // Note: If the value exceeds Long.MAX_VALUE (bit 63 is 1), this will produce a negative Long (two's complement). + // In our context (lengths/counts), such extremely large values are not expected. + return (bytes[7].toLong() and 0xFFL shl 56) or + (bytes[6].toLong() and 0xFFL shl 48) or + (bytes[5].toLong() and 0xFFL shl 40) or + (bytes[4].toLong() and 0xFFL shl 32) or + (bytes[3].toLong() and 0xFFL shl 24) or + (bytes[2].toLong() and 0xFFL shl 16) or + (bytes[1].toLong() and 0xFFL shl 8) or + (bytes[0].toLong() and 0xFFL) + } + + /** Helper: Read a GGUF string from the stream (8-byte length followed by UTF-8 bytes). */ + private fun readString(input: InputStream): String = + // Read 8-byte little-endian length (number of bytes in the string). + readLittleLong(input).let { len -> + if (len < 0 || len > Int.MAX_VALUE) throw IOException("String too long: $len") + + // Read the UTF-8 bytes of the given length. + ByteArray(len.toInt()).let { + if (it.isNotEmpty()) input.readFully(it) + String(it, Charsets.UTF_8) + } + } + + /** Helper: Convert a 4-byte little-endian byte array to a 32-bit integer. */ + private fun littleEndianBytesToInt(bytes: ByteArray): Int = + // Note: assumes bytes length is 4. + (bytes[3].toInt() and 0xFF shl 24) or + (bytes[2].toInt() and 0xFF shl 16) or + (bytes[1].toInt() and 0xFF shl 8) or + (bytes[0].toInt() and 0xFF) + + /** + * Robust skip that works the same on JDK 11 and Android’s desugared runtime. + * + * @param n Number of bytes to advance in the stream. + * @throws IOException on premature EOF. + */ + private fun InputStream.skipFully(n: Long) { + var remaining = n + val scratch = ByteArray(8192) // read‑and‑toss buffer + while (remaining > 0) { + val skipped = skip(remaining) + when { + skipped > 0 -> remaining -= skipped // normal fast path + skipped == 0L -> { + // fallback: read and discard + val read = read(scratch, 0, minOf(remaining, scratch.size.toLong()).toInt()) + if (read == -1) throw IOException("EOF while skipping $n bytes") + remaining -= read + } + else -> throw IOException("Skip returned negative value") + } + } + } + + /** + * Extension that keeps reading until the requested number of bytes are filled. + * Falls back to `read()` when `skip()` returns 0, which happens on some Android + * streams. + * + * @param buf Destination buffer. + * @param len Number of bytes to fill (defaults to `buf.size`). + * @throws IOException on premature EOF. + */ + private fun InputStream.readFully(buf: ByteArray, len: Int = buf.size) { + var off = 0 + while (off < len) { + val n = read(buf, off, len - off) + if (n == -1) throw IOException("EOF after $off of $len bytes") + off += n + } + } + + /** + * Read EXACTLY `n` bytes or throw – never returns a partially‑filled array. + * This is used for small fixed‑length reads (e.g. 4‑byte type codes). + * + * @throws IOException on premature EOF. + */ + private fun InputStream.readNBytesExact(n: Int) = ByteArray(n).also { + if (read(it) != n) throw IOException("Unexpected EOF") + } +} diff --git a/lib/src/test/java/android/llama/cpp/ExampleUnitTest.kt b/lib/src/test/java/android/llama/cpp/ExampleUnitTest.kt new file mode 100644 index 0000000000000000000000000000000000000000..0b873a6087763b87c1e1180eff0a171572679ba1 --- /dev/null +++ b/lib/src/test/java/android/llama/cpp/ExampleUnitTest.kt @@ -0,0 +1,17 @@ +package android.llama.cpp + +import org.junit.Test + +import org.junit.Assert.* + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +class ExampleUnitTest { + @Test + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } +} diff --git a/release/BonsaiLocal-debug.apk b/release/BonsaiLocal-debug.apk new file mode 100644 index 0000000000000000000000000000000000000000..91a78a73c8a5f27d21264a2caaf35f29be51fa0e --- /dev/null +++ b/release/BonsaiLocal-debug.apk @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bdaf2d9ee7ee1bbb2a424242678d75ac35f2b770973e3f4c9e58639ce8f93e5c +size 120762843 diff --git a/release/SHA256.txt b/release/SHA256.txt new file mode 100644 index 0000000000000000000000000000000000000000..822afb10d4cee08abe062b101515c751c1745a3b --- /dev/null +++ b/release/SHA256.txt @@ -0,0 +1 @@ +BDAF2D9EE7EE1BBB2A424242678D75AC35F2B770973E3F4C9E58639CE8F93E5C BonsaiLocal-debug.apk diff --git a/screenshots/01-start.png b/screenshots/01-start.png new file mode 100644 index 0000000000000000000000000000000000000000..26a0da5bbbe4b1f07f49c63e70fe186a1074dbe8 --- /dev/null +++ b/screenshots/01-start.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b9273794a4636f7009db491c64467f83747d86da7d53579fdf5ce3df1c0cd9d +size 370575 diff --git a/screenshots/02-model-loaded.png b/screenshots/02-model-loaded.png new file mode 100644 index 0000000000000000000000000000000000000000..25326182d95746c7cfc4e1a331a2b7099df70dda --- /dev/null +++ b/screenshots/02-model-loaded.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c39b1c969bf446199d07312627732be4aedd6c4be63ddafd8520fe20bab403ef +size 138079 diff --git a/screenshots/03-benchmark.png b/screenshots/03-benchmark.png new file mode 100644 index 0000000000000000000000000000000000000000..dfebb2cf14be814c08a6f3883f02ab24722802f7 --- /dev/null +++ b/screenshots/03-benchmark.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00f82af4441eee96e5c867365506a51db866e8b14a38ebf98e572ff952e06ba5 +size 194424 diff --git a/screenshots/04-reasoning.png b/screenshots/04-reasoning.png new file mode 100644 index 0000000000000000000000000000000000000000..14039d1e0cd0cb5c2123c6a1eafc20a169adc7c6 --- /dev/null +++ b/screenshots/04-reasoning.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fef9b731d338506c6ffcc0eced29e90f79707e3941994a76b8282eca64996650 +size 302534 diff --git a/screenshots/05-russian-kotlin.png b/screenshots/05-russian-kotlin.png new file mode 100644 index 0000000000000000000000000000000000000000..ce04929e849a0a641d2e1939ceefe43a0fdb093f --- /dev/null +++ b/screenshots/05-russian-kotlin.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0dc09edd8b158df605b9baae2e4b2a4b7e31a8f73c0e619d6cc888b64c3b398 +size 347529 diff --git a/screenshots/06-final-installed.png b/screenshots/06-final-installed.png new file mode 100644 index 0000000000000000000000000000000000000000..25326182d95746c7cfc4e1a331a2b7099df70dda --- /dev/null +++ b/screenshots/06-final-installed.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c39b1c969bf446199d07312627732be4aedd6c4be63ddafd8520fe20bab403ef +size 138079 diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000000000000000000000000000000000000..ce9ee3dff566622fb41c7f97d38f831163580544 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + mavenCentral() + google() + } +} + +rootProject.name = "BonsaiLocal" +include(":app") +include(":lib")