Instructions to use livadies/Bonsai-27B-Android-Local with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use livadies/Bonsai-27B-Android-Local with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf livadies/Bonsai-27B-Android-Local:Q1_0 # Run inference directly in the terminal: llama cli -hf livadies/Bonsai-27B-Android-Local:Q1_0
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf livadies/Bonsai-27B-Android-Local:Q1_0 # Run inference directly in the terminal: llama cli -hf livadies/Bonsai-27B-Android-Local:Q1_0
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf livadies/Bonsai-27B-Android-Local:Q1_0 # Run inference directly in the terminal: ./build/bin/llama cli -hf livadies/Bonsai-27B-Android-Local:Q1_0
Use Docker
docker model run hf.co/livadies/Bonsai-27B-Android-Local:Q1_0
- Llama new
- LM Studio
- Jan
- vLLM
How to use livadies/Bonsai-27B-Android-Local with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "livadies/Bonsai-27B-Android-Local" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "livadies/Bonsai-27B-Android-Local", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/livadies/Bonsai-27B-Android-Local:Q1_0
- Ollama
How to use livadies/Bonsai-27B-Android-Local with Ollama:
ollama run hf.co/livadies/Bonsai-27B-Android-Local:Q1_0
- Unsloth Desktop
- Pi
How to use livadies/Bonsai-27B-Android-Local with Pi:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf livadies/Bonsai-27B-Android-Local:Q1_0
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "llama-cpp": { "baseUrl": "http://localhost:9931/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "livadies/Bonsai-27B-Android-Local:Q1_0" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use livadies/Bonsai-27B-Android-Local with Docker Model Runner:
docker model run hf.co/livadies/Bonsai-27B-Android-Local:Q1_0
- Lemonade
How to use livadies/Bonsai-27B-Android-Local with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull livadies/Bonsai-27B-Android-Local:Q1_0
Run and chat with the model
lemonade run user.Bonsai-27B-Android-Local-Q1_0
List all available models
lemonade list
- Hermes Agent
How to use livadies/Bonsai-27B-Android-Local with Hermes Agent:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf livadies/Bonsai-27B-Android-Local:Q1_0
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:9931/v1 hermes config set model.default livadies/Bonsai-27B-Android-Local:Q1_0
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use livadies/Bonsai-27B-Android-Local with OpenClaw:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf livadies/Bonsai-27B-Android-Local:Q1_0
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:9931/v1 \ --custom-model-id "livadies/Bonsai-27B-Android-Local:Q1_0" \ --custom-provider-id llama-cpp \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
Publish Android source, APK, bilingual research notes, benchmarks, and screenshots / Публикация Android-проекта, APK, исследования и замеров
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+9
- .gitignoreAdded+8
- BENCHMARKS.mdAdded+58
- LICENSEAdded+21
- README.mdAdded+410
- README_EN.mdAdded+276
- THIRD_PARTY.mdAdded+25
- app/.gitignoreAdded+1
- app/build.gradle.ktsAdded+66
- app/proguard-rules.proAdded+29
- app/src/main/AndroidManifest.xmlAdded+30
- app/src/main/java/com/example/llama/MainActivity.ktAdded+329
- app/src/main/java/com/example/llama/MessageAdapter.ktAdded+51
- app/src/main/res/drawable-nodpi/bonsai_launcher.pngAdded
- app/src/main/res/drawable/bg_assistant_message.xmlAdded+5
- app/src/main/res/drawable/bg_user_message.xmlAdded+4
- app/src/main/res/drawable/ic_launcher_background.xmlAdded+4
- app/src/main/res/drawable/ic_launcher_foreground.xmlAdded+12
- app/src/main/res/drawable/outline_folder_open_24.xmlAdded+10
- app/src/main/res/drawable/outline_send_24.xmlAdded+11
- app/src/main/res/layout/activity_main.xmlAdded+174
- app/src/main/res/layout/item_message_assistant.xmlAdded+19
- app/src/main/res/layout/item_message_user.xmlAdded+18
- app/src/main/res/mipmap-anydpi/ic_launcher.xmlAdded+6
- app/src/main/res/mipmap-anydpi/ic_launcher_round.xmlAdded+6
- app/src/main/res/mipmap-hdpi/ic_launcher.pngAdded
- app/src/main/res/mipmap-hdpi/ic_launcher_round.pngAdded
- app/src/main/res/mipmap-mdpi/ic_launcher.pngAdded
- app/src/main/res/mipmap-mdpi/ic_launcher_round.pngAdded
- app/src/main/res/mipmap-xhdpi/ic_launcher.pngAdded
- app/src/main/res/mipmap-xhdpi/ic_launcher_round.pngAdded
- app/src/main/res/mipmap-xxhdpi/ic_launcher.pngAdded
- app/src/main/res/mipmap-xxhdpi/ic_launcher_round.pngAdded
- app/src/main/res/mipmap-xxxhdpi/ic_launcher.pngAdded
- app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.pngAdded
- app/src/main/res/values/colors.xmlAdded+13
- app/src/main/res/values/strings.xmlAdded+3
- app/src/main/res/values/themes.xmlAdded+15
- app/src/main/res/xml/backup_rules.xmlAdded+13
- app/src/main/res/xml/data_extraction_rules.xmlAdded+19
- bonsai-icon-source.pngAdded
- build.gradle.ktsAdded+6
- build/reports/problems/problems-report.htmlAdded
- gradle.propertiesAdded+24
- gradle/libs.versions.tomlAdded+50
- gradle/wrapper/gradle-wrapper.jarAdded
- gradle/wrapper/gradle-wrapper.propertiesAdded+6
- gradlewAdded+185
- lib/.gitignoreAdded+1
- lib/build.gradle.ktsAdded+78
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines33343536373839404142434432 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textapp/src/main/res/drawable-nodpi/bonsai_launcher.png filter=lfs diff=lfs merge=lfs -textbonsai-icon-source.png filter=lfs diff=lfs merge=lfs -textrelease/BonsaiLocal-debug.apk filter=lfs diff=lfs merge=lfs -textscreenshots/01-start.png filter=lfs diff=lfs merge=lfs -textscreenshots/02-model-loaded.png filter=lfs diff=lfs merge=lfs -textscreenshots/03-benchmark.png filter=lfs diff=lfs merge=lfs -textscreenshots/04-reasoning.png filter=lfs diff=lfs merge=lfs -textscreenshots/05-russian-kotlin.png filter=lfs diff=lfs merge=lfs -textscreenshots/06-final-installed.png filter=lfs diff=lfs merge=lfs -text
12345678/.gradle//.idea//**/build//**/.cxx//models//local.properties*.iml*.log12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758# Android benchmark results / Результаты Android-бенчмарка
[English](#english) · [Русский](#русский)
## English
These measurements were produced inside the `Bonsai_27B_Test` Android emulatorby 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, onegraph split, 149.62 MiB recurrent buffer, and 523.02 MiB CPU compute buffer.
The Russian/Kotlin prompt reached the configured 512-token generation limit inthinking mode. It demonstrated prompt comprehension but did not produce a cleanfinal answer, so it is marked as a failed instruction-following case.
## Русский
Эти замеры выполнены внутри Android-эмулятора `Bonsai_27B_Test` через JNIruntime из 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 DeltaNet для autoregressive и chunked путей, 3 703 узла графа, один split, recurrentbuffer 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)123456789101112131415161718192021MIT License
Copyright (c) 2026 livadies
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410---license: mitpipeline_tag: text-generationlanguage:- ru- entags:- 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-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.
## Архитектура
```mermaidflowchart 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<String>`.
Критический фрагмент JNI:
```cppllama_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корутинами.
```kotlinprivate 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% — fullattention.
Текущий 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 проверенной модели:
```text17EF842E47450CAEB8EAA3EBFBBAB5D2F2278B62B79BE107985FB69A2F819AA0```
Официальная карточка указывает около 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 появляется в:
```textapp/build/outputs/apk/debug/app-debug.apk```
Проверенный итоговый артефакт дополнительно скопирован в:
```textrelease/BonsaiLocal-debug.apk```
Его размер — 120 762 843 байта, SHA-256:
```textBDAF2D9EE7EE1BBB2A424242678D75AC35F2B770973E3F4C9E58639CE8F93E5C```
Первая сборка долгая: генерируются сотни C/C++ объектов и несколько CPUvariants для двух ABI. Инкрементальные сборки значительно быстрее.
### Привязка llama.cpp в CMake
Проект был вынесен из `examples/llama.android`, поэтому относительный путьисходников пришлось изменить:
```cmakeset(LLAMA_SRC ${CMAKE_CURRENT_LIST_DIR}/../../../../../third_party/llama.cpp)add_subdirectory(${LLAMA_SRC} build-llama)```
Для Android компилируются обе ABI:
```kotlinndk { abiFilters += listOf("arm64-v8a", "x86_64")}```
## Установка модели
### Обычный пользовательский путь
1. Скопировать `Bonsai-27B-Q1_0.gguf` на телефон.2. Открыть приложение.3. Нажать **Выбрать GGUF** и выбрать файл.4. Дождаться копирования и загрузки.
### Воспроизводимый путь для эмулятора
После первой установки APK:
```powershelladb -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. Это обход нестабильного Unicodeinput у 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 декодируется без сетевых вызовов:
```kotlinString(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 и GatedDelta Net paths.
### 3. JDK 17 toolchain отсутствовал
Gradle запускался на JBR 21, а исходный sample требовал установленный JDK 17через `jvmToolchain(17)`. Gradle не имел repository для автоматической загрузки.Решение: убрать принудительный поиск отдельного toolchain и явно компилироватьJava/Kotlin bytecode target 17:
```kotlinkotlin { compilerOptions { jvmTarget.set(JvmTarget.JVM_17) }}```
### 4. Android logging API
`__android_log_is_loggable()` доступен только с API 30, а ранняя конфигурацияиспользовала minSdk 28. Решение: локальный фильтр log level и итоговый minSdk30.
### 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. Проект использует NDKr28 и 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 делает даже короткие тесты долгими
Запрос с требованием вернуть одно число всё равно сгенерировал подробный`<think>` блок. Это ожидаемое поведение модели и полезная проверка 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. Отделить `<think>` в сворачиваемую 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-проектов.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276---license: mitpipeline_tag: text-generationlanguage:- en- rutags:- 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 iscopied to the device, chat inference does not use a PC server, cloud API, orinternet connection.

## 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 availablefrom the upstream model repository and would make application deliveryimpractical.
## 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 JNIruntime, 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 negativeresult: the model understood the requested language, signature, and validationconstraints, but spent the complete 512-token limit in visible reasoning anddid not reach a clean final code answer. This is recorded rather than presentedas 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 physicaldevice has different SIMD support, thermal limits, memory bandwidth, and powermanagement.
## Architecture
```mermaidflowchart 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<String>`.
Critical JNI setup:
```cppllama_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 areglobal native resources:
```kotlinprivate 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-attentionmodel, so there are no experts or routing network to enumerate. Roughly 75% ofits 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:
```textgpt/├── 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 copyis published as `release/BonsaiLocal-debug.apk`:
```textsize: 120762843 bytesSHA256: BDAF2D9EE7EE1BBB2A424242678D75AC35F2B770973E3F4C9E58639CE8F93E5C```
The native runtime is wired through:
```cmakeset(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:
```powershelladb shell mkdir -p ` /sdcard/Android/data/com.prismml.bonsailocal/files/modelsadb push .\models\Bonsai-27B-Q1_0.gguf ` /sdcard/Android/data/com.prismml.bonsailocal/files/models/```
Verified model checksum:
```text17EF842E47450CAEB8EAA3EBFBBAB5D2F2278B62B79BE107985FB69A2F819AA0```
## 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 thinkingUI, WorkManager download/resume, vision `mmproj`, speculative decoding, andper-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.12345678910111213141516171819202122232425# 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 <https://huggingface.co/prism-ml/Bonsai-27B-gguf> 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 в этот репозиторий не включён. Он загружается из <https://huggingface.co/prism-ml/Bonsai-27B-gguf> и распространяется по условиям Apache-2.0 и model card.- AndroidX, Material Components, Kotlin, Gradle, NDK и CMake сохраняют свои upstream-лицензии.1/build123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import 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)
}1234567891011121314151617181920212223242526272829# 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(...);
}123456789101112131415161718192021222324252627282930<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="false" android:dataExtractionRules="@xml/data_extraction_rules"
android:extractNativeLibs="true"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AiChatSample" android:largeHeap="true" android:usesCleartextTraffic="false" >
<activity android:name=".MainActivity" android:exported="true" android:launchMode="singleTop"> <intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329package com.prismml.bonsailocal
import android.content.Intentimport android.net.Uriimport android.os.Buildimport android.os.Bundleimport android.util.Logimport android.util.Base64import android.view.Viewimport android.view.inputmethod.EditorInfoimport android.widget.EditTextimport android.widget.ProgressBarimport android.widget.TextViewimport android.widget.Toastimport androidx.activity.addCallbackimport androidx.activity.result.contract.ActivityResultContractsimport androidx.appcompat.app.AppCompatActivityimport androidx.lifecycle.lifecycleScopeimport androidx.recyclerview.widget.LinearLayoutManagerimport androidx.recyclerview.widget.RecyclerViewimport com.arm.aichat.AiChatimport com.arm.aichat.InferenceEngineimport com.arm.aichat.gguf.GgufMetadataimport com.arm.aichat.gguf.GgufMetadataReaderimport com.google.android.material.button.MaterialButtonimport com.google.android.material.floatingactionbutton.FloatingActionButtonimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Jobimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.flow.onCompletionimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContextimport java.io.Fileimport java.io.FileOutputStreamimport java.io.InputStreamimport 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<Message>() 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()}"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051package 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<Message>
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
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<TextView>(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)
}12345<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/bonsai_surface_light" /> <stroke android:width="1dp" android:color="#31516A" /> <corners android:topLeftRadius="18dp" android:topRightRadius="18dp" android:bottomLeftRadius="5dp" android:bottomRightRadius="18dp" /></shape>1234<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="@color/bonsai_green" /> <corners android:topLeftRadius="18dp" android:topRightRadius="18dp" android:bottomLeftRadius="18dp" android:bottomRightRadius="5dp" /></shape>1234<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#061A36" /></shape>123456789101112<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:left="18dp" android:top="18dp" android:right="18dp" android:bottom="18dp"> <bitmap android:gravity="fill" android:src="@drawable/bonsai_launcher" /> </item></layer-list>12345678910<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal">
<path
android:fillColor="@android:color/white"
android:pathData="M20,6h-8l-2,-2L4,4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,8c0,-1.1 -0.9,-2 -2,-2zM20,18L4,18L4,8h16v10z"/>
</vector>1234567891011<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="?attr/colorControlNormal"
android:autoMirrored="true">
<path
android:fillColor="@android:color/white"
android:pathData="M4.01,6.03l7.51,3.22 -7.52,-1 0.01,-2.22m7.5,8.72L4,17.97v-2.22l7.51,-1M2.01,3L2,10l15,2 -15,2 0.01,7L23,12 2.01,3z"/>
</vector>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/bonsai_navy" android:fitsSystemWindows="true" android:orientation="vertical" tools:context=".MainActivity">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal" android:paddingStart="20dp" android:paddingTop="12dp" android:paddingEnd="20dp" android:paddingBottom="10dp">
<ImageView android:layout_width="52dp" android:layout_height="52dp" android:contentDescription="Bonsai Local" android:src="@drawable/bonsai_launcher" />
<LinearLayout android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="12dp" android:layout_weight="1" android:orientation="vertical">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Bonsai Local" android:textColor="@color/bonsai_text" android:textSize="22sp" android:textStyle="bold" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="27B · 1-bit · полностью на устройстве" android:textColor="@color/bonsai_text_muted" android:textSize="12sp" /> </LinearLayout>
<ProgressBar android:id="@+id/progress" style="?android:attr/progressBarStyleSmall" android:layout_width="28dp" android:layout_height="28dp" android:indeterminateTint="@color/bonsai_green" /> </LinearLayout>
<com.google.android.material.card.MaterialCardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginHorizontal="16dp" android:layout_marginBottom="10dp" app:cardBackgroundColor="@color/bonsai_surface" app:cardCornerRadius="18dp" app:strokeColor="#28445C" app:strokeWidth="1dp">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="14dp">
<TextView android:id="@+id/gguf" android:layout_width="match_parent" android:layout_height="wrap_content" android:maxLines="3" android:text="Инициализация локального движка…" android:textColor="@color/bonsai_text" android:textSize="13sp" />
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:gravity="end" android:orientation="horizontal">
<com.google.android.material.button.MaterialButton android:id="@+id/pick_model" style="@style/Widget.Material3.Button.TonalButton" android:layout_width="wrap_content" android:layout_height="40dp" android:text="Выбрать GGUF" android:textSize="12sp" />
<com.google.android.material.button.MaterialButton android:id="@+id/benchmark" style="@style/Widget.Material3.Button.TonalButton" android:layout_width="wrap_content" android:layout_height="40dp" android:layout_marginStart="8dp" android:enabled="false" android:text="Тест скорости" android:textSize="12sp" /> </LinearLayout> </LinearLayout> </com.google.android.material.card.MaterialCardView>
<androidx.recyclerview.widget.RecyclerView android:id="@+id/messages" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:clipToPadding="false" android:paddingTop="4dp" android:paddingBottom="8dp" android:scrollbars="vertical" tools:listitem="@layout/item_message_assistant" />
<com.google.android.material.card.MaterialCardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="12dp" android:layout_marginEnd="12dp" android:layout_marginBottom="10dp" app:cardBackgroundColor="@color/bonsai_surface" app:cardCornerRadius="22dp" app:strokeColor="#31516A" app:strokeWidth="1dp">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_vertical" android:orientation="horizontal" android:paddingStart="14dp" android:paddingTop="4dp" android:paddingEnd="4dp" android:paddingBottom="4dp">
<EditText android:id="@+id/user_input" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@android:color/transparent" android:enabled="false" android:hint="Сначала выберите модель Bonsai GGUF" android:imeOptions="actionSend" android:inputType="textCapSentences|textMultiLine" android:maxLines="5" android:minHeight="48dp" android:paddingVertical="10dp" android:textColor="@color/bonsai_text" android:textColorHint="@color/bonsai_text_muted" android:textSize="15sp" />
<com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab" style="@style/Widget.Material3.FloatingActionButton.Primary" android:layout_width="52dp" android:layout_height="52dp" android:contentDescription="Отправить" android:enabled="false" android:src="@drawable/outline_send_24" app:backgroundTint="@color/bonsai_green" app:tint="@color/bonsai_navy" /> </LinearLayout> </com.google.android.material.card.MaterialCardView></LinearLayout>12345678910111213141516171819<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="16dp"
android:layout_marginVertical="8dp"
android:gravity="start">
<TextView
android:id="@+id/msg_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_assistant_message"
android:padding="12dp"
android:maxWidth="336dp" android:textColor="@color/bonsai_text" android:textIsSelectable="true" android:textSize="15sp" /></LinearLayout>123456789101112131415161718<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="16dp"
android:layout_marginVertical="8dp"
android:gravity="end">
<TextView
android:id="@+id/msg_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_user_message"
android:padding="12dp"
android:maxWidth="320dp" android:textColor="@color/bonsai_navy" android:textSize="15sp" /></LinearLayout>123456<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>123456<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>12345678910111213<?xml version="1.0" encoding="utf-8"?><resources> <color name="bonsai_navy">#071628</color> <color name="bonsai_surface">#10243A</color> <color name="bonsai_surface_light">#19334E</color> <color name="bonsai_green">#40D39C</color> <color name="bonsai_mint">#8AF5CF</color> <color name="bonsai_cyan">#55E6EB</color> <color name="bonsai_text">#F3FAF8</color> <color name="bonsai_text_muted">#A9C1C6</color> <color name="black">#FF000000</color> <color name="white">#FFFFFFFF</color></resources>123<resources>
<string name="app_name">Bonsai Local</string></resources>123456789101112131415<?xml version="1.0" encoding="utf-8"?><resources> <style name="Base.Theme.AiChatSample" parent="Theme.Material3.Dark.NoActionBar"> <item name="colorPrimary">@color/bonsai_green</item> <item name="colorOnPrimary">@color/bonsai_navy</item> <item name="colorSecondary">@color/bonsai_cyan</item> <item name="colorSurface">@color/bonsai_surface</item> <item name="colorOnSurface">@color/bonsai_text</item> <item name="android:fontFamily">sans</item> <item name="android:windowLightStatusBar">false</item> <item name="android:navigationBarColor">@color/bonsai_navy</item> <item name="android:statusBarColor">@color/bonsai_navy</item> </style> <style name="Theme.AiChatSample" parent="Base.Theme.AiChatSample" /></resources>12345678910111213<?xml version="1.0" encoding="utf-8"?><!--
Sample backup rules file; uncomment and customize as necessary.
See https://developer.android.com/guide/topics/data/autobackup
for details.
Note: This file is ignored for devices older that API 31
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content>
<!--
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content>12345678910111213141516171819<?xml version="1.0" encoding="utf-8"?><!--
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules>
<cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up.
<include .../>
<exclude .../>
-->
</cloud-backup>
<!--
<device-transfer>
<include .../>
<exclude .../>
</device-transfer>
-->
</data-extraction-rules>123456// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.android.library) apply false
alias(libs.plugins.jetbrains.kotlin.android) apply false
}123456789101112131415161718192021222324# 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=verbose1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950[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",]123456#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/dists123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185#!/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" "$@"1/build123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import 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)
}.gitattributes+9
.gitignoreAdded+8
BENCHMARKS.mdAdded+58
LICENSEAdded+21
README.mdAdded+410
README_EN.mdAdded+276
THIRD_PARTY.mdAdded+25
app/.gitignoreAdded+1
app/build.gradle.ktsAdded+66
app/proguard-rules.proAdded+29
app/src/main/AndroidManifest.xmlAdded+30
app/src/main/java/com/example/llama/MainActivity.ktAdded+329
app/src/main/java/com/example/llama/MessageAdapter.ktAdded+51
app/src/main/res/drawable-nodpi/bonsai_launcher.pngAdded

Large File Pointer Details
- SHA256: ff9392343b0d8f88f44282ebb5e726d8d76ab2c6b9c486c4c3a5204415f6e01b
- Pointer size: 132 Bytes
- Size of remote file: 1.46 MB
app/src/main/res/drawable/bg_assistant_message.xmlAdded+5
app/src/main/res/drawable/bg_user_message.xmlAdded+4
app/src/main/res/drawable/ic_launcher_background.xmlAdded+4
app/src/main/res/drawable/ic_launcher_foreground.xmlAdded+12
app/src/main/res/drawable/outline_folder_open_24.xmlAdded+10
app/src/main/res/drawable/outline_send_24.xmlAdded+11
app/src/main/res/layout/activity_main.xmlAdded+174
app/src/main/res/layout/item_message_assistant.xmlAdded+19
app/src/main/res/layout/item_message_user.xmlAdded+18
app/src/main/res/mipmap-anydpi/ic_launcher.xmlAdded+6
app/src/main/res/mipmap-anydpi/ic_launcher_round.xmlAdded+6
app/src/main/res/mipmap-hdpi/ic_launcher.pngAdded

app/src/main/res/mipmap-hdpi/ic_launcher_round.pngAdded

app/src/main/res/mipmap-mdpi/ic_launcher.pngAdded

app/src/main/res/mipmap-mdpi/ic_launcher_round.pngAdded

app/src/main/res/mipmap-xhdpi/ic_launcher.pngAdded

app/src/main/res/mipmap-xhdpi/ic_launcher_round.pngAdded

app/src/main/res/mipmap-xxhdpi/ic_launcher.pngAdded

app/src/main/res/mipmap-xxhdpi/ic_launcher_round.pngAdded

app/src/main/res/mipmap-xxxhdpi/ic_launcher.pngAdded

app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.pngAdded

app/src/main/res/values/colors.xmlAdded+13
app/src/main/res/values/strings.xmlAdded+3
app/src/main/res/values/themes.xmlAdded+15
app/src/main/res/xml/backup_rules.xmlAdded+13
app/src/main/res/xml/data_extraction_rules.xmlAdded+19
bonsai-icon-source.pngAdded
Large File Pointer Details
- SHA256: ff9392343b0d8f88f44282ebb5e726d8d76ab2c6b9c486c4c3a5204415f6e01b
- Pointer size: 132 Bytes
- Size of remote file: 1.46 MB
build.gradle.ktsAdded+6
build/reports/problems/problems-report.htmlAdded
gradle.propertiesAdded+24
gradle/libs.versions.tomlAdded+50
gradle/wrapper/gradle-wrapper.jarAdded
gradle/wrapper/gradle-wrapper.propertiesAdded+6
gradlewAdded+185
lib/.gitignoreAdded+1
lib/build.gradle.ktsAdded+78