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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ jobs:
yes | sdkmanager --install "ndk;${{ env.NDK_VERSION }}" "cmake;3.22.1" || true

- name: Run unit tests
run: ./gradlew testDebugUnitTest --no-daemon -Pandroid.ndkVersion=${{ env.NDK_VERSION }}
run: ./gradlew testVulkanDebugUnitTest --no-daemon -Pandroid.ndkVersion=${{ env.NDK_VERSION }}

- name: Upload test results
uses: actions/upload-artifact@v4
Expand Down
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,7 @@ app/release/
# Temporary files
*.tmp
*.swp

# Hexagon build artifacts
hexagon-libs/
app/src/main/cpp/llama.cpp/build-hexagon/
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@
[submodule "third_party/Vulkan-Headers"]
path = third_party/Vulkan-Headers
url = https://github.com/KhronosGroup/Vulkan-Headers.git
[submodule "third_party/OpenCL-Headers"]
path = third_party/OpenCL-Headers
url = https://github.com/KhronosGroup/OpenCL-Headers.git
39 changes: 34 additions & 5 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,6 @@ android {
"-DANDROID_STL=c++_shared"
)
}
// Don't build 32 bit libraries in 2025
ndk {
abiFilters.add("arm64-v8a")
abiFilters.add("x86_64")
}
}

}
Expand All @@ -59,6 +54,39 @@ android {
signingConfig = signingConfigs.getByName("release")
}
}

// Backend variants: Vulkan (from source) or Hexagon (prebuilt)
flavorDimensions += "backend"
productFlavors {
create("vulkan") {
dimension = "backend"
ndk {
abiFilters.addAll(listOf("arm64-v8a", "x86_64"))
}
externalNativeBuild {
cmake {
arguments("-DBACKEND=vulkan")
}
}
}
create("hexagon") {
dimension = "backend"
externalNativeBuild {
cmake {
arguments("-DBACKEND=hexagon")
}
}
// Hexagon is Qualcomm-only, no x86_64
ndk {
abiFilters.clear()
abiFilters.add("arm64-v8a")
}
// Package prebuilt Hexagon/OpenCL/HTP .so files into APK
sourceSets.getByName("hexagon") {
jniLibs.srcDirs("hexagon-libs")
}
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
Expand Down Expand Up @@ -88,6 +116,7 @@ android {
jniLibs {
pickFirsts.add("lib/arm64-v8a/libc++_shared.so")
pickFirsts.add("lib/x86_64/libc++_shared.so")
useLegacyPackaging = true
}
}
}
Expand Down
10 changes: 10 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,23 @@
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:extractNativeLibs="true"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.BaseweightSnap"
tools:targetApi="31">

<!-- Vendor libraries needed by ggml compute backends.
android:required="false" so the app still installs on devices without these. -->
<uses-native-library
android:name="libOpenCL.so"
android:required="false" />
<uses-native-library
android:name="libcdsprpc.so"
android:required="false" />
<activity
android:name=".SplashActivity"
android:exported="true"
Expand Down
175 changes: 140 additions & 35 deletions app/src/main/cpp/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html.
# For more examples on how to use CMake, see https://github.com/android/ndk-samples.
# BaseweightSnap CMakeLists.txt
# Supports both Vulkan (built from source) and Hexagon (prebuilt) backends

# Sets the minimum CMake version required for this project.
cmake_minimum_required(VERSION 3.22.1)

# Declares the project name
project("baseweightsnap")

# Common settings
# =============================================================================
# Backend Selection
# =============================================================================
# Use -DBACKEND=vulkan or -DBACKEND=hexagon (default: vulkan)
set(BACKEND "vulkan" CACHE STRING "Backend to use: vulkan or hexagon")
set_property(CACHE BACKEND PROPERTY STRINGS vulkan hexagon)

message(STATUS "Selected backend: ${BACKEND}")

# =============================================================================
# Common Settings
# =============================================================================
set(LLAMA_CURL OFF)
set(BUILD_NUMBER 0)
set(BUILD_COMMIT "unknown")
Expand All @@ -20,39 +27,137 @@ set(LLAMA_BUILD_COMMON ON)
set(LLAMA_BUILD_TOOLS OFF)

# =============================================================================
# Vulkan Variant (Simplified - only build option)
# Vulkan Backend (Built from source)
# =============================================================================
if(BACKEND STREQUAL "vulkan")
message(STATUS "Building with Vulkan backend (from source)")

set(GGML_VULKAN ON)
set(GGML_CPU_KLEIDIAI OFF)

# Vulkan headers
set(VULKAN_HEADERS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../../third_party/Vulkan-Headers)
set(VULKAN_HEADERS_INSTALL_DIR ${VULKAN_HEADERS_DIR})
set(Vulkan_INCLUDE_DIR ${VULKAN_HEADERS_DIR}/include)
include_directories(${VULKAN_HEADERS_DIR}/include)

# Build llama.cpp from source
add_subdirectory(llama.cpp build-llama)

# Build mtmd from source
set(LLAMA_INSTALL_VERSION "0.0.0")
add_subdirectory(llama.cpp/tools/mtmd build-mtmd)

# Source files
add_library(baseweightsnap SHARED
mtmd-android.cpp
model_manager.cpp)

target_include_directories(baseweightsnap PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/common
${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/tools/mtmd
${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/src
${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/ggml/src)

target_link_libraries(baseweightsnap
llama
common
mtmd
android
log)

# =============================================================================
# Hexagon Backend (Prebuilt libraries from Snapdragon Docker)
# =============================================================================
elseif(BACKEND STREQUAL "hexagon")
message(STATUS "Building with Hexagon backend (prebuilt libraries)")

# Path to prebuilt Hexagon libraries
# CMAKE_CURRENT_SOURCE_DIR = app/src/main/cpp, so ../../../ = app/
set(HEXAGON_LIB_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../hexagon-libs/${ANDROID_ABI})

# OpenCL headers (for Adreno GPU fallback)
set(OPENCL_HEADERS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../../third_party/OpenCL-Headers)
include_directories(${OPENCL_HEADERS_DIR})

# Verify libraries exist
if(NOT EXISTS ${HEXAGON_LIB_DIR}/libllama.so)
message(FATAL_ERROR "Hexagon libraries not found at ${HEXAGON_LIB_DIR}\n"
"Copy prebuilt .so files to app/hexagon-libs/${ANDROID_ABI}/")
endif()

message(STATUS "Using Hexagon libraries from: ${HEXAGON_LIB_DIR}")

# ---- Import prebuilt shared libraries ----

add_library(llama SHARED IMPORTED)
set_target_properties(llama PROPERTIES
IMPORTED_LOCATION ${HEXAGON_LIB_DIR}/libllama.so
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/include;${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/ggml/include"
)

add_library(mtmd SHARED IMPORTED)
set_target_properties(mtmd PROPERTIES
IMPORTED_LOCATION ${HEXAGON_LIB_DIR}/libmtmd.so
INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/tools/mtmd"
)

add_library(ggml SHARED IMPORTED)
set_target_properties(ggml PROPERTIES
IMPORTED_LOCATION ${HEXAGON_LIB_DIR}/libggml.so
)

add_library(ggml-base SHARED IMPORTED)
set_target_properties(ggml-base PROPERTIES
IMPORTED_LOCATION ${HEXAGON_LIB_DIR}/libggml-base.so
)

# Backend libraries (ggml-cpu, ggml-opencl, ggml-hexagon, ggml-htp-v*)
# are NOT imported as CMake targets. They are packaged into the APK
# via jniLibs and loaded at runtime by llama's backend plugin system.

# ---- Build 'common' static library from source ----
# common is not in the prebuilt package (it's a static lib).
# Our model_manager.cpp uses common_sampler_*, common_chat_templates_*, etc.

set(GGML_VULKAN ON)
set(GGML_CPU_KLEIDIAI OFF)
# No-op stubs for functions defined in llama.cpp's top-level CMake
function(llama_add_compile_flags)
endfunction()
function(license_add_file name file)
endfunction()

# Set Vulkan headers path (relative to project root)
set(VULKAN_HEADERS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../../third_party/Vulkan-Headers)
set(VULKAN_HEADERS_INSTALL_DIR ${VULKAN_HEADERS_DIR})
set(Vulkan_INCLUDE_DIR ${VULKAN_HEADERS_DIR}/include)
include_directories(${VULKAN_HEADERS_DIR}/include)
# cpp-httplib (vendored, required by common)
add_subdirectory(llama.cpp/vendor/cpp-httplib build-httplib)

# Load llama.cpp
add_subdirectory(llama.cpp build-llama)
# common static library
add_subdirectory(llama.cpp/common build-common)

# Build mtmd (multimodal) library - not built when LLAMA_BUILD_TOOLS is OFF
set(LLAMA_INSTALL_VERSION "0.0.0")
add_subdirectory(llama.cpp/tools/mtmd build-mtmd)
# ---- Our native library ----
add_library(baseweightsnap SHARED
mtmd-android.cpp
model_manager.cpp)

# Build Vulkan library
add_library(baseweightsnap SHARED
mtmd-android.cpp
model_manager.cpp)
target_include_directories(baseweightsnap PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/common
${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/tools/mtmd
${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/src
${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/ggml/include)

target_include_directories(baseweightsnap PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/common
${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/tools/mtmd
${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/src
${CMAKE_CURRENT_SOURCE_DIR}/llama.cpp/ggml/src)
# Backend libraries (ggml-hexagon, ggml-opencl, ggml-cpu, ggml-htp-v*)
# are NOT linked directly. They are packaged into the APK via jniLibs
# and loaded at runtime by llama's backend plugin system (dlopen).
# Linking them here would cause transitive dependency failures
# (e.g. libggml-opencl.so needs system libOpenCL.so which is
# blocked by Android's linker namespace isolation).
target_link_libraries(baseweightsnap
llama
common
mtmd
ggml
ggml-base
android
log)

target_link_libraries(baseweightsnap
llama
common
mtmd
android
log)
else()
message(FATAL_ERROR "Unknown backend: ${BACKEND}. Use 'vulkan' or 'hexagon'.")
endif()
2 changes: 1 addition & 1 deletion app/src/main/cpp/llama.cpp
Submodule llama.cpp updated 878 files
28 changes: 27 additions & 1 deletion app/src/main/cpp/model_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,31 @@ bool ModelManager::initializeContext() {
llama_context_params ctx_params = llama_context_default_params();
ctx_params.n_ctx = 4096; // Adjust based on your needs
ctx_params.n_batch = n_batch;

ctx_params.swa_full = false; // Match CLI behavior

lctx = llama_init_from_model(model, ctx_params);
if (!lctx) {
LOGe("Failed to create language context");
return false;
}

// Warmup: let backends compile and validate compute graphs before real data.
// Without this, the Hexagon backend can crash on the first real decode.
llama_set_warmup(lctx, true);
{
llama_token bos = llama_vocab_bos(vocab);
llama_token eos = llama_vocab_eos(vocab);
std::vector<llama_token> tmp;
if (bos != LLAMA_TOKEN_NULL) tmp.push_back(bos);
if (eos != LLAMA_TOKEN_NULL) tmp.push_back(eos);
if (tmp.empty()) tmp.push_back(0);
if (llama_decode(lctx, llama_batch_get_one(tmp.data(), tmp.size()))) {
LOGe("Warmup decode failed");
}
}
llama_set_warmup(lctx, false);
llama_memory_clear(llama_get_memory(lctx), true);

return true;
}

Expand Down Expand Up @@ -197,6 +216,13 @@ void ModelManager::generateResponseAsync(const char* prompt, int max_tokens, JNI
// Store the callback
setCurrentCallback(env, callback);

// Reset context for a fresh generation with the new image.
// Without this, the KV cache accumulates tokens from all previous
// generations and n_past grows unbounded, causing stale context.
n_past = 0;
llama_memory_clear(llama_get_memory(lctx), true);
common_sampler_reset(sampler);

// This ate up literal days of my life
std::string str_prompt(prompt);
if(str_prompt.find("<__image__>") == std::string::npos) {
Expand Down
9 changes: 8 additions & 1 deletion app/src/main/cpp/mtmd-android.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <math.h>
#include <string>
#include <unistd.h>
#include <cstdlib>
#include "llama.h"
#include "common.h"
#include "mtmd.h"
Expand Down Expand Up @@ -178,7 +179,13 @@ Java_ai_baseweight_baseweightsnap_MTMD_1Android_process_1image(

extern "C"
JNIEXPORT void JNICALL
Java_ai_baseweight_baseweightsnap_MTMD_1Android_backend_1init(JNIEnv *, jobject) {
Java_ai_baseweight_baseweightsnap_MTMD_1Android_backend_1init(JNIEnv *env, jobject, jstring native_lib_dir) {
if (native_lib_dir) {
const char *path = env->GetStringUTFChars(native_lib_dir, nullptr);
LOGi("Setting ADSP_LIBRARY_PATH=%s", path);
setenv("ADSP_LIBRARY_PATH", path, 1);
env->ReleaseStringUTFChars(native_lib_dir, path);
}
llama_backend_init();
}

Expand Down
Loading