### Build and Install Library Source: https://github.com/aatricks/llmedge/blob/main/README.md Gradle commands to build the library and the example application. ```bash ./gradlew :llmedge:assembleRelease ``` ```bash cd llmedge-examples ../gradlew :app:assembleDebug ../gradlew :app:installDebug ``` -------------------------------- ### Setup the conversion environment Source: https://github.com/aatricks/llmedge/blob/main/tools/safetensors-convert/README.md Initialize the llama.cpp submodule, create a virtual environment, and install necessary dependencies. ```bash git submodule update --init llama.cpp # provides convert_hf_to_gguf.py + gguf-py python3 -m venv .venv && source .venv/bin/activate pip install -r tools/safetensors-convert/requirements.txt ``` -------------------------------- ### Build documentation locally with MkDocs Source: https://github.com/aatricks/llmedge/blob/main/docs/contributing.md Install the necessary dependencies and start the local development server to preview documentation changes. ```fish pip install mkdocs mkdocs-material mkdocs serve ``` -------------------------------- ### Validate Example Application Source: https://github.com/aatricks/llmedge/blob/main/docs/testing.md Executes the helper script from the repository root to validate the example application. ```bash bash scripts/validate_examples.sh ``` -------------------------------- ### Prompt Configuration Examples Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Examples of prompt strings for video generation, emphasizing descriptive content and quality modifiers while avoiding negations. ```kotlin // Good "a serene ocean sunset, waves gently rolling, golden hour lighting, cinematic" // Better "a professional chef preparing pasta, kitchen environment, natural lighting, detailed hands" // Avoid "a cat, not blurry" // Negations don't work well ``` -------------------------------- ### Build the Library and Example App Source: https://github.com/aatricks/llmedge/blob/main/docs/installation.md Commands to build the AAR library and the associated example application via Gradle. ```fish ./gradlew :llmedge:assembleDebug ``` ```fish ./gradlew :llmedge:assembleRelease cd llmedge-examples ./gradlew :app:assembleDebug ``` -------------------------------- ### Install build prerequisites Source: https://github.com/aatricks/llmedge/blob/main/scripts/README-macos-host-build.md Install required tools via Homebrew to ensure compatibility with build scripts. ```bash brew install bash cmake ninja gpatch openjdk@17 ``` -------------------------------- ### Initial Image Setup for I2V Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Loading an initial frame and configuring parameters for image-to-video generation. ```kotlin val initialFrame = BitmapFactory.decodeResource(resources, R.drawable.scene) val params = VideoGenerateParams( prompt = "animate this image, add wind and motion", initImage = initialFrame, strength = 0.8f, videoFrames = 16, width = initialFrame.width, height = initialFrame.height ) ``` -------------------------------- ### Build the project using Gradle Source: https://github.com/aatricks/llmedge/blob/main/docs/contributing.md Compiles the library and the example application using Gradle tasks. ```fish ./gradlew :llmedge:assembleDebug ./gradlew :llmedge:assembleRelease cd llmedge-examples && ./gradlew :app:assembleDebug ``` -------------------------------- ### Build and Test Project Source: https://github.com/aatricks/llmedge/blob/main/docs/contributing.md Commands for cleaning and building the project, and validating example applications. ```fish ./gradlew clean build ``` ```fish bash scripts/validate_examples.sh ``` ```fish LLMEDGE_EXAMPLES_GRADLE_TASKS=':app:assembleDebug :app:assembleRelease' bash scripts/validate_examples.sh ``` -------------------------------- ### Install Vulkan Dependencies Source: https://github.com/aatricks/llmedge/blob/main/README.md Install the necessary Vulkan shader compiler and development headers on a Linux host or WSL2. ```bash sudo apt-get update sudo apt-get install -y glslc libvulkan-dev ``` -------------------------------- ### Accept Android SDK Licenses Source: https://github.com/aatricks/llmedge/blob/main/docs/testing.md Automatically accepts all Android SDK licenses if prompted during setup. ```bash yes | "$ANDROID_HOME"/tools/bin/sdkmanager --licenses ``` -------------------------------- ### Verify glslc Installation Source: https://github.com/aatricks/llmedge/blob/main/README.md Check that the glslc compiler is correctly installed and available in the system PATH. ```bash glslc --version ``` -------------------------------- ### Validate examples with build skipping Source: https://github.com/aatricks/llmedge/blob/main/docs/contributing.md Runs the validation script while skipping the library build process to save time. ```fish LLMEDGE_SKIP_LIBRARY_BUILD=true bash scripts/validate_examples.sh ``` -------------------------------- ### C++ JNI Wrapper Implementation Source: https://github.com/aatricks/llmedge/blob/main/docs/contributing.md Example of a JNI-exported function in C++, demonstrating proper string handling and resource release. ```cpp extern "C" JNIEXPORT jlong JNICALL Java_io_aatricks_llmedge_SmolLM_loadModel( JNIEnv* env, jobject /* this */, jstring modelPath, jfloat minP, // ... other params ) { const char* path = env->GetStringUTFChars(modelPath, nullptr); if (!path) { __android_log_print(ANDROID_LOG_ERROR, "SmolLM", "Failed to get model path"); return 0; } // Implementation env->ReleaseStringUTFChars(modelPath, path); return reinterpret_cast(model_ptr); } ``` -------------------------------- ### Configure Bark JNI Library Source: https://github.com/aatricks/llmedge/blob/main/scripts/jni-desktop/CMakeLists.txt Configures the build environment for the Bark JNI wrapper, including directory setup, library linking, and compiler options. ```cmake if(BUILD_BARK) get_filename_component(BARK_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../bark.cpp" ABSOLUTE) if(EXISTS "${BARK_ROOT}/bark.h") set(BARK_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(ENCODEC_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) add_subdirectory(${BARK_ROOT} bark.cpp) add_library(${LLMEDGE_TARGET_BARK_JNI} SHARED ${LLMEDGE_CPP_ROOT}/bark_jni.cpp ${LLMEDGE_CPP_ROOT}/jni_thread_cache.cpp ) target_include_directories(${LLMEDGE_TARGET_BARK_JNI} PRIVATE ${BARK_ROOT} ${BARK_ROOT}/encodec.cpp ${BARK_ROOT}/encodec.cpp/ggml/include ${JNI_INCLUDE_DIRS} ) target_link_libraries(${LLMEDGE_TARGET_BARK_JNI} PRIVATE bark encodec ggml ${JNI_LIBRARIES} pthread m ) find_package(OpenMP) if(OpenMP_CXX_FOUND) target_link_libraries(${LLMEDGE_TARGET_BARK_JNI} PRIVATE OpenMP::OpenMP_CXX) endif() target_compile_options(${LLMEDGE_TARGET_BARK_JNI} PUBLIC -fvisibility=hidden -fvisibility-inlines-hidden) message(STATUS "Bark desktop JNI configured") else() message(WARNING "bark.cpp not found at ${BARK_ROOT}, skipping bark_jni") endif() endif() ``` -------------------------------- ### Validate multiple example variants Source: https://github.com/aatricks/llmedge/blob/main/docs/contributing.md Executes the validation script with specific Gradle tasks for both debug and release builds. ```fish LLMEDGE_EXAMPLES_GRADLE_TASKS=':app:assembleDebug :app:assembleRelease' bash scripts/validate_examples.sh ``` -------------------------------- ### Analyze Images with VLM Source: https://github.com/aatricks/llmedge/blob/main/docs/usage.md Perform image analysis using a Vision Language Model. The second example demonstrates configuring thread counts for the underlying runtime. ```kotlin val edge = LLMEdge.create(context, viewModelScope) val description = edge.vision.analyze( VisionRequest( image = bitmap, prompt = "What is in this image?", model = edge.config.models.vision.model, projector = edge.config.models.vision.projector, ), ) ``` ```kotlin val description = edge.vision.analyze( VisionRequest( image = bitmap, prompt = "What is in this image?", model = edge.config.models.vision.model, projector = edge.config.models.vision.projector, numThreads = 4, generationThreads = 2, ), ) ``` -------------------------------- ### Kotlin Native Wrapper Implementation Source: https://github.com/aatricks/llmedge/blob/main/docs/contributing.md Example of a suspend function for loading models, utilizing Dispatchers.IO to handle blocking JNI operations. ```kotlin /** * Loads a GGUF model from the specified path. * * @param modelPath Absolute path to the GGUF file. * @param params Inference configuration parameters. * @throws ModelFileNotFoundException if the model file doesn't exist. * @throws InvalidModelFileException if the file is unreadable, empty, or not a GGUF model. * @throws ModelLoadException if the validated model cannot be loaded by the native runtime. */ suspend fun load( modelPath: String, params: InferenceParams = InferenceParams() ) = withContext(Dispatchers.IO) { // Implementation - uses IO because native JNI calls block the thread } ``` -------------------------------- ### Initialize RAG Session Source: https://github.com/aatricks/llmedge/blob/main/README.md Sets up a RAG session to index documents and perform queries. ```kotlin val edge = LLMEdge.create(this, lifecycleScope) val rag = edge.rag.createSession() lifecycleScope.launch { rag.init() val count = rag.indexPdf(pdfUri) val answer = rag.ask("What are the key points?") // render answer } ``` -------------------------------- ### Clone the Repository Source: https://github.com/aatricks/llmedge/blob/main/docs/installation.md Initializes the project and its submodules from the remote repository. ```fish git clone https://github.com/Aatricks/llmedge.git cd llmedge git submodule update --init --recursive ``` -------------------------------- ### Build with OpenCL and Vulkan Support Source: https://github.com/aatricks/llmedge/blob/main/README.md Use Gradle to assemble the release build with experimental OpenCL and Vulkan support enabled via project properties. ```bash ./gradlew :llmedge:assembleRelease \ -PllmedgeAndroidOpencl=ON \ -Pandroid.injected.build.api=30 \ -Pandroid.jniCmakeArgs="-DSD_VULKAN=ON -DGGML_VULKAN=ON" ``` -------------------------------- ### Switch Between Models Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Demonstrates manual model unloading and loading to manage memory during transitions. ```kotlin // Load first model var sd = StableDiffusion.load(this, modelId1, filename1) val frames1 = sd.txt2vid(params) sd.close() // Switch to second model sd = StableDiffusion.load(this, modelId2, filename2) val frames2 = sd.txt2vid(params) sd.close() ``` -------------------------------- ### Verify GPU Backend Logs Source: https://github.com/aatricks/llmedge/blob/main/README.md Use adb logcat to inspect initialization messages for OpenCL or Vulkan backends. ```bash adb logcat -s SmolSD:* | sed -n '1,200p' ``` -------------------------------- ### Initialize Bash Execution Tool Source: https://github.com/aatricks/llmedge/blob/main/README.md Configures a bash tool for shell command execution, requiring explicit opt-in for raw shell strings and specific policies. ```kotlin val edge = LLMEdge.create(context, viewModelScope) val bashTool = BashToolFactory( BashToolOptions( allowRawShell = true, // raw `command` strings are disabled unless you opt in defaultWorkingDirectory = context.filesDir.absolutePath, ), ).createBashTool() val agent = edge.text.toolAgent( tools = listOf(bashTool), systemPrompt = "Use shell commands only when necessary.", policy = ToolPolicies.ALLOW_ALL, // required because run_bash_command is an action tool ) ``` -------------------------------- ### Run E2E helper scripts Source: https://github.com/aatricks/llmedge/blob/main/docs/testing.md Uses helper scripts to automatically build and copy the required host libraries for E2E testing. ```bash ./scripts/run_text_e2e.sh ./scripts/run_whisper_e2e.sh ``` -------------------------------- ### Build Library with GPU Support Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Configure Gradle build parameters to enable OpenCL and Vulkan support for Android. ```bash ./gradlew :llmedge:assembleRelease \ -PllmedgeAndroidOpencl=ON \ -Pandroid.jniCmakeArgs="-DGGML_VULKAN=ON -DSD_VULKAN=ON" ``` -------------------------------- ### Clone the LLMEdge repository Source: https://github.com/aatricks/llmedge/blob/main/README.md Use these commands to clone the repository and initialize the required submodules. ```bash git clone --depth=1 https://github.com/Aatricks/llmedge cd llmedge git submodule update --init --recursive ``` -------------------------------- ### Load and run local model inference Source: https://github.com/aatricks/llmedge/blob/main/docs/examples.md Demonstrates initializing the LLMEdge engine and executing a text generation request using a local GGUF model file. ```kotlin val modelPath = copyAssetIfNeeded("YourModel.gguf") val edge = LLMEdge.create(context, lifecycleScope) // Run inference through the text client val response = edge.text.generate( prompt = "Say 'hello from llmedge'.", model = ModelSpec.localFile(modelPath), ) ``` -------------------------------- ### Build and run text model tests Source: https://github.com/aatricks/llmedge/blob/main/scripts/README-macos-host-build.md Configure environment variables and execute the build and test commands for the smollm JNI library. ```bash PATCH_BIN=/tmp/gnubin # dir containing a `patch` -> gpatch symlink (see above) JDK=/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home JBR="/Applications/Android Studio.app/Contents/jbr/Contents/Home" # any JDK 17+ runs gradle # 1) Build the host smollm JNI library JAVA_HOME="$JDK" PATH="$PATCH_BIN:/opt/homebrew/bin:$PATH" \ /opt/homebrew/bin/bash scripts/build_native_linux.sh smollm # 2) Run the text E2E against any GGUF (here: BitNet b1.58 IQ2_BN) export LLMEDGE_BUILD_NATIVE_LIB_PATH="$PWD/llmedge/build/native/linux-aarch64/libsmollm.so" export LLMEDGE_TEST_TEXT_MODEL_PATH="$PWD/models/bitnet1582b4t-iq2_bn.gguf" JAVA_HOME="$JBR" ./gradlew :llmedge:testDebugUnitTest \ --tests "io.aatricks.llmedge.TextInferenceLinuxE2ETest" --no-daemon --rerun-tasks ``` -------------------------------- ### Generate video with Wan 2.1 Source: https://github.com/aatricks/llmedge/blob/main/docs/examples.md Demonstrates text-to-video generation. Enabling forceSequentialLoad is critical for devices with limited RAM to manage memory usage during model loading. ```kotlin val edge = LLMEdge.create(context, lifecycleScope) // 1. Configure params for mobile-friendly generation val params = VideoGenerationRequest( prompt = "A dog running in the park", width = 512, // Wan models require multiples of 64 between 256-960 height = 512, videoFrames = 8, // Start with fewer frames (8-16) steps = 20, cfgScale = 7.0f, flowShift = 3.0f, // Use Float.POSITIVE_INFINITY to auto-select forceSequentialLoad = true // Critical for devices with <12GB RAM ) // 2. Generate video edge.image.generateVideo(params).collect { event -> when (event) { is GenerationStreamEvent.Progress -> updateProgress(event.update.message) is GenerationStreamEvent.Completed -> imageView.setImageBitmap(event.frames.first()) } } ``` -------------------------------- ### Configure CMake Project and Dependencies Source: https://github.com/aatricks/llmedge/blob/main/scripts/jni-desktop/CMakeLists.txt Sets up the project environment, C++ standards, and includes necessary llmedge modules. ```cmake cmake_minimum_required(VERSION 3.10) project(sdcpp_desktop) set(CMAKE_CXX_STANDARD 20) set(CMAKE_POSITION_INDEPENDENT_CODE ON) get_filename_component(LLMEDGE_CPP_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../llmedge/src/main/cpp" ABSOLUTE) include("${LLMEDGE_CPP_ROOT}/cmake/llmedge-mods.cmake") include("${LLMEDGE_CPP_ROOT}/cmake/llmedge-targets.cmake") ``` -------------------------------- ### Download Models from Hugging Face Source: https://github.com/aatricks/llmedge/blob/main/docs/usage.md Methods for prefetching or loading models directly from Hugging Face with progress tracking. ```kotlin val edge = LLMEdge.create(context, viewModelScope) val modelFile = edge.models.prefetch( ModelSpec.huggingFace( repoId = "unsloth/Qwen3-0.6B-GGUF", filename = "Qwen3-0.6B-Q4_K_M.gguf", preferSystemDownloader = true, ), onProgress = { progress -> /* update UI */ }, ) ``` ```kotlin val download = smol.loadFromHuggingFace( context = context, modelId = "unsloth/Qwen3-0.6B-GGUF", filename = "Qwen3-0.6B-Q4_K_M.gguf", params = InferenceParams(contextSize = 4096L), preferSystemDownloader = true, onProgress = { downloaded, total -> /* update UI */ } ) ``` ```kotlin val sdWan = StableDiffusion.loadFromHuggingFace( context = context, modelId = "wan/Wan2.1-T2V-1.3B", preferSystemDownloader = true, onProgress = { name, downloaded, total -> /* update progress */ } ) ``` -------------------------------- ### Verify GPU Capability Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Check the availability of OpenCL and Vulkan backends at runtime. ```kotlin val openClAvailable = LLMEdge.isOpenClAvailable() val vulkanAvailable = LLMEdge.isVulkanAvailable() // The selected backend is logged during model load. ``` -------------------------------- ### Configure Tool Agents for Model Interaction Source: https://github.com/aatricks/llmedge/blob/main/README.md Sets up a tool agent with a factory and policy, allowing the model to execute defined tools during conversation. ```kotlin val edge = LLMEdge.create(context, viewModelScope) val factory = DeviceToolFactory(context) val agent = edge.text.toolAgent( tools = factory.createDefaultTools(), systemPrompt = "Be concise and only use tools when needed.", policy = ToolPolicies.ALLOW_ALL, // or keep the default to deny action tools ) viewModelScope.launch { val result = agent.reply("What time is it and how much battery is left?") println(result.text) agent.stream("Open https://example.com").collect { event -> when (event) { is ToolAgentEvent.ToolCallRequested -> println("Tool: ${event.call.tool}") is ToolAgentEvent.TextChunk -> print(event.value) is ToolAgentEvent.Completed -> println("\nDone: ${event.result.finishReason}") else -> Unit } } } ``` -------------------------------- ### Initialize a tool agent Source: https://github.com/aatricks/llmedge/blob/main/docs/usage.md Configures a tool agent with specific tools and policies, enabling the model to execute shell commands via the BashTool. ```kotlin val edge = LLMEdge.create(context, viewModelScope) val agent = edge.text.toolAgent( tools = listOf( BashToolFactory( BashToolOptions( allowRawShell = true, defaultWorkingDirectory = context.filesDir.absolutePath, ), ).createBashTool(), ), systemPrompt = "Use shell commands only when they materially help answer the user.", policy = ToolPolicies.ALLOW_ALL, ) ``` -------------------------------- ### Build and use llama-quantize for specific precisions Source: https://github.com/aatricks/llmedge/blob/main/tools/safetensors-convert/README.md Build the llama-quantize binary from the submodule and use it for lossy quantization tasks. ```bash cmake -S llama.cpp -B build-host -DGGML_IQK_FLASH_ATTENTION=ON && cmake --build build-host -t llama-quantize python convert.py --source deepgrove/Bonsai --adapter bonsai-qlinear \ --precision iq2_bn --out bonsai-0.5b-iq2_bn.gguf --quantize-bin build-host/bin/llama-quantize ``` -------------------------------- ### Run WAN video E2E tests Source: https://github.com/aatricks/llmedge/blob/main/docs/testing.md Execute video generation tests on a connected arm64 device using the specific test class runner. ```bash ./gradlew :llmedge:connectedDebugAndroidTest \ -Pandroid.testInstrumentationRunnerArguments.class=io.aatricks.llmedge.WanVideoE2ETest ``` -------------------------------- ### Configure Quality-Focused Video Generation Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Use higher resolution and step counts to improve output fidelity at the cost of performance. ```kotlin // Quality-focused configuration val params = VideoGenerateParams( prompt = "detailed, high quality, cinematic scene...", videoFrames = 16, width = 768, height = 768, steps = 25, cfgScale = 8.0, scheduler = Scheduler.DDPM ) ``` -------------------------------- ### Execute Batch Video Generation Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Reuse a single model instance to generate multiple videos sequentially from a list of prompts. ```kotlin // Reuse model instance val sd = StableDiffusion.load(this, modelId, filename) prompts.forEach { prompt -> val frames = sd.txt2vid(params.copy(prompt = prompt)) processFrames(frames) } sd.close() ``` -------------------------------- ### Create a Feature Branch Source: https://github.com/aatricks/llmedge/blob/main/docs/contributing.md Use this command to initialize a new feature branch in the repository. ```fish git checkout -b feature/your-feature-name ``` -------------------------------- ### Configure Reasoning Controls Source: https://github.com/aatricks/llmedge/blob/main/docs/usage.md Adjusts thinking traces and reasoning budgets for reasoning-aware models at load time or runtime. ```kotlin // Disable thinking at load time val params = InferenceParams( thinkingMode = ThinkingMode.DISABLED, reasoningBudget = 0 ) smol.load(modelPath, params) // Toggle at runtime smol.setThinkingEnabled(false) // disable smol.setReasoningBudget(-1) // unrestricted ``` -------------------------------- ### Utilize built-in model presets Source: https://github.com/aatricks/llmedge/blob/main/docs/usage.md Access pre-configured model specifications for low-end devices, including BitNet and SmolVLM2. ```kotlin // Microsoft BitNet b1.58 2B4T — native 1-bit LLM (IQ2_BN, ~988 MB). // The canonical chat template ships on the preset (BitNet's GGUF metadata one is wrong), // so this is well-formed without setting TextModelOptions.chatTemplate. val reply = edge.text.generate(prompt = "Hi", model = ModelPresets.bitnet) // SmolVLM2-256M — tiny vision model (~280 MB total: base + projector). val caption = edge.vision.analyze( image = bitmap, prompt = "Describe this image.", model = ModelPresets.smolVlm2.model, projector = ModelPresets.smolVlm2.projector, ) ``` -------------------------------- ### Run unit tests for fold math Source: https://github.com/aatricks/llmedge/blob/main/tools/safetensors-convert/README.md Execute the test suite for the Bonsai fold logic using numpy. ```bash pip install numpy python tools/safetensors-convert/test_bonsai_fold.py ``` -------------------------------- ### Stream Audio for Real-time Transcription Source: https://github.com/aatricks/llmedge/blob/main/README.md Implement live captioning using a sliding window approach with streaming parameters. ```kotlin val edge = LLMEdge.create(context, viewModelScope) val session = edge.speech.createStreamingSession( params = Whisper.StreamingParams( stepMs = 3000, lengthMs = 10000, keepMs = 200, language = "en", useVad = true, ), ) viewModelScope.launch { session.events().collect { segment -> updateCaptions(segment.text) } } audioRecorder.onAudioChunk { samples -> viewModelScope.launch { session.feedAudio(samples) } } session.stop() ``` -------------------------------- ### Generate Videos with Wan 2.1 Source: https://github.com/aatricks/llmedge/blob/main/docs/usage.md Configures a video generation request and collects streaming events to handle progress and final output. ```kotlin val edge = LLMEdge.create(context, viewModelScope) val request = VideoGenerationRequest( prompt = "A robot dancing in the rain", videoFrames = 16, width = 512, height = 512, steps = 20, cfgScale = 7.0f, flowShift = 3.0f, forceSequentialLoad = true, ) viewModelScope.launch { edge.image.generateVideo(request).collect { event -> when (event) { is GenerationStreamEvent.Progress -> Log.d("Video", event.update.message) is GenerationStreamEvent.Completed -> previewImageView.setImageBitmap(event.frames.first()) } } } ``` -------------------------------- ### Configure environment variables for Linux E2E Source: https://github.com/aatricks/llmedge/blob/main/docs/testing.md Sets the necessary paths for native libraries, models, and library search paths before running tests. ```bash export LLMEDGE_BUILD_NATIVE_LIB_PATH="$PWD/llmedge/build/native/linux-x86_64/libsmollm.so" export LLMEDGE_BUILD_WHISPER_LIB_PATH="$PWD/llmedge/build/native/linux-x86_64/libwhisper_jni.so" export LLMEDGE_BUILD_BARK_LIB_PATH="$PWD/llmedge/build/native/linux-x86_64/libbark_jni.so" export LLMEDGE_TEST_TEXT_MODEL_PATH="$PWD/models/SmolLM2-135M-Instruct-Q8_0.gguf" export LLMEDGE_TEST_TOOL_MODEL_PATH="$PWD/models/SmolLM2-1.7B-Instruct-Q8_0.gguf" export LLMEDGE_TEST_WHISPER_MODEL_PATH="$PWD/models/ggml-tiny.en.bin" export LD_LIBRARY_PATH="$PWD/llmedge/build/native/linux-x86_64:$LD_LIBRARY_PATH" ``` -------------------------------- ### Run JVM unit tests Source: https://github.com/aatricks/llmedge/blob/main/docs/testing.md Executes the library's JVM unit tests via Gradle. ```bash ./gradlew :llmedge:testDebugUnitTest ``` -------------------------------- ### Build host JNI library Source: https://github.com/aatricks/llmedge/blob/main/docs/testing.md Compiles the native host library for the specified model. ```bash ./scripts/build_native_linux.sh smollm ``` -------------------------------- ### Build native code with GPU backends Source: https://github.com/aatricks/llmedge/blob/main/docs/contributing.md Clean existing native builds and rebuild with specific GPU backend flags for Android. ```fish # Clean native builds rm -rf llmedge/.cxx # Rebuild with Android GPU backends ./gradlew :llmedge:assembleRelease \ -PllmedgeAndroidOpencl=ON \ -Pandroid.jniCmakeArgs="-DGGML_VULKAN=ON -DSD_VULKAN=ON" ``` -------------------------------- ### Define Build Options and Paths Source: https://github.com/aatricks/llmedge/blob/main/scripts/jni-desktop/CMakeLists.txt Configures paths for stable-diffusion.cpp and defines build toggles for various JNI components. ```cmake # Point to stable-diffusion.cpp root. set(SD_ROOT_OVERRIDE "" CACHE PATH "Override path to stable-diffusion.cpp root") if (SD_ROOT_OVERRIDE) get_filename_component(SD_ROOT "${SD_ROOT_OVERRIDE}" ABSOLUTE) else() get_filename_component(SD_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../stable-diffusion.cpp" ABSOLUTE) endif() get_filename_component(LLMEDGE_REPO_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../.." ABSOLUTE) set(LLMEDGE_MODS_DIR "${LLMEDGE_REPO_ROOT}/mods") # Options to control what to build option(BUILD_SDCPP "Build stable-diffusion.cpp JNI" ON) option(BUILD_SMOLLM "Build SmolLM (llama.cpp) JNI" OFF) option(BUILD_BARK "Build Bark JNI" OFF) # Find JNI find_package(JNI REQUIRED) ``` -------------------------------- ### Convert and quantize Bonsai models Source: https://github.com/aatricks/llmedge/blob/main/README.md Converts unpacked Bonsai transformer weights to BFL naming and quantizes them for use with stable-diffusion.cpp. ```bash python3 scripts/convert_bonsai_flux2_to_bfl.py \ bonsai-image-ternary-4B-unpacked/transformer/diffusion_pytorch_model.safetensors \ bonsai-flux2-bfl.safetensors sd -M convert -m bonsai-flux2-bfl.safetensors --type q2_K -o bonsai-flux2-klein-q2_K.gguf ``` -------------------------------- ### Analyze Images with Vision Models Source: https://github.com/aatricks/llmedge/blob/main/README.md Use a vision-capable GGUF model to analyze an image with a prompt. ```kotlin val edge = LLMEdge.create(context, viewModelScope) val description = edge.vision.analyze( image = bitmap, prompt = "Describe this image in detail.", numThreads = 4, generationThreads = 2, ) { status -> Log.d("Vision", "Status: $status") } ``` -------------------------------- ### Classifier-Free Guidance Scale Configuration Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Adjusting the cfgScale to control how strictly the model adheres to the provided prompt. ```kotlin // Creative freedom cfgScale = 3.0 // Standard (recommended) cfgScale = 7.0 // Strict prompt following cfgScale = 10.0 ``` -------------------------------- ### Load video generation models explicitly Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Manually download and load model components. This is required for Wan models where the simplified modelId approach is unsupported. ```kotlin // Download all three model files explicitly val modelFile = HuggingFaceHub.ensureRepoFileOnDisk( context = this, modelId = "Comfy-Org/Wan_2.1_ComfyUI_repackaged", revision = "main", filename = "wan2.1_t2v_1.3B_fp16.safetensors", allowedExtensions = listOf(".safetensors"), preferSystemDownloader = true ) val vaeFile = HuggingFaceHub.ensureRepoFileOnDisk( context = this, modelId = "Comfy-Org/Wan_2.1_ComfyUI_repackaged", revision = "main", filename = "wan_2.1_vae.safetensors", allowedExtensions = listOf(".safetensors"), preferSystemDownloader = true ) val t5xxlFile = HuggingFaceHub.ensureRepoFileOnDisk( context = this, modelId = "city96/umt5-xxl-encoder-gguf", revision = "main", filename = "umt5-xxl-encoder-Q3_K_S.gguf", allowedExtensions = listOf(".gguf"), preferSystemDownloader = true ) // Load all three models together val sd = StableDiffusion.load( context = this, modelPath = modelFile.file.absolutePath, vaePath = vaeFile.file.absolutePath, t5xxlPath = t5xxlFile.file.absolutePath, nThreads = Runtime.getRuntime().availableProcessors(), offloadToCpu = true, keepClipOnCpu = true, keepVaeOnCpu = true, loraModelDir = null, // Or provide path to LoRA directory if applicable loraApplyMode = StableDiffusion.LoraApplyMode.AUTO ) ``` -------------------------------- ### Configure Fast Video Generation Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Adjust parameters to improve generation speed while maintaining acceptable output quality. ```kotlin // Fast generation configuration val params = VideoGenerateParams( prompt = "...", videoFrames = 16, width = 512, height = 512, steps = 15, // Reduced from 20 cfgScale = 7.0 ) ``` -------------------------------- ### Resolution Configuration Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Setting width and height for output resolution, where values must be multiples of 64. ```kotlin // Fast generation (~2 sec/frame on mid-range) width = 256, height = 256 // Balanced (recommended) width = 512, height = 512 // High quality (~8 sec/frame on mid-range) width = 768, height = 768 ``` -------------------------------- ### Generate Images with LLMEdge Source: https://github.com/aatricks/llmedge/blob/main/docs/usage.md Initializes the LLMEdge client and generates an image using a prompt and optional LoRA fine-tuning parameters. ```kotlin val edge = LLMEdge.create(context, viewModelScope) val bitmap = edge.image.generate( ImageGenerationRequest( prompt = "A cyberpunk city street at night, neon lights ", width = 512, height = 512, steps = 20, loraModelDir = getExternalFilesDir("loras")?.absolutePath + "/detail-tweaker-lora-sd15", loraApplyMode = StableDiffusion.LoraApplyMode.AUTO ), ) ``` -------------------------------- ### Generate images with LLMEdge Source: https://github.com/aatricks/llmedge/blob/main/docs/examples.md Demonstrates basic image generation. Use smaller dimensions like 256x256 for devices with less than 4GB of RAM. ```kotlin val edge = LLMEdge.create(context, lifecycleScope) // Generate image val bitmap = edge.image.generate( ImageGenerationRequest( prompt = "a cute cat", width = 256, // Start small on mobile height = 256, steps = 20, cfgScale = 7.0f ), ) // Display result imageView.setImageBitmap(bitmap) ``` -------------------------------- ### Implement RAG pipeline for PDFs Source: https://github.com/aatricks/llmedge/blob/main/docs/examples.md Indexes PDF documents and performs Q&A using vector store search. Requires embedding models in the assets directory. ```kotlin val edge = LLMEdge.create(context, lifecycleScope) val rag = edge.rag.createSession() rag.init() // 1. Index a PDF document val count = rag.indexPdf(pdfUri) Log.d("RAG", "Indexed $count chunks") // 2. Ask questions val answer = rag.ask("What are the key points?", topK = 5) ``` -------------------------------- ### Diffusion Steps Configuration Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Setting the number of diffusion steps to balance generation speed and output quality. ```kotlin // Fast generation steps = 15 // Production quality steps = 20 // Maximum quality steps = 30 ``` -------------------------------- ### Convert models to GGUF Source: https://github.com/aatricks/llmedge/blob/main/tools/safetensors-convert/README.md Execute the conversion script for standard models or models requiring specific adapters. ```bash cd tools/safetensors-convert # Stock Llama/Mistral/Qwen… -> F16 (arbitrary archs inherit upstream converter coverage) python convert.py --source unsloth/Qwen3-0.6B --precision f16 --out qwen3-0.6b-f16.gguf # Bonsai 0.5B: fold the QLinear per-output scales, then quantize python convert.py --source deepgrove/Bonsai --adapter bonsai-qlinear \ --precision q8_0 --out bonsai-0.5b-q8_0.gguf ``` -------------------------------- ### Prepare Vision Runtime Source: https://github.com/aatricks/llmedge/blob/main/docs/usage.md Explicitly prepare the vision runtime with specific thread configurations. ```kotlin edge.vision.prepare( VisionPrepareRequest( model = edge.config.models.vision.model, projector = edge.config.models.vision.projector, promptThreads = 4, generationThreads = 2, ), ) ``` -------------------------------- ### Initialize LLMEdge and Generate Text Source: https://github.com/aatricks/llmedge/blob/main/README.md Create an LLMEdge instance and perform a text generation task within a coroutine scope. ```kotlin val edge = LLMEdge.create( context = context, scope = viewModelScope, ) viewModelScope.launch { val reply = edge.text.generate( prompt = "Summarize on-device LLMs in one sentence.", ) outputView.text = reply } ``` -------------------------------- ### Generate images with MiniT2I Source: https://github.com/aatricks/llmedge/blob/main/README.md Initializes the MiniT2I helper to generate images from text prompts using default diffusion settings. ```kotlin val edge = LLMEdge.create(context, viewModelScope) val bitmap = edge.image.generate( MiniT2I.imageRequest("a small robot watering flowers"), ) ``` -------------------------------- ### Configure SmolLM JNI Build Source: https://github.com/aatricks/llmedge/blob/main/scripts/jni-desktop/CMakeLists.txt Sets up the llama.cpp environment, applies architecture-specific compiler flags, and defines the shared library target for SmolLM. ```cmake if(BUILD_SMOLLM) get_filename_component(LLAMA_ROOT_UPSTREAM "${CMAKE_CURRENT_SOURCE_DIR}/../../llama.cpp" ABSOLUTE) llmedge_prepare_patch_modded_tree( NAME "llama.cpp" SOURCE_ROOT "${LLAMA_ROOT_UPSTREAM}" MODS_ROOT "${LLMEDGE_MODS_DIR}/llama.cpp" USE_MODS_VAR "LLMEDGE_LLAMA_USE_MODS" OUT_VAR LLAMA_ROOT ) message(STATUS "Using llama.cpp root: ${LLAMA_ROOT}") set(LLMEDGE_LLAMA_USE_MEMORY_API OFF CACHE BOOL "Use llama_memory_* APIs instead of llama_kv_cache_* compatibility APIs" FORCE) # Configure llama.cpp options set(LLAMA_BUILD_TESTS OFF CACHE BOOL "" FORCE) set(LLAMA_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(LLAMA_BUILD_SERVER OFF CACHE BOOL "" FORCE) set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) set(LLAMA_CURL OFF CACHE BOOL "" FORCE) set(LLAMA_LLGUIDANCE OFF CACHE BOOL "" FORCE) if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64)$") # ik_llama.cpp IQK kernels only compile their real x86 path when the build enables # AVX2-or-better CPU features. Without this, Linux host builds fall back to stubbed # implementations that abort at runtime for Q8_KV / IQ*_K* inference. set(GGML_NATIVE ON CACHE BOOL "" FORCE) set(GGML_AVX2 ON CACHE BOOL "" FORCE) set(GGML_FMA ON CACHE BOOL "" FORCE) set(GGML_F16C ON CACHE BOOL "" FORCE) elseif(APPLE AND CMAKE_SYSTEM_PROCESSOR MATCHES "^(aarch64|arm64)$") set(GGML_NATIVE OFF CACHE BOOL "" FORCE) add_compile_options(-march=armv8.2-a+fp16+dotprod) endif() if(NOT DEFINED GGML_VULKAN) set(GGML_VULKAN OFF CACHE BOOL "" FORCE) endif() # Add llama.cpp add_subdirectory(${LLAMA_ROOT} llama.cpp) add_subdirectory(${LLAMA_ROOT}/examples/mtmd llama.cpp-mtmd) add_subdirectory(${LLAMA_ROOT}/examples/quantize llama.cpp-quantize) # Build smollm shared library add_library(${LLMEDGE_TARGET_SMOLLM} SHARED ${LLMEDGE_CPP_ROOT}/smollm.cpp ${LLMEDGE_CPP_ROOT}/smollm_jni_load.cpp ${LLMEDGE_CPP_ROOT}/smollm_jni_completion.cpp ${LLMEDGE_CPP_ROOT}/smollm_jni_embeddings.cpp ${LLMEDGE_CPP_ROOT}/smollm_jni_state.cpp ${LLMEDGE_CPP_ROOT}/smollm_jni_convert.cpp ${LLMEDGE_CPP_ROOT}/LLMInference.cpp ${LLMEDGE_CPP_ROOT}/llm_backend_support.cpp ${LLMEDGE_CPP_ROOT}/gguf_reader_internal.cpp ${LLMEDGE_CPP_ROOT}/GGUFReader.cpp # On-device safetensors -> GGUF converter (Track B / Phase B2). No ggml/llama dependency. ${LLMEDGE_CPP_ROOT}/convert/safetensors_reader.cpp ${LLMEDGE_CPP_ROOT}/convert/gguf_writer.cpp ${LLMEDGE_CPP_ROOT}/convert/tokenizer_bake.cpp ${LLMEDGE_CPP_ROOT}/convert/hf_to_gguf.cpp ) target_include_directories(${LLMEDGE_TARGET_SMOLLM} PRIVATE ${LLAMA_ROOT}/include ${LLAMA_ROOT}/common ${LLAMA_ROOT}/examples/mtmd ${LLAMA_ROOT}/ggml/include ${LLAMA_ROOT}/ggml/src ${LLAMA_ROOT} # For some internal headers if needed ${JNI_INCLUDE_DIRS} ) target_compile_definitions(${LLMEDGE_TARGET_SMOLLM} PRIVATE LLMEDGE_LLAMA_USE_MEMORY_API=$ ) target_link_libraries(${LLMEDGE_TARGET_SMOLLM} PRIVATE llama common mtmd ${JNI_LIBRARIES} ) if(APPLE) # macOS produces .dylib by default; the desktop test harness loads the lib by an absolute # `.so` path (System.load accepts any extension), so force the `.so` suffix on all hosts. set_target_properties(${LLMEDGE_TARGET_SMOLLM} PROPERTIES SUFFIX ".so") endif() endif() ``` -------------------------------- ### Create Managed Chat Sessions in Kotlin Source: https://github.com/aatricks/llmedge/blob/main/README.md Initializes a chat session with a conversation window and system prompt, handling streaming events within a coroutine scope. ```kotlin val edge = LLMEdge.create(context, viewModelScope) val session = edge.text.session( memory = ConversationWindow( maxTurns = 6, maxTokens = 4096, stripThinkTags = true, ), systemPrompt = "You are a concise assistant.", ) viewModelScope.launch { session.prepare() val reply = session.reply("Explain why context windows fill up.") session.stream("Now summarize that in 3 bullets.").collect { event -> when (event) { is TextStreamEvent.Chunk -> print(event.value) is TextStreamEvent.Completed -> println(event.fullText) else -> Unit } } } ``` -------------------------------- ### Run Bark TTS Desktop E2E Test Source: https://github.com/aatricks/llmedge/blob/main/docs/testing.md Environment configuration and Gradle command for running Bark tests on a Linux desktop environment. ```bash export LLMEDGE_BUILD_BARK_LIB_PATH="/path/to/libbark_jni.so" export LLMEDGE_TEST_BARK_MODEL_PATH="/path/to/bark_ggml_weights.bin" export LD_LIBRARY_PATH="/path/to/lib:$LD_LIBRARY_PATH" ./gradlew :llmedge:testDebugUnitTest --tests "*BarkLinuxE2ETest*" --no-daemon ``` -------------------------------- ### Configure Reasoning Controls Source: https://github.com/aatricks/llmedge/blob/main/README.md Disable thinking mode and set reasoning budgets for models that support reasoning-aware generation. ```kotlin val edge = LLMEdge.create(context, viewModelScope) val reply = edge.text.generate( prompt = "Solve this step by step, then give only the final answer.", options = TextModelOptions( thinkingMode = SmolLM.ThinkingMode.DISABLED, reasoningBudget = 0, ), ) ``` -------------------------------- ### Check Device Compatibility in Kotlin Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Verifies device RAM before loading models to prevent crashes on low-memory hardware. ```kotlin fun checkDeviceCompatibility(context: Context): Boolean { val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val memInfo = ActivityManager.MemoryInfo() activityManager.getMemoryInfo(memInfo) val totalRamGB = memInfo.totalMem / (1024.0 * 1024.0 * 1024.0) if (totalRamGB < 12.0) { Log.w("VideoGen", "Insufficient RAM: ${String.format("%.1f", totalRamGB)}GB (12GB required)") return false } return true } // Usage if (!checkDeviceCompatibility(this)) { showErrorDialog( "Video generation requires 12GB+ RAM. " + "This device has ${String.format("%.1f", totalRamGB)}GB. " + "Consider using cloud inference APIs instead." ) return } // Proceed with model loading ``` -------------------------------- ### Check Video Model Capability Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Method to verify if the currently loaded model supports video generation. ```kotlin fun isVideoModel(): Boolean ``` -------------------------------- ### Enable EasyCache for StableDiffusion Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Configure EasyCache parameters within VideoGenerateParams to reuse intermediate diffusion steps for supported DiT models. ```kotlin val params = VideoGenerateParams( // ... other params easyCacheParams = StableDiffusion.EasyCacheParams( enabled = true, reuseThreshold = 0.2f, // Threshold for skipping steps (0.0 - 1.0) startPercent = 0.15f, // Start skipping after this percentage of steps endPercent = 0.95f // Stop skipping before this percentage of steps ) ) ``` -------------------------------- ### LLMEdge High-Level Facade Source: https://github.com/aatricks/llmedge/blob/main/docs/usage.md Methods for initializing the high-level LLMEdge facade and performing core text generation tasks. ```APIDOC ## LLMEdge.create(...) ### Description Creates the instance-based high-level facade for interacting with LLMEdge services. ## edge.text.generate(...) ### Description Performs high-level text generation. ## edge.text.stream(...) ### Description Performs high-level text streaming with optional batch size configuration. ``` -------------------------------- ### Scheduler Algorithm Selection Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Choosing the diffusion scheduler algorithm to influence quality, speed, and determinism. ```kotlin // Default scheduler = Scheduler.EULER_A // Deterministic scheduler = Scheduler.DDIM // Quality-focused scheduler = Scheduler.DDPM ``` -------------------------------- ### Configure text generation parameters Source: https://github.com/aatricks/llmedge/blob/main/docs/usage.md Customizes generation performance by specifying token limits, batch sizes, and thread counts for prompt and generation phases. ```kotlin val response = edge.text.generate( prompt = "Summarize the latest release notes.", maxTokens = 256, batchSize = 12, options = TextModelOptions( numThreads = 8, // prompt/batch processing generationThreads = 3, // single-token generation ), ) ``` -------------------------------- ### ModelPresets Source: https://github.com/aatricks/llmedge/blob/main/docs/usage.md Utilize built-in model presets for optimized performance on low-end devices. ```APIDOC ## ModelPresets ### Description Access ready-to-use model specifications for LLM generation and vision analysis. ### Usage ```kotlin // LLM Generation val reply = edge.text.generate(prompt = "Hi", model = ModelPresets.bitnet) // Vision Analysis val caption = edge.vision.analyze( image = bitmap, prompt = "Describe this image.", model = ModelPresets.smolVlm2.model, projector = ModelPresets.smolVlm2.projector, ) ``` ``` -------------------------------- ### Expert API Usage Source: https://github.com/aatricks/llmedge/blob/main/README.md Directly manages model downloads and low-level runtime components for advanced control. ```kotlin // Direct model download when you need full control over artifact selection. val download = HuggingFaceHub.ensureModelOnDisk( context = context, modelId = "unsloth/Qwen3-0.6B-GGUF", filename = "Qwen3-0.6B-Q4_K_M.gguf", ) // Expert text runtime with live reasoning-state control. val smol = SmolLM() smol.load(download.file.absolutePath) smol.setThinkingEnabled(false) // Expert RAG wiring when you want to own both the runtime and the pipeline yourself. val ragEngine = RAGEngine(context = context, smolLM = smol) ``` -------------------------------- ### Run unit tests for llmedge Source: https://github.com/aatricks/llmedge/blob/main/AGENTS.md Executes the unit test suite while skipping end-to-end tests, requiring a specific JAVA_HOME path. ```bash LLMEDGE_SKIP_E2E_IN_UNIT=true JAVA_HOME="/Applications/Android Studio.app/Contents/jbr/Contents/Home" ./gradlew :llmedge:testDebugUnitTest ``` -------------------------------- ### Prefetch Models Source: https://github.com/aatricks/llmedge/blob/main/README.md Download and cache model weights independently of inference using the model repository. ```kotlin val edge = LLMEdge.create(context, viewModelScope) val modelFile = edge.models.prefetch( ModelSpec.huggingFace( repoId = "unsloth/Qwen3-0.6B-GGUF", filename = "Qwen3-0.6B-Q4_K_M.gguf", ), ) Log.d("llmedge", "Cached ${modelFile.name} at ${modelFile.parent}") ``` -------------------------------- ### Define Video Generation Parameters Source: https://github.com/aatricks/llmedge/blob/main/docs/video-generation-api.md Data class defining configuration for video generation, including frame count, dimensions, and LoRA settings. ```kotlin data class VideoGenerateParams( val prompt: String, val videoFrames: Int = 16, val width: Int = 512, val height: Int = 512, val steps: Int = 20, val cfgScale: Double = 7.0, val seed: Long = -1, val scheduler: Scheduler = Scheduler.EULER_A, val strength: Float = 0.8f, val initImage: Bitmap? = null, val easyCacheParams: EasyCacheParams = EasyCacheParams(), // Parameters for EasyCache optimization val loraModelDir: String? = null, // Directory containing LoRA .safetensors (only applicable if also loading base model with LoRA support) val loraApplyMode: StableDiffusion.LoraApplyMode = StableDiffusion.LoraApplyMode.AUTO // LoRA application strategy ) ```