Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,12 @@ jobs:
- name: Build Release APK
run: ./gradlew :app:assembleRelease

# arm64 build for CPUs without the ARMv8.2 dot-product and FP16 instructions (separate output folder)
- name: Build Compat arm64 APK
run: ./gradlew :app:assembleRelease -PcompatCpu=true

- name: Create GitHub Release
uses: softprops/action-gh-release@v2
if: startsWith(github.ref, 'refs/tags/v')
with:
files: |
app/build/outputs/apk/release/voice_plugin*.apk
app/build-compat/outputs/apk/release/voice_plugin-arm64-v8a-compat.apk
name: Voice Plugin ${{ github.ref_name }}
body_path: docs/release_notes/${{ github.ref_name }}.md
draft: false
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ This plugin provides fast, on-device offline speech-to-text capabilities using [

- **Operating System**: Android 5.0 (API 21) or higher
- **Supported CPU Architectures**: `arm64-v8a`, `armeabi-v7a`, `x86_64`
- **CPU feature requirement (`arm64-v8a`)**: The standard 64-bit build (`voice_plugin-arm64-v8a.apk`, and the universal APK on 64-bit devices) is compiled for ARMv8.2 with dot-product and FP16 instructions (`-march=armv8.2-a+dotprod+fp16`) for speed. This needs a CPU from roughly 2018 on (Cortex-A55/A75 class and newer). On older 64-bit CPUs (for example Cortex-A53, A57, A72 or A73 only devices) the plugin detects this and shows a message instead of crashing; install **`voice_plugin-arm64-v8a-compat.apk`** from the releases there. It runs on every ARMv8 CPU, a little slower. whisper.cpp itself has no Android version requirement beyond the plugin's minimum.
- **CPU (`arm64-v8a`)**: Since v1.1.0 the CPU part of whisper.cpp is included in variants from ARMv8.0 up to ARMv9.2 (dot-product, FP16, i8mm, SVE, SME, KleidiAI kernels), and the plugin loads the best one for the phone at runtime. So the standard build runs on every 64-bit ARM CPU and uses what newer ones can; the separate compat APK of v1.0.4 isn't needed any more.
- **Host Keyboard**: [LeanType](https://github.com/LeanBitLab/LeanType) v4.1.0+ (All flavors); v4.3.3+ for the **Transcribe while speaking** option
- **Permissions**: Microphone permission (`RECORD_AUDIO`)

Expand Down Expand Up @@ -82,7 +82,7 @@ The plugin is an on-demand service. LeanType connects to it when you start voice
### 7. Troubleshooting
- **"Voice plugin is not installed"**: Install the plugin APK from the [releases](https://github.com/LeanBitLab/LeanType-Voice-Plugin/releases/latest) page.
- **"Failed to import model into voice plugin"**: Update the plugin to the latest release and import the `.bin` file again.
- **"This device's CPU lacks the ARMv8.2 dot-product and FP16 instructions"**: Install `voice_plugin-arm64-v8a-compat.apk` from the releases page over the current plugin.
- **"This device's CPU lacks the ARMv8.2 dot-product and FP16 instructions"** (plugin v1.0.3–v1.0.4): update to v1.1.0 or newer, it runs on every 64-bit ARM CPU.
- **No text or only a part of it**: Choose a larger model, check the microphone permission of the plugin, and try a longer **Silence Timeout**.

---
Expand All @@ -91,7 +91,7 @@ The plugin is an on-demand service. LeanType connects to it when you start voice
```bash
./gradlew assembleDebug
```
The compat arm64 APK is built with `./gradlew :app:assembleRelease -PcompatCpu=true` (output in `app/build-compat`). It differs only in the compiler architecture of the native code.
`-PcompatCpu=true` has no effect since v1.1.0 (the CPU variants cover every ARMv8 CPU). `-Pvoice.abis=arm64-v8a` builds one APK with only the given ABIs, which is faster while developing.

Debug builds use the package `com.leanbitlab.leantype.voice.offline.debug`, so they can be installed next to the release plugin. LeanType debug builds connect to the debug plugin when it is installed.

Expand Down
31 changes: 24 additions & 7 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import java.util.Properties

// -PcompatCpu=true builds the arm64 APK for CPUs without the ARMv8.2 dot-product and FP16 instructions
val compatCpu = providers.gradleProperty("compatCpu").orNull == "true"
// -Pvoice.abis=arm64-v8a builds only these ABIs (whisper.cpp takes long to build)
val onlyAbis = providers.gradleProperty("voice.abis").orNull?.split(",")?.map { it.trim() }?.filter { it.isNotEmpty() }
if (compatCpu) {
// separate output, so that the fast and the compat build do not overwrite each other
layout.buildDirectory.set(file("build-compat"))
Expand All @@ -29,15 +31,20 @@ android {
applicationId = "com.leanbitlab.leantype.voice.offline"
minSdk = 21
targetSdk = 35
versionCode = 105
versionName = "1.0.5"
versionCode = 110
versionName = "1.1.0"

// true if the arm64 library of this build needs ARMv8.2 dot-product and FP16 (see CMakeLists.txt)
buildConfigField("boolean", "ARM64_NEEDS_ARMV82", (!compatCpu).toString())
// false: the CPU backend is loaded at runtime in the variant that fits the CPU (see CMakeLists.txt)
buildConfigField("boolean", "ARM64_NEEDS_ARMV82", "false")

externalNativeBuild {
cmake {
arguments("-DCMAKE_BUILD_TYPE=Release", "-DWHISPER_NO_OPENMP=ON", "-DVOICE_COMPAT_CPU=${if (compatCpu) "ON" else "OFF"}")
// shared C++ runtime: whisper, ggml and the CPU backend variants are separate libraries
arguments("-DCMAKE_BUILD_TYPE=Release", "-DWHISPER_NO_OPENMP=ON", "-DANDROID_STL=c++_shared",
// 16 KB memory pages (Android 15+ devices)
"-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON",
"-DVOICE_COMPAT_CPU=${if (compatCpu) "ON" else "OFF"}")
cFlags("-O3", "-DNDEBUG")
cppFlags("-O3", "-DNDEBUG")
}
Expand All @@ -53,6 +60,11 @@ android {
jvmTarget = "17"
}

packaging {
// extracted to the library folder: ggml loads the CPU backend variants from there by path
jniLibs.useLegacyPackaging = true
}

buildFeatures {
aidl = true
buildConfig = true
Expand Down Expand Up @@ -105,14 +117,15 @@ android {
}
ndk {
// the compat build is a single arm64 APK, there are no ABI splits (see below)
abiFilters += if (compatCpu) listOf("arm64-v8a") else listOf("arm64-v8a", "armeabi-v7a", "x86_64")
// with -Pvoice.abis one APK with only these ABIs, without splits
abiFilters += if (compatCpu) listOf("arm64-v8a") else onlyAbis ?: listOf("arm64-v8a", "armeabi-v7a", "x86_64")
}
}
}

splits {
abi {
isEnable = !compatCpu
isEnable = !compatCpu && onlyAbis == null
reset()
include("arm64-v8a", "armeabi-v7a", "x86_64")
isUniversalApk = true
Expand All @@ -126,7 +139,11 @@ android {
if (abi != null) {
output.outputFileName = "voice_plugin-$abi.apk"
} else {
output?.outputFileName = if (compatCpu) "voice_plugin-arm64-v8a-compat.apk" else "voice_plugin.apk"
output?.outputFileName = when {
compatCpu -> "voice_plugin-arm64-v8a-compat.apk"
onlyAbis != null -> "voice_plugin-${onlyAbis.joinToString("-")}.apk"
else -> "voice_plugin.apk"
}
}
}
}
Expand Down
37 changes: 31 additions & 6 deletions app/src/main/cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Pinned whisper.cpp release: v1.7.4 (commit 1fe009c)
# Pinned whisper.cpp release: v1.9.6 (commit 96ec4d9), with the patches in patches/
cmake_minimum_required(VERSION 3.22.1)
project(whisper_jni C CXX)

Expand All @@ -16,12 +16,36 @@ set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG")
set(WHISPER_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(WHISPER_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(WHISPER_NO_OPENMP ON CACHE BOOL "" FORCE)
# ggml's own thread pool (see the patch below), not OpenMP
set(GGML_OPENMP OFF CACHE BOOL "" FORCE)

# The fast arm64 build uses ARMv8.2 dot-product and FP16 instructions, which CPUs before about 2018 (Cortex-A53,
# A57, A72, A73) do not have. The compat build leaves the architecture at the NDK default (ARMv8-a with NEON).
option(VOICE_COMPAT_CPU "arm64 build for every ARMv8-a CPU, without dot-product and FP16 instructions" OFF)
if (ANDROID_ABI STREQUAL "arm64-v8a" AND NOT VOICE_COMPAT_CPU)
set(GGML_CPU_ARM_ARCH "armv8.2-a+dotprod+fp16" CACHE STRING "ggml ARM arch" FORCE)
# The CPU backend is built in variants for different CPU generations (arm64: ARMv8.0 up to ARMv9.2 with i8mm
# and SME, x86_64 likewise) and ggml loads the best one for the phone at runtime, as the LeanType offline AI
# plugin does. So the arm64 build runs on every ARMv8-a CPU and uses what newer ones can.
# VOICE_COMPAT_CPU is not needed any more and changes nothing.
option(VOICE_COMPAT_CPU "no effect: the CPU backend variants cover every ARMv8-a CPU" OFF)
set(BUILD_SHARED_LIBS ON CACHE BOOL "" FORCE)
set(GGML_BACKEND_DL ON CACHE BOOL "" FORCE)
set(GGML_NATIVE OFF CACHE BOOL "" FORCE)
if (ANDROID_ABI STREQUAL "arm64-v8a" OR ANDROID_ABI STREQUAL "x86_64")
set(GGML_CPU_ALL_VARIANTS ON CACHE BOOL "" FORCE)
endif()
if (ANDROID_ABI STREQUAL "arm64-v8a")
# fast kernels for quantized models on ARM (i8mm, SME), chosen at runtime
set(GGML_CPU_KLEIDIAI ON CACHE BOOL "" FORCE)
endif()

# LeanType patch: one thread pool for the CPU backend on the fastest cores, instead of new threads for
# every graph (every decoded token). Applied to the submodule's working tree once.
set(WHISPER_PATCH ${CMAKE_CURRENT_SOURCE_DIR}/patches/whisper-threadpool.patch)
execute_process(COMMAND git apply --reverse --check ${WHISPER_PATCH}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/whisper.cpp RESULT_VARIABLE WHISPER_PATCH_PRESENT OUTPUT_QUIET ERROR_QUIET)
if (NOT WHISPER_PATCH_PRESENT EQUAL 0)
execute_process(COMMAND git apply ${WHISPER_PATCH}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/whisper.cpp RESULT_VARIABLE WHISPER_PATCH_RESULT)
if (NOT WHISPER_PATCH_RESULT EQUAL 0)
message(FATAL_ERROR "whisper.cpp patch ${WHISPER_PATCH} does not apply")
endif()
endif()

add_subdirectory(whisper.cpp)
Expand All @@ -35,5 +59,6 @@ target_include_directories(whisper_jni PRIVATE

target_link_libraries(whisper_jni
whisper
ggml
log
)
84 changes: 84 additions & 0 deletions app/src/main/cpp/patches/whisper-threadpool.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
diff --git a/src/whisper.cpp b/src/whisper.cpp
index 0336bf7..8593ec3 100644
--- a/src/whisper.cpp
+++ b/src/whisper.cpp
@@ -6,6 +6,12 @@
#include "ggml-cpp.h"
#include "ggml-alloc.h"
#include "ggml-backend.h"
+#include "ggml-cpu.h" // types only: the CPU backend may be loaded at runtime, its functions are looked up
+
+#include <map>
+#include <mutex>
+#include <sched.h>
+#include <unistd.h>

#ifdef WHISPER_USE_COREML
#include "coreml/whisper-encoder.h"
@@ -169,6 +175,54 @@ static bool ggml_graph_compute_helper(
return ggml_backend_graph_compute(backend.get(), graph) == GGML_STATUS_SUCCESS;
}

+// LeanType: one thread pool for the CPU backend, kept while the process runs, on the fastest cores.
+// Without it ggml starts and ends threads for every graph, so for every decoded token; on phones the new
+// threads also start on slow cores. Same change in the LeanType offline AI plugin doubled its speed.
+static std::vector<int> whisper_fast_cores(int n) {
+#if defined(__linux__)
+ cpu_set_t allowed;
+ CPU_ZERO(&allowed);
+ // the cores of the process (its main thread), not of this thread: ggml pins the thread that creates a
+ // pool to that pool's cores, so after a pool for 4 threads a pool for 6 would get only those 4 cores
+ if (sched_getaffinity(getpid(), sizeof(allowed), &allowed) != 0) return {};
+ std::vector<std::pair<long, int>> cpus;
+ for (int i = 0; i < CPU_SETSIZE && i < GGML_MAX_N_THREADS; i++) {
+ if (!CPU_ISSET(i, &allowed)) continue;
+ long khz = 0;
+ std::ifstream file("/sys/devices/system/cpu/cpu" + std::to_string(i) + "/cpufreq/cpuinfo_max_freq");
+ file >> khz;
+ if (khz <= 0) return {};
+ cpus.emplace_back(khz, i);
+ }
+ std::stable_sort(cpus.begin(), cpus.end(), [](const auto & a, const auto & b) { return a.first > b.first; });
+ std::vector<int> chosen;
+ for (int i = 0; i < n && i < (int) cpus.size(); i++) chosen.push_back(cpus[i].second);
+ return chosen;
+#else
+ (void) n;
+ return {};
+#endif
+}
+
+// One pool per thread count, never freed: a CPU backend keeps a pointer to the pool it used and pauses it
+// when it gets another one, so freeing it after a change of the thread count would be a use after free.
+// A pool that isn't used sleeps.
+static ggml_threadpool_t whisper_cpu_threadpool(ggml_backend_reg_t reg, int n_threads) {
+ static std::mutex mutex;
+ static std::map<int, ggml_threadpool_t> pools;
+ std::lock_guard<std::mutex> lock(mutex);
+ const auto found = pools.find(n_threads);
+ if (found != pools.end()) return found->second;
+ auto * new_fn = (decltype(ggml_threadpool_new) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_new");
+ if (new_fn == nullptr) return nullptr;
+ ggml_threadpool_params params = ggml_threadpool_params_default(n_threads);
+ for (int core : whisper_fast_cores(n_threads)) params.cpumask[core] = true;
+ params.strict_cpu = false;
+ ggml_threadpool_t pool = new_fn(&params);
+ if (pool != nullptr) pools[n_threads] = pool;
+ return pool;
+}
+
static bool ggml_graph_compute_helper(
ggml_backend_sched_t sched,
struct ggml_cgraph * graph,
@@ -183,6 +237,11 @@ static bool ggml_graph_compute_helper(
if (fn_set_n_threads) {
fn_set_n_threads(backend, n_threads);
}
+ if (dev != nullptr && reg != nullptr && ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU) {
+ auto * set_pool_fn = (decltype(ggml_backend_cpu_set_threadpool) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_set_threadpool");
+ ggml_threadpool_t pool = set_pool_fn != nullptr ? whisper_cpu_threadpool(reg, n_threads) : nullptr;
+ if (pool != nullptr) set_pool_fn(backend, pool);
+ }
}

const bool t = (ggml_backend_sched_graph_compute(sched, graph) == GGML_STATUS_SUCCESS);
2 changes: 1 addition & 1 deletion app/src/main/cpp/whisper.cpp
Loading