openassistant: drop siglip embedding service and onnxruntime
- Commit
1073d4e2e12c799e61f1b35be339edadfb4134ce- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-27 01:46 UTC (1 month ago)
- Parents
41f1998
Diff
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 203489de82..d20091c6d4 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -128,9 +128,6 @@ chicory = "1.4.0" # Git jgit = "7.8.0.202609011348-r" -# On-device AI (openassistant: SigLIP2 ONNX embeddings)-onnxruntimeAndroid = "1.31.0"- # Crypto, security & credential storage sqlcipherAndroid = "4.19.1" sqldelight = "2.2.0"@@ -337,9 +334,6 @@ chicory-runtime = { module = "com.dylibso.chicory:runtime", version.ref = "chico # Git jgit = { module = "org.eclipse.jgit:org.eclipse.jgit", version.ref = "jgit" } -# On-device AI (openassistant: SigLIP2 ONNX embeddings)-onnxruntime-android = { module = "com.microsoft.onnxruntime:onnxruntime-android", version.ref = "onnxruntimeAndroid" }- # Crypto, security & credential storage sqlcipher-android = { module = "net.zetetic:sqlcipher-android", version.ref = "sqlcipherAndroid" } jna = { module = "net.java.dev.jna:jna", version.ref = "jna" }
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.ktindex 99a1b779f6..52cf358431 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt@@ -12,45 +12,9 @@ import java.io.File * Mirror contents (path = file served under MIRROR_BASE): * models/gemma4/gemma4_text.maml, gemma4_embed.maml, gemma4_head.maml, * gemma4_vision.maml, gemma4_audio.maml, gemma4_tokenizer.spm1- * models/siglip2_vision_model_fp16.onnx- * models/siglip2_text_model_int8.onnx- * models/siglip2_tokenizer.model */ object ModelUrls { const val MIRROR_BASE = "https://data.maproj.org/models/"- // On-disk file names (also the mirror path for the SigLIP2 files).- const val SIGLIP_VISION_FILE = "siglip2_vision_model_fp16.onnx"- const val SIGLIP_TEXT_FILE = "siglip2_text_model_int8.onnx"- const val SIGLIP_TOKENIZER_FILE = "siglip2_tokenizer.model"- // Mirror download URLs.- const val SIGLIP_VISION_URL = "${MIRROR_BASE}siglip2_vision_model_fp16.onnx"- const val SIGLIP_TEXT_URL = "${MIRROR_BASE}siglip2_text_model_int8.onnx"- const val SIGLIP_TOKENIZER_URL = "${MIRROR_BASE}siglip2_tokenizer.model"- // SHA-256 integrity checks (verified against the files uploaded to the mirror).- const val SIGLIP_VISION_SHA256 = "a1959f7bd3993a607e48839f6d01e25b876fe76afda301b028b78eef68aabd95"- const val SIGLIP_TEXT_SHA256 = "3a0603d3a00c05a80a6ded4743c16aaac7b1e62cdcc7e362e7ce418659b96400"- const val SIGLIP_TOKENIZER_SHA256 = "61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2"- val SIGLIP_VISION = ModelDownloadItem(- SIGLIP_VISION_URL,- SIGLIP_VISION_FILE,- "Vision Model",- SIGLIP_VISION_SHA256- )- val SIGLIP_TEXT = ModelDownloadItem(- SIGLIP_TEXT_URL,- SIGLIP_TEXT_FILE,- "Text Model",- SIGLIP_TEXT_SHA256- )- val SIGLIP_TOKENIZER =- ModelDownloadItem(- SIGLIP_TOKENIZER_URL,- SIGLIP_TOKENIZER_FILE,- "Tokenizer",- SIGLIP_TOKENIZER_SHA256- )- /** SigLIP2 semantic-search models fetched on demand by the photos app. */- val SIGLIP = listOf(SIGLIP_VISION, SIGLIP_TEXT, SIGLIP_TOKENIZER) /** * Gemma 4 E2B for `:library:ml`'s maml runtime (`Gemma4Handle` and its vision and audio@@ -112,8 +76,8 @@ object ModelUrls { } } - /** Everything downloaded on OpenAssistant first launch (Gemma + SigLIP2). */- val INITIAL = GemmaMaml.FILES + SIGLIP+ /** Everything downloaded on OpenAssistant first launch. */+ val INITIAL = GemmaMaml.FILES } /** A single model file fetched from the self-hosted mirror, with optional SHA-256. */ data class ModelDownloadItem(
library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/ModelUrlsTest.kt
diff --git a/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/ModelUrlsTest.kt b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/ModelUrlsTest.ktindex 302578728f..eac056ce4a 100644--- a/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/ModelUrlsTest.kt+++ b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/ModelUrlsTest.kt@@ -14,17 +14,9 @@ class ModelUrlsTest { private val shaShape = Regex("[0-9a-f]{64}") - private fun allUrls() = ModelUrls.GemmaMaml.FILES.map { it.url } + listOf(- ModelUrls.SIGLIP_VISION_URL,- ModelUrls.SIGLIP_TEXT_URL,- ModelUrls.SIGLIP_TOKENIZER_URL,- )+ private fun allUrls() = ModelUrls.GemmaMaml.FILES.map { it.url } - private fun allShas() = ModelUrls.GemmaMaml.FILES.map { it.sha256.orEmpty() } + listOf(- ModelUrls.SIGLIP_VISION_SHA256,- ModelUrls.SIGLIP_TEXT_SHA256,- ModelUrls.SIGLIP_TOKENIZER_SHA256,- )+ private fun allShas() = ModelUrls.GemmaMaml.FILES.map { it.sha256.orEmpty() } @Test fun mirror_base_is_https_and_ends_with_a_slash() {@@ -57,29 +49,8 @@ class ModelUrlsTest { } @Test- fun siglip_mirror_paths_match_their_on_disk_file_names() {- assertEquals(ModelUrls.SIGLIP_VISION_FILE, ModelUrls.SIGLIP_VISION_URL.removePrefix(ModelUrls.MIRROR_BASE))- assertEquals(ModelUrls.SIGLIP_TEXT_FILE, ModelUrls.SIGLIP_TEXT_URL.removePrefix(ModelUrls.MIRROR_BASE))- assertEquals(- ModelUrls.SIGLIP_TOKENIZER_FILE,- ModelUrls.SIGLIP_TOKENIZER_URL.removePrefix(ModelUrls.MIRROR_BASE),- )- }-- @Test- fun siglip_bundle_holds_the_three_search_models() {- assertEquals(3, ModelUrls.SIGLIP.size)- assertEquals(- listOf(ModelUrls.SIGLIP_VISION, ModelUrls.SIGLIP_TEXT, ModelUrls.SIGLIP_TOKENIZER),- ModelUrls.SIGLIP,- )- }-- @Test- fun initial_bundle_is_gemma_first_then_siglip_with_distinct_files() {- assertEquals(9, ModelUrls.INITIAL.size)- assertEquals(ModelUrls.GemmaMaml.FILES, ModelUrls.INITIAL.take(6))- assertEquals(ModelUrls.SIGLIP, ModelUrls.INITIAL.drop(6))+ fun initial_bundle_is_the_gemma_set_with_distinct_files() {+ assertEquals(ModelUrls.GemmaMaml.FILES, ModelUrls.INITIAL) val files = ModelUrls.INITIAL.map { it.fileName } assertEquals(files.size, files.toSet().size, "duplicate on-disk file names would overwrite each other") }@@ -101,13 +72,14 @@ class ModelUrlsTest { @Test fun item_sha_defaults_to_null_for_unpinned_files() {- assertNull(ModelDownloadItem(ModelUrls.SIGLIP_TEXT_URL, ModelUrls.SIGLIP_TEXT_FILE, "Model").sha256)- assertEquals(ModelUrls.SIGLIP_TEXT_SHA256, ModelUrls.SIGLIP_TEXT.sha256)+ val tokenizer = ModelUrls.GemmaMaml.FILES.last()+ assertNull(ModelDownloadItem(tokenizer.url, tokenizer.fileName, "Model").sha256) } @Test fun items_compare_by_value() {- assertEquals(ModelUrls.SIGLIP_TEXT, ModelUrls.SIGLIP_TEXT.copy())- assertFalse(ModelUrls.SIGLIP_TEXT == ModelUrls.SIGLIP_TEXT.copy(url = "${ModelUrls.MIRROR_BASE}other.bin"))+ val tokenizer = ModelUrls.GemmaMaml.FILES.last()+ assertEquals(tokenizer, tokenizer.copy())+ assertFalse(tokenizer == tokenizer.copy(url = "${ModelUrls.MIRROR_BASE}other.bin")) } }
openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex 5a8e5071ab..abbe29eda6 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -15,13 +15,13 @@ _Install: ./install openassistant (dev by default)._ **Purpose:** A simple open-source local AI app — Gemma 4 E2B runs fully on device (~3.5GB RAM when active). Internet only for initial asset downloads. **Key features:** - Multiple chats with streaming responses and markdown rendering, persisted in Room-- Multimodal input: photo upload (SigLIP embeddings) and audio recording+- Multimodal input: photo upload and audio recording, read by Gemma 4's vision and audio towers - Tool calling into other Modern Apps over local IPC, with JSON-schema validation - A model-managed memory plus an editable system prompt; can be set as the device's default digital assistant (Assist API + voice interaction service) **Architecture / data-flow:** `ui/LiteRTChatUi` → `util/AssistantViewModel` → `data/OpenAssistantRepository` (Room) + `util/InferenceService` → `platform/MamlChatEngine` (Gemma 4 on `:library:ml`'s `Gemma4Handle`; own tool loop, max 6 rounds) with `platform/AssistantTools` (explicit registry over `domain/AssistantToolSpecs`) dispatching IPC tool calls. Pure logic (tool-call parsing/markup stripping, tool loop, WAV decode, history fitting) lives in `domain/` with unit tests. `onCreateBeforeContent` only wires the `IntentLauncher` and picks up Assist-API screen context; `Content()` gates on the initial model download before the chat renders. **Entry points + reading order:** `Route` (`ConversationPage(id)` / `SettingsPage`, inline) → `MainActivity.kt` → `ui/LiteRTChatUi.kt` → `util/AssistantViewModel.kt` → `util/InferenceService.kt` → `platform/MamlChatEngine.kt` → `data/OpenAssistantRepository.kt`. **Gotchas:**-- Card drift fixed: `ui/` files were renamed `Assistant*` → `LiteRT*` and `util/` gained `AssistantDeviceTools`, `AssistantToolIntents`, `InferenceEmbeddingHandler`, `JsonSchemaValidator`, `SentencePieceTokenizer`, `SiglipEmbedder`; `Gemma4Engine`/`Gemma4EtEngine` no longer exist+- Card drift fixed: `ui/` files were renamed `Assistant*` → `LiteRT*` and `util/` gained `AssistantDeviceTools`, `AssistantToolIntents`, `JsonSchemaValidator`; `Gemma4Engine`/`Gemma4EtEngine` no longer exist - `MainActivity.intentLauncher` is a shared static other apps mirror (maps/taxi pattern) — keep it initialized in `onCreateBeforeContent` - `StubRecognitionService` is a placeholder voice-recognition hook, not a real recognizer - Tool names are snake_case (`get_notes`, `add_to_memory`), matching what LiteRT-LM exposed; the system prompt references them. Add a tool in `domain/AssistantToolSpecs.kt` AND `platform/AssistantTools.kt` (an init check fails if they disagree)@@ -58,9 +58,6 @@ _Install: ./install openassistant (dev by default)._ - com/vayunmathur/openassistant/util/AssistantViewModel.kt - com/vayunmathur/openassistant/util/AssistantUiContract.kt - com/vayunmathur/openassistant/util/InferenceService.kt-- com/vayunmathur/openassistant/util/InferenceEmbeddingHandler.kt-- com/vayunmathur/openassistant/util/SentencePieceTokenizer.kt-- com/vayunmathur/openassistant/util/SiglipEmbedder.kt - com/vayunmathur/openassistant/util/AssistantToolIntents.kt - com/vayunmathur/openassistant/util/AssistantDeviceTools.kt - com/vayunmathur/openassistant/util/JsonSchemaValidator.kt
openassistant/build.gradle.kts
diff --git a/openassistant/build.gradle.kts b/openassistant/build.gradle.ktsindex bfd7f17caf..df44de70a7 100644--- a/openassistant/build.gradle.kts+++ b/openassistant/build.gradle.kts@@ -15,13 +15,6 @@ android { applicationId = "com.vayunmathur.openassistant" } - androidResources {- // SigLIP2 .onnx encoders are downloaded to external files at runtime,- // but the SentencePiece tokenizer.model is downloaded too; keep .onnx- // uncompressed for consistency with the ONNX Runtime memory-mapped read.- noCompress += "onnx"- }- packaging { jniLibs { pickFirsts.add("**/libc++_shared.so")@@ -45,9 +38,6 @@ dependencies { // Gemma 4 chat runs on `:library:ml`'s Vulkan runtime (Gemma4Handle). implementation(project(":library:ml")) implementation(libs.kotlinx.coroutines.android)- // SigLIP2 image/text embedding (semantic photo search served to the photos- // app) runs on ONNX Runtime.- implementation(libs.onnxruntime.android) implementation(project(":library:downloadservice")) }
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.ktindex 2c43f83a93..594ab8aaef 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt@@ -235,41 +235,30 @@ class AssistantViewModel( audioRecorder = null } - /**- * Version the on-demand SigLIP2 model files: if [SiglipEmbedder.MODEL_VERSION]- * changed since we last downloaded them, delete the stale files and clear the- * downloadservice `dlid_`/`progress_` keys so they re-download on the next- * embedding request. Unlike the gemma path this never touches- * `dbSetupComplete` — SigLIP2 is optional and fetched on demand.- */+ /** Deletes the SigLIP2 files and their download records left by versions that served image search. */ private fun cleanupStaleSiglipModels() { val context = getApplication<Application>() viewModelScope.launch(Dispatchers.IO) { try { val ds = DataStoreUtils.getInstance(context)- val stored = ds.getLong("siglip_model_version") ?: 0L- if (stored == SiglipEmbedder.MODEL_VERSION.toLong()) return@launch- val externalDir = context.getExternalFilesDir(null)- val files = listOf(- SiglipEmbedder.VISION_FILE,- SiglipEmbedder.TEXT_FILE,- SiglipEmbedder.TOKENIZER_FILE,- )- for (name in files) {- externalDir?.let { File(it, name).takeIf { f -> f.exists() }?.delete() }- ds.setLong("dlid_$name", 0L)- ds.setDouble("progress_$name", 0.0)+ for (name in LEGACY_SIGLIP_FILES) {+ externalDir?.let { File(it, name).delete(); File(it, "$name.part").delete() } }- ds.setLong("siglip_model_version", SiglipEmbedder.MODEL_VERSION.toLong())+ ds.removeKeys(LEGACY_SIGLIP_FILES.map { "dlid_$it" } + "siglip_model_version") } catch (expected: Exception) {- Log.error(TAG, "Error cleaning up stale SigLIP2 model files", expected)+ Log.error(TAG, "Error deleting legacy SigLIP2 model files", expected) } } } companion object { private const val TAG = "AssistantViewModel"+ private val LEGACY_SIGLIP_FILES = listOf(+ "siglip2_vision_model_fp16.onnx",+ "siglip2_text_model_int8.onnx",+ "siglip2_tokenizer.model",+ ) } }
openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceEmbeddingHandler.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceEmbeddingHandler.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceEmbeddingHandler.ktdeleted file mode 100644index 53e39945da..0000000000--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceEmbeddingHandler.kt+++ /dev/null@@ -1,156 +0,0 @@-package com.vayunmathur.openassistant.util--import android.content.Context-import android.os.Bundle-import android.os.ResultReceiver-import com.vayunmathur.library.log.Log-import com.vayunmathur.library.downloadservice.ModelUrls-import com.vayunmathur.library.downloadservice.downloadModels-import com.vayunmathur.library.util.DataStoreUtils-import java.io.File-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Job-import kotlinx.coroutines.isActive-import kotlinx.coroutines.launch--/**- * SigLIP2 embedding queue consumer for [InferenceService]. Owns the- * on-demand model download and the text/image/info dispatch so the service- * class stays under the TooManyFunctions limit.- */-internal class InferenceEmbeddingHandler(- private val context: Context,- private val scope: CoroutineScope,-) {- @Volatile private var downloadJob: Job? = null-- fun isDownloadActive(): Boolean = downloadJob?.isActive == true-- suspend fun process(job: InferenceService.InferenceJobPublic.Embedding) {- // Models are downloaded on demand; until all three files are present,- // report "downloading" (code 2) with aggregate progress and retry later.- if (!SiglipEmbedder.filesPresent(context)) {- startModelDownloadIfNeeded()- job.receiver.send(- InferenceService.EMBEDDING_DOWNLOADING_CODE,- Bundle().apply {- putString("status", "downloading")- putDouble("progress", currentDownloadProgress())- },- )- return- }-- if (!SiglipEmbedder.isAvailable(context)) {- job.receiver.send(- InferenceService.EMBEDDING_ERROR_CODE,- Bundle().apply { putString("error", "Embedder failed to load") },- )- return- }-- when (job.mode) {- "info" -> sendInfo(job)- "text" -> sendText(job)- "image" -> sendImage(job)- else -> job.receiver.send(- InferenceService.EMBEDDING_ERROR_CODE,- Bundle().apply { putString("error", "Unknown embed_mode ${job.mode}") },- )- }- }-- fun reportError(job: InferenceService.InferenceJobPublic.Embedding, expected: Exception) {- try {- job.receiver.send(- InferenceService.EMBEDDING_ERROR_CODE,- Bundle().apply {- putString("error", expected.localizedMessage ?: "Embedding failed")- },- )- } catch (ignored: Exception) {- Log.error("InferenceService", "Failed to report embedding error", ignored)- }- }-- private fun sendInfo(job: InferenceService.InferenceJobPublic.Embedding) {- job.receiver.send(- InferenceService.EMBEDDING_OK_CODE,- Bundle().apply {- putString("model_id", SiglipEmbedder.MODEL_ID)- putInt("dim", SiglipEmbedder.dim(context))- putString("status", "ready")- },- )- }-- private fun sendText(job: InferenceService.InferenceJobPublic.Embedding) {- val t0 = System.currentTimeMillis()- val emb = SiglipEmbedder.textEmbedding(context, job.userText)- Log.status(- "InferenceService",- "Text embed (${emb?.size ?: 0}d) in " +- "${System.currentTimeMillis() - t0}ms ok=${emb != null}",- )- sendEmbedding(job.receiver, emb)- }-- private fun sendImage(job: InferenceService.InferenceJobPublic.Embedding) {- val path = job.imagePath- val t0 = System.currentTimeMillis()- val emb = if (path != null) SiglipEmbedder.imageEmbedding(context, File(path)) else null- Log.status(- "InferenceService",- "Image embed (${emb?.size ?: 0}d) in " +- "${System.currentTimeMillis() - t0}ms ok=${emb != null} path=$path",- )- sendEmbedding(job.receiver, emb)- // The temp copy from copyUriToFile is no longer needed.- if (path != null) runCatching { File(path).delete() }- }-- private fun sendEmbedding(receiver: ResultReceiver, emb: FloatArray?) {- if (emb == null) {- // Provider is up but this specific item couldn't be embedded; mark it- // per_item so the client skips just this one rather than pausing.- receiver.send(- InferenceService.EMBEDDING_ERROR_CODE,- Bundle().apply {- putString("error", "Embedding failed")- putBoolean("per_item", true)- },- )- } else {- receiver.send(- InferenceService.EMBEDDING_OK_CODE,- Bundle().apply {- putByteArray("embedding", SiglipEmbedder.floatsToBytes(emb))- putString("model_id", SiglipEmbedder.MODEL_ID)- putInt("dim", emb.size)- },- )- }- }-- private fun startModelDownloadIfNeeded() {- if (downloadJob?.isActive == true) return- downloadJob = scope.launch {- try {- val ds = DataStoreUtils.getInstance(context)- downloadModels(context, ds, ModelUrls.SIGLIP)- } catch (expected: Exception) {- Log.error("InferenceService", "SigLIP2 model download failed", expected)- }- }- }-- private fun currentDownloadProgress(): Double {- val ds = DataStoreUtils.getInstance(context)- val files = listOf(- SiglipEmbedder.VISION_FILE,- SiglipEmbedder.TEXT_FILE,- SiglipEmbedder.TOKENIZER_FILE,- )- return files.sumOf { ds.getDouble("progress_$it") ?: 0.0 } / files.size- }-}
openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.ktindex ceaf3af096..957cdecc23 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -55,9 +55,8 @@ class InferenceService : Service() { /** DataStore key holding the user-editable chat system prompt. */ const val KEY_SYSTEM_PROMPT = "system_prompt"- internal const val EMBEDDING_ERROR_CODE = -1- internal const val EMBEDDING_DOWNLOADING_CODE = 2- internal const val EMBEDDING_OK_CODE = 0+ private const val RESULT_ERROR_CODE = -1+ private const val RESULT_OK_CODE = 0 private const val INTENT_TIMEOUT_MILLIS = 45000L private const val INTENT_QUEUE_TTL_MILLIS = 45000L private const val HISTORY_RECENCY_MILLIS = 1000L@@ -97,38 +96,11 @@ class InferenceService : Service() { val imagePaths: Array<String>, val audioPath: String?, ) : InferenceJob()-- /**- * A SigLIP2 embedding request from another app (photos). [mode] is- * "text", "image", or "info". Runs on [SiglipEmbedder], independent of- * the chat [MamlChatEngine], so it can be served while the LLM is busy.- */- data class Embedding(- val mode: String,- val userText: String,- val imagePath: String?,- val receiver: ResultReceiver,- ) : InferenceJob()- }-- /** Public aliases so [InferenceEmbeddingHandler] can consume the queue types. */- object InferenceJobPublic {- data class Embedding(- val mode: String,- val userText: String,- val imagePath: String?,- val receiver: ResultReceiver,- ) } private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val standardQueue = Channel<InferenceJob.Standard>(Channel.UNLIMITED) private val intentQueue = Channel<InferenceJob.Intent>(Channel.UNLIMITED)- private val embeddingQueue = Channel<InferenceJobPublic.Embedding>(Channel.UNLIMITED)-- private val embeddingHandler by lazy {- InferenceEmbeddingHandler(applicationContext, serviceScope)- } private var engine: MamlChatEngine? = null private val engineLock = Mutex()@@ -146,7 +118,6 @@ class InferenceService : Service() { startForegroundTask() launchPrewarm() launchJobLoop()- launchEmbeddingLoop() } private fun launchPrewarm() {@@ -191,24 +162,6 @@ class InferenceService : Service() { return false } - // Embeddings run on their own consumer so they don't wait behind the- // (possibly long) chat/intent LLM jobs — they use SiglipEmbedder, not the- // chat engine.- private fun launchEmbeddingLoop() {- serviceScope.launch {- for (job in embeddingQueue) {- try {- embeddingHandler.process(job)- } catch (e: CancellationException) {- throw e- } catch (expected: Exception) {- Log.error("InferenceService", "Error processing embedding job", expected)- embeddingHandler.reportError(job, expected)- }- }- }- }- override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { Log.debug("InferenceService", "onStartCommand received intent") if (intent == null) return START_STICKY@@ -218,7 +171,6 @@ class InferenceService : Service() { val userText = intent.getStringExtra("user_text") ?: "" val audioPath = intent.getStringExtra("audio_path") val schema = intent.getStringExtra("schema")- val embedMode = intent.getStringExtra("embed_mode") val receiver = IntentCompat.getParcelableExtra(intent, "RECEIVER", ResultReceiver::class.java) val imageUris = IntentCompat.getParcelableArrayListExtra(intent, "image_uris", Uri::class.java)@@ -231,18 +183,7 @@ class InferenceService : Service() { val imagePaths = staticImagePaths + imagePathsFromUris - if (embedMode != null && receiver != null) {- // Embedding request from another app (photos): text/image/info.- Log.status("InferenceService", "Queueing Embedding request mode=$embedMode")- embeddingQueue.trySend(- InferenceJobPublic.Embedding(- embedMode,- userText,- imagePaths.firstOrNull(),- receiver,- ),- )- } else if (receiver != null && schema != null) {+ if (receiver != null && schema != null) { Log.status("InferenceService", "Queueing Intent Inference request") intentQueue.trySend(InferenceJob.Intent(userText, imagePaths, schema, receiver)) } else if (conversationId != -1L) {@@ -296,7 +237,7 @@ class InferenceService : Service() { } catch (e: TimeoutCancellationException) { Log.error("InferenceService", "Intent inference timed out after 45 seconds") job.receiver.send(- EMBEDDING_ERROR_CODE,+ RESULT_ERROR_CODE, Bundle().apply { putString("error", getString(R.string.error_inference_timeout)) }, ) } catch (e: CancellationException) {@@ -304,7 +245,7 @@ class InferenceService : Service() { } catch (expected: Exception) { Log.error("InferenceService", "Error during intent inference", expected) job.receiver.send(- EMBEDDING_ERROR_CODE,+ RESULT_ERROR_CODE, Bundle().apply { putString( "error",@@ -319,7 +260,7 @@ class InferenceService : Service() { if (System.currentTimeMillis() - job.enqueuedTime > INTENT_QUEUE_TTL_MILLIS) { Log.status("InferenceService", "Intent job expired in queue, discarding.") job.receiver.send(- EMBEDDING_ERROR_CODE,+ RESULT_ERROR_CODE, Bundle().apply { putString("error", getString(R.string.error_request_expired)) }, ) } else {@@ -327,9 +268,6 @@ class InferenceService : Service() { } } - // ---------- SigLIP2 embedding provider (served to the photos app) ----------- // Dispatch lives in [InferenceEmbeddingHandler]; queue types are public aliases above.- private suspend fun loadHistory(conversationId: Long, userText: String): List<HistoryTurn> { val cutoff = Clock.System.now().toEpochMilliseconds() - HISTORY_RECENCY_MILLIS return fetchHistoryFromDb(conversationId)@@ -404,7 +342,7 @@ class InferenceService : Service() { val candidate = tryExtractLargestJson(text) if (candidate != null && JsonSchemaValidator.validateJsonAgainstSchema(candidate, schema) == null) { Log.status("InferenceService", "Valid JSON extracted and verified against schema. Halting.")- receiver.send(EMBEDDING_OK_CODE, Bundle().apply { putString("json_result", candidate) })+ receiver.send(RESULT_OK_CODE, Bundle().apply { putString("json_result", candidate) }) sent = true false } else {@@ -417,14 +355,14 @@ class InferenceService : Service() { val finalJson = tryExtractLargestJson(reply) if (finalJson != null && JsonSchemaValidator.validateJsonAgainstSchema(finalJson, schema) == null) {- receiver.send(EMBEDDING_OK_CODE, Bundle().apply { putString("json_result", finalJson) })+ receiver.send(RESULT_OK_CODE, Bundle().apply { putString("json_result", finalJson) }) Log.dev("InferenceService", "AI produced output: $finalJson") return } Log.error("InferenceService", "AI finished generation without providing a schema-matching JSON.") receiver.send(- EMBEDDING_ERROR_CODE,+ RESULT_ERROR_CODE, Bundle().apply { putString("error", getString(R.string.error_ai_json_schema_mismatch)) }, ) }
openassistant/src/main/java/com/vayunmathur/openassistant/util/SentencePieceTokenizer.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/SentencePieceTokenizer.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/SentencePieceTokenizer.ktdeleted file mode 100644index bcab56ed90..0000000000--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/SentencePieceTokenizer.kt+++ /dev/null@@ -1,353 +0,0 @@-package com.vayunmathur.openassistant.util--import com.vayunmathur.library.log.Log-import java.io.File-import java.nio.ByteBuffer-import java.nio.ByteOrder-import java.text.Normalizer-import kotlin.math.min--/**- * Minimal, dependency-free **SentencePiece Unigram** tokenizer for the Gemma- * SentencePiece model (`tokenizer.model`, ~4 MB, 256k vocab) that SigLIP2 uses- * for its text tower.- *- * We need raw token ids to feed SigLIP2's text ONNX model with SigLIP2's own- * vocabulary, so this is a standalone re-implementation of the- * two pieces we actually need:- *- * 1. **Model parsing** ([load]): the `.model` file is a serialized- * `sentencepiece.ModelProto`. We hand-parse just the repeated `pieces`- * (field 1) — each a `SentencePiece{ piece=1:string, score=2:float,- * type=3:enum }` — because pulling in a protobuf runtime for three fields is- * overkill. Piece **index == token id**.- * 2. **Encoding** ([encode]): Viterbi best-path Unigram segmentation over the- * normalized text, with **byte fallback** (Gemma enables it and ships all- * 256 `<0xNN>` byte pieces) so every input is representable.- *- * ## SigLIP2 text preprocessing (flagged review risk)- *- * The exact normalization SigLIP2 applies is the highest-uncertainty part of the- * photos→OpenAssistant embedding move (see the plan's "Key risks"). We apply the- * documented SigLIP convention — lowercase, NFKC, whitespace-collapse, a- * SentencePiece dummy-prefix space, and pad/truncate to [SEQ_LEN] with the pad- * id — and keep every knob a named constant so it is easy to retune against the- * reference `transformers` `Siglip2Processor` output. Image and text vectors- * only line up if this matches, so this is the first thing to verify.- */-class SentencePieceTokenizer private constructor(- private val pieceToId: HashMap<String, Int>,- private val scores: FloatArray,- private val byteToId: IntArray, // 256 entries, -1 if absent- private val maxPieceLen: Int,- val unkId: Int,- val padId: Int,-) {-- companion object {- private const val TAG = "SentencePieceTokenizer"-- /** SentencePiece meta symbol standing in for a space (U+2581, "▁"). */- private const val SPACE = '\u2581'-- /** SigLIP2 text tower fixed context length (padded/truncated). */- const val SEQ_LEN = 64-- // SentencePiece piece types (sentencepiece_model.proto).- private const val TYPE_NORMAL = 1- private const val TYPE_UNKNOWN = 2- private const val TYPE_CONTROL = 3- private const val TYPE_USER_DEFINED = 4- private const val TYPE_BYTE = 6-- private const val BYTE_ALPHABET = 256- private const val GEMMA_DEFAULT_UNK_ID = 3- private const val GEMMA_DEFAULT_PAD_ID = 0- private const val MAX_PIECE_LEN_CAP = 48- private const val HEX_RADIX = 16- private const val BYTE_MASK = 0xFF- private const val VARINT_CONTINUATION = 0x80- private const val VARINT_PAYLOAD_MASK = 0x7F- private const val VARINT_SHIFT = 7- private const val WIRE_VARINT = 0- private const val WIRE_FIXED64 = 1- private const val WIRE_LENGTH_DELIMITED = 2- private const val WIRE_FIXED32 = 5- private const val FIELD_PIECE = 1- private const val FIELD_SCORE = 2- private const val FIELD_TYPE = 3- private const val FLOAT_BYTES = 4- private const val FIXED64_BYTES = 8- private const val BYTE_PIECE_LEN = 6- private const val BYTE_HEX_START = 3- private const val BYTE_HEX_END = 5-- /**- * Parse a Gemma `tokenizer.model` file, or null if it can't be read.- * `padId`/`unkId` default to the Gemma special-token ids and are refined- * from the parsed pieces where possible.- */- fun load(modelFile: File): SentencePieceTokenizer? {- return try {- val bytes = modelFile.readBytes()- parse(bytes)- } catch (expected: Exception) {- Log.error(TAG, "Failed to load SentencePiece model ${modelFile.absolutePath}", expected)- null- }- }-- private fun parse(data: ByteArray): SentencePieceTokenizer {- val pieces = ArrayList<String>(256_000)- val scoreList = ArrayList<Float>(256_000)- val types = ArrayList<Int>(256_000)-- var pos = 0- val end = data.size- while (pos < end) {- val (tag, p1) = readVarint(data, pos)- pos = p1- val field = (tag ushr 3).toInt()- val wire = (tag and 0x7).toInt()- if (field == 1 && wire == 2) {- // pieces: length-delimited SentencePiece message.- val (len, p2) = readVarint(data, pos)- pos = p2- val msgEnd = pos + len.toInt()- parsePiece(data, pos, msgEnd, pieces, scoreList, types)- pos = msgEnd- } else {- pos = skipField(data, pos, wire)- }- }-- val n = pieces.size- val scoresArr = FloatArray(n) { scoreList[it] }- val pieceToId = HashMap<String, Int>(n * 2)- val byteToId = IntArray(BYTE_ALPHABET) { -1 }- var unkId = GEMMA_DEFAULT_UNK_ID- var padId = GEMMA_DEFAULT_PAD_ID- var maxLen = 1-- for (id in 0 until n) {- val piece = pieces[id]- when (types[id]) {- TYPE_UNKNOWN -> unkId = id- TYPE_BYTE -> {- val b = parseBytePiece(piece)- if (b in 0 until BYTE_ALPHABET) byteToId[b] = id- }- TYPE_CONTROL -> {- if (piece == "<pad>") padId = id- }- TYPE_NORMAL, TYPE_USER_DEFINED -> {- pieceToId[piece] = id- val cpLen = piece.codePointCount(0, piece.length)- if (cpLen > maxLen) maxLen = cpLen- }- }- }- // Cap the DP window; real Gemma pieces are short subwords.- maxLen = min(maxLen, MAX_PIECE_LEN_CAP)- Log.status(- TAG,- "Loaded SentencePiece: $n pieces, unkId=$unkId, padId=$padId, maxPieceLen=$maxLen",- )- return SentencePieceTokenizer(pieceToId, scoresArr, byteToId, maxLen, unkId, padId)- }-- private fun parsePiece(- data: ByteArray,- start: Int,- end: Int,- pieces: ArrayList<String>,- scores: ArrayList<Float>,- types: ArrayList<Int>,- ) {- var pos = start- var piece = ""- var score = 0f- var type = TYPE_NORMAL- while (pos < end) {- val (tag, p1) = readVarint(data, pos)- pos = p1- val field = (tag ushr VARINT_SHIFT).toInt()- val wire = (tag and VARINT_PAYLOAD_MASK.toLong()).toInt()- when {- field == FIELD_PIECE && wire == WIRE_LENGTH_DELIMITED -> {- val (len, p2) = readVarint(data, pos)- pos = p2- val l = len.toInt()- piece = String(data, pos, l, Charsets.UTF_8)- pos += l- }- field == FIELD_SCORE && wire == WIRE_FIXED32 -> {- score = ByteBuffer.wrap(data, pos, FLOAT_BYTES)- .order(ByteOrder.LITTLE_ENDIAN).float- pos += FLOAT_BYTES- }- field == FIELD_TYPE && wire == WIRE_VARINT -> {- val (t, p2) = readVarint(data, pos)- pos = p2- type = t.toInt()- }- else -> pos = skipField(data, pos, wire)- }- }- pieces.add(piece)- scores.add(score)- types.add(type)- }-- /** "<0x1F>" -> 31, else -1. */- private fun parseBytePiece(piece: String): Int {- if (piece.length == BYTE_PIECE_LEN &&- piece.startsWith("<0x") &&- piece.endsWith(">")- ) {- return piece.substring(BYTE_HEX_START, BYTE_HEX_END)- .toIntOrNull(HEX_RADIX) ?: -1- }- return -1- }-- private fun readVarint(data: ByteArray, start: Int): Pair<Long, Int> {- var result = 0L- var shift = 0- var pos = start- while (true) {- val b = data[pos].toInt() and BYTE_MASK- pos++- result = result or ((b and VARINT_PAYLOAD_MASK).toLong() shl shift)- if (b and VARINT_CONTINUATION == 0) break- shift += VARINT_SHIFT- }- return result to pos- }-- private fun skipField(data: ByteArray, start: Int, wire: Int): Int {- var pos = start- when (wire) {- WIRE_VARINT -> pos = readVarint(data, pos).second- WIRE_FIXED64 -> pos += FIXED64_BYTES- WIRE_LENGTH_DELIMITED -> {- val (len, p) = readVarint(data, pos)- pos = p + len.toInt()- }- WIRE_FIXED32 -> pos += FLOAT_BYTES- else -> throw IllegalStateException("Unsupported wire type $wire")- }- return pos- }- }-- /**- * Encode [text] into a fixed [SEQ_LEN]-long id array (SigLIP2 text input),- * padded with [padId] and truncated as needed.- */- fun encode(text: String): IntArray {- val ids = encodeVariable(text)- val out = IntArray(SEQ_LEN) { padId }- val take = min(ids.size, SEQ_LEN)- for (i in 0 until take) out[i] = ids[i]- return out- }-- /** Viterbi Unigram segmentation of the normalized text (no padding). */- private fun encodeVariable(text: String): IntArray {- val normalized = normalize(text)- if (normalized.isEmpty()) return IntArray(0)-- // Work over Unicode code points so multi-byte chars index cleanly.- val cps = normalized.codePoints().toArray()- val n = cps.size- val bestScore = DoubleArray(n + 1) { Double.NEGATIVE_INFINITY }- bestScore[0] = 0.0- val prev = IntArray(n + 1) { -1 }- val stepIds = arrayOfNulls<IntArray>(n + 1)-- for (i in 0 until n) {- if (bestScore[i] == Double.NEGATIVE_INFINITY) continue- relaxPieces(cps, n, i, bestScore, prev, stepIds)- relaxByteFallback(cps, i, bestScore, prev, stepIds)- }-- if (bestScore[n] == Double.NEGATIVE_INFINITY) {- // Should not happen with byte fallback; degrade to a single unk.- return intArrayOf(unkId)- }-- // Backtrack, collecting ids, then reverse.- val rev = ArrayList<Int>()- var pos = n- while (pos > 0) {- val ids = stepIds[pos] ?: intArrayOf(unkId)- for (k in ids.indices.reversed()) rev.add(ids[k])- pos = prev[pos]- }- rev.reverse()- return rev.toIntArray()- }-- private fun relaxPieces(- cps: IntArray,- n: Int,- i: Int,- bestScore: DoubleArray,- prev: IntArray,- stepIds: Array<IntArray?>,- ) {- // (a) Try every vocab piece starting at i.- val maxL = min(maxPieceLen, n - i)- val sb = StringBuilder()- for (l in 1..maxL) {- sb.appendCodePoint(cps[i + l - 1])- val id = pieceToId[sb.toString()] ?: continue- val sc = bestScore[i] + scores[id]- if (sc > bestScore[i + l]) {- bestScore[i + l] = sc- prev[i + l] = i- stepIds[i + l] = intArrayOf(id)- }- }- }-- private fun relaxByteFallback(- cps: IntArray,- i: Int,- bestScore: DoubleArray,- prev: IntArray,- stepIds: Array<IntArray?>,- ) {- // (b) Byte fallback for the single code point at i, so every- // position stays reachable even with no matching piece.- val ch = String(Character.toChars(cps[i]))- val chBytes = ch.toByteArray(Charsets.UTF_8)- val fallbackIds = IntArray(chBytes.size)- var fbScore = bestScore[i]- for (k in chBytes.indices) {- val bid = byteToId[chBytes[k].toInt() and BYTE_MASK]- if (bid < 0) return- fallbackIds[k] = bid- fbScore += scores[bid]- }- if (fbScore > bestScore[i + 1]) {- bestScore[i + 1] = fbScore- prev[i + 1] = i- stepIds[i + 1] = fallbackIds- }- }-- /**- * SigLIP text normalization: lowercase, NFKC, collapse whitespace, then the- * SentencePiece dummy-prefix space with spaces mapped to [SPACE] (▁).- */- private fun normalize(text: String): String {- val lowered = text.lowercase()- val nfkc = Normalizer.normalize(lowered, Normalizer.Form.NFKC)- val collapsed = nfkc.trim().replace(Regex("\\s+"), " ")- if (collapsed.isEmpty()) return ""- // Dummy prefix + space→▁ (SentencePiece convention).- return (" $collapsed").replace(' ', SPACE)- }-}
openassistant/src/main/java/com/vayunmathur/openassistant/util/SiglipEmbedder.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/SiglipEmbedder.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/SiglipEmbedder.ktdeleted file mode 100644index 20b107adc3..0000000000--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/SiglipEmbedder.kt+++ /dev/null@@ -1,335 +0,0 @@-package com.vayunmathur.openassistant.util--import ai.onnxruntime.OnnxTensor-import ai.onnxruntime.OrtEnvironment-import ai.onnxruntime.OrtSession-import android.content.Context-import android.graphics.Bitmap-import android.graphics.BitmapFactory-import com.vayunmathur.library.log.Log-import com.vayunmathur.library.downloadservice.ModelUrls-import java.io.File-import java.nio.ByteBuffer-import java.nio.ByteOrder-import java.nio.FloatBuffer-import java.nio.LongBuffer-import kotlin.math.sqrt--/**- * On-device **SigLIP2-base** image/text embedder on ONNX Runtime, the semantic- * search provider OpenAssistant serves to the photos app over [InferenceService].- *- * SigLIP puts images and text in one shared space: the image encoder turns a- * photo into a vector, the text encoder turns a query into a vector, and their- * cosine similarity says how well the phrase describes the photo. photos stores- * the returned vectors and does cosine locally.- *- * Mirrors the old on-device `photos/.../ClipEmbedder.kt` (lazy single-threaded- * [OrtSession]s, [OnnxTensor] + `run`, L2-normalize, [floatsToBytes]) but with- * SigLIP2 preprocessing and the Gemma [SentencePieceTokenizer]:- * - **Vision** ([VISION_FILE]): resize **directly** to [IMAGE_SIZE]² (square,- * no shortest-side + center-crop), rescale 1/255, normalize mean/std 0.5 →- * `(px-127.5)/127.5`, packed NCHW `[1,3,224,224]`.- * - **Text** ([TEXT_FILE]): tokenize with [SentencePieceTokenizer] to a fixed- * [SentencePieceTokenizer.SEQ_LEN] and run the text tower.- *- * The embedding [dim] is read from the model at run time (SigLIP2-base = 768)- * and flows back to photos via the IPC `dim` key, so nothing hardcodes it.- *- * The three model files are downloaded on demand to `getExternalFilesDir(null)`- * (see [InferenceService]); if any is missing [filesPresent] is false and the- * caller triggers the download instead.- */-object SiglipEmbedder {- /** HuggingFace source, also the model id photos uses for change-detection. */- const val MODEL_ID = "onnx-community/siglip2-base-patch16-224-ONNX"-- /**- * Bump when the downloaded SigLIP2 files or preprocessing change, so- * [com.vayunmathur.openassistant.util.AssistantViewModel] deletes the stale- * on-disk files and they re-download on the next embedding request.- */- const val MODEL_VERSION = 1-- // On-disk names shared with the mirror-first downloader (single source of- // truth in ModelUrls) so file-presence gating and the fetch always agree.- const val VISION_FILE = ModelUrls.SIGLIP_VISION_FILE- const val TEXT_FILE = ModelUrls.SIGLIP_TEXT_FILE- const val TOKENIZER_FILE = ModelUrls.SIGLIP_TOKENIZER_FILE-- /** Square RGB input side the SigLIP2 image encoder expects. */- const val IMAGE_SIZE = 224-- private const val TAG = "SiglipEmbedder"- private const val CHANNELS = 3- private const val PIXEL_MID = 127.5f- private const val CHANNEL_MASK = 0xFF- private const val RED_SHIFT = 16- private const val GREEN_SHIFT = 8- private const val FLOAT_BYTES = 4- private const val BATCH_DIM = 1L-- private val env: OrtEnvironment by lazy { OrtEnvironment.getEnvironment() }- private val lock = Any()-- @Volatile private var visionSession: OrtSession? = null- @Volatile private var textSession: OrtSession? = null- @Volatile private var tokenizer: SentencePieceTokenizer? = null- @Volatile private var visionOutputName: String? = null- @Volatile private var textOutputName: String? = null- @Volatile private var initTried = false- @Volatile private var initOk = false-- /** True only if all three model files are present on disk. */- fun filesPresent(context: Context): Boolean =- modelFile(context, VISION_FILE).exists() &&- modelFile(context, TEXT_FILE).exists() &&- modelFile(context, TOKENIZER_FILE).exists()-- /** True if both encoders + tokenizer are loaded and ready. */- fun isAvailable(context: Context): Boolean = ensureInit(context)-- /** Embedding dimension read from the vision model, or 0 if not initialised. */- fun dim(context: Context): Int {- if (!ensureInit(context)) return 0- return cachedDim- }-- @Volatile private var cachedDim = 0-- private fun modelFile(context: Context, name: String): File =- File(context.applicationContext.getExternalFilesDir(null), name)-- private fun ensureInit(context: Context): Boolean {- if (initOk) return true- synchronized(lock) {- if (initOk) return true- if (initTried) return false- initTried = true- return try {- val app = context.applicationContext- if (!filesPresent(app)) {- Log.status(TAG, "SigLIP2 model files missing; embedder unavailable")- initTried = false // allow a retry once files are downloaded- return false- }- val tok = SentencePieceTokenizer.load(modelFile(app, TOKENIZER_FILE)) ?: run {- Log.status(TAG, "Failed to load SentencePiece tokenizer")- return false- }- val opts = OrtSession.SessionOptions().apply {- // Single-threaded keeps sustained CPU/battery use low.- setIntraOpNumThreads(1)- setInterOpNumThreads(1)- }- visionSession = env.createSession(modelFile(app, VISION_FILE).absolutePath, opts)- textSession = env.createSession(modelFile(app, TEXT_FILE).absolutePath, opts)- tokenizer = tok- // These sub-model exports emit BOTH `last_hidden_state` and the- // pooled embedding (`pooler_output`); we must read the pooled one,- // not output index 0, or the vectors are meaningless.- visionOutputName = bestOutputName(visionSession!!)- textOutputName = bestOutputName(textSession!!)- cachedDim = visionSession?.let { readOutputDim(it, visionOutputName!!) } ?: 0- initOk = true- Log.status(- TAG,- "SigLIP2 embedder ready " +- "(dim=$cachedDim, visionOut=$visionOutputName, textOut=$textOutputName)",- )- true- } catch (expected: Throwable) {- Log.error(TAG, "Failed to initialise SigLIP2 embedder", expected)- closeLocked()- false- }- }- }-- /**- * Pick the output that holds the pooled embedding. SigLIP2's vision/text- * sub-model exports emit `last_hidden_state` (rank-3) plus the pooled- * `pooler_output` (rank-2 `[1, dim]`) — the latter is the retrieval vector.- * Prefer a name hinting "pool"/"embed", else the first rank-2 output, else- * output 0.- */- private fun bestOutputName(session: OrtSession): String {- val info = session.outputInfo- info.keys.firstOrNull { it.contains("pool", ignoreCase = true) }?.let { return it }- info.keys.firstOrNull { it.contains("embed", ignoreCase = true) }?.let { return it }- info.entries.firstOrNull { (it.value.info as? ai.onnxruntime.TensorInfo)?.shape?.size == 2 }- ?.let { return it.key }- return info.keys.first()- }-- private fun readOutputDim(session: OrtSession, outputName: String): Int {- return try {- val info = session.outputInfo[outputName]!!.info as ai.onnxruntime.TensorInfo- info.shape.last().toInt()- } catch (_: Exception) {- 0- }- }-- /**- * Embed the image at [file] into an L2-normalised vector, or null on- * failure. The file is a decoded copy handed over by [InferenceService].- */- fun imageEmbedding(context: Context, file: File): FloatArray? {- if (!ensureInit(context)) return null- val session = visionSession ?: return null- val bitmap = try {- BitmapFactory.decodeFile(file.absolutePath)- } catch (expected: Exception) {- Log.error(TAG, "Failed to decode image ${file.absolutePath}", expected)- null- } ?: return null- val input = try {- preprocess(bitmap)- } finally {- bitmap.recycle()- }- return try {- synchronized(lock) {- val inputName = session.inputNames.iterator().next()- val outName = visionOutputName ?: bestOutputName(session)- OnnxTensor.createTensor(- env,- FloatBuffer.wrap(input),- longArrayOf(- BATCH_DIM,- CHANNELS.toLong(),- IMAGE_SIZE.toLong(),- IMAGE_SIZE.toLong(),- ),- ).use { tensor ->- session.run(mapOf(inputName to tensor)).use { result ->- val out = result.get(outName).get() as OnnxTensor- val vec = FloatArray(out.info.shape.last().toInt())- out.floatBuffer.get(vec)- l2Normalize(vec)- }- }- }- } catch (expected: Exception) {- Log.error(TAG, "Image embedding failed", expected)- null- }- }-- /**- * Embed [text] into an L2-normalised vector in the SAME space as- * [imageEmbedding], or null on failure.- */- fun textEmbedding(context: Context, text: String): FloatArray? {- if (!ensureInit(context)) return null- val session = textSession ?: return null- val tok = tokenizer ?: return null- val ids = tok.encode(text)- val longIds = LongArray(ids.size) { ids[it].toLong() }- return try {- synchronized(lock) {- val tensors = HashMap<String, OnnxTensor>()- try {- for (name in session.inputNames) {- val lname = name.lowercase()- when {- lname.contains("mask") -> {- // SigLIP attends over the full padded sequence; all-ones.- val mask = LongArray(ids.size) { 1L }- tensors[name] = OnnxTensor.createTensor(- env, LongBuffer.wrap(mask), longArrayOf(1, ids.size.toLong())- )- }- lname.contains("position") -> {- // Sequential positions 0..seqLen-1.- val pos = LongArray(ids.size) { it.toLong() }- tensors[name] = OnnxTensor.createTensor(- env, LongBuffer.wrap(pos), longArrayOf(1, ids.size.toLong())- )- }- else -> {- // input_ids- tensors[name] = OnnxTensor.createTensor(- env, LongBuffer.wrap(longIds), longArrayOf(1, ids.size.toLong())- )- }- }- }- session.run(tensors).use { result ->- val outName = textOutputName ?: bestOutputName(session)- val out = result.get(outName).get() as OnnxTensor- val vec = FloatArray(out.info.shape.last().toInt())- out.floatBuffer.get(vec)- l2Normalize(vec)- }- } finally {- tensors.values.forEach { it.close() }- }- }- } catch (expected: Exception) {- Log.error(TAG, "Text embedding failed", expected)- null- }- }-- fun close() {- synchronized(lock) { closeLocked() }- }-- private fun closeLocked() {- try { visionSession?.close() } catch (_: Exception) {}- try { textSession?.close() } catch (_: Exception) {}- visionSession = null- textSession = null- tokenizer = null- visionOutputName = null- textOutputName = null- cachedDim = 0- initOk = false- initTried = false- }-- /**- * SigLIP preprocessing: resize [src] **directly** to [IMAGE_SIZE]² (no- * center-crop), rescale to [0,1], normalize mean/std 0.5 → (px-127.5)/127.5,- * packed NCHW (RGB).- */- private fun preprocess(src: Bitmap): FloatArray {- val safe = if (src.config == Bitmap.Config.HARDWARE || src.config == null) {- src.copy(Bitmap.Config.ARGB_8888, false)- } else src-- val scaled = Bitmap.createScaledBitmap(safe, IMAGE_SIZE, IMAGE_SIZE, true)- val px = IntArray(IMAGE_SIZE * IMAGE_SIZE)- scaled.getPixels(px, 0, IMAGE_SIZE, 0, 0, IMAGE_SIZE, IMAGE_SIZE)- if (scaled != safe) scaled.recycle()- if (safe != src) safe.recycle()-- val area = IMAGE_SIZE * IMAGE_SIZE- val out = FloatArray(CHANNELS * area)- for (i in 0 until area) {- val p = px[i]- out[i] = (((p shr RED_SHIFT) and CHANNEL_MASK) - PIXEL_MID) / PIXEL_MID- out[area + i] = (((p shr GREEN_SHIFT) and CHANNEL_MASK) - PIXEL_MID) / PIXEL_MID- out[2 * area + i] = ((p and CHANNEL_MASK) - PIXEL_MID) / PIXEL_MID- }- return out- }-- // ---- Shared math + serialisation helpers ------ fun l2Normalize(values: FloatArray): FloatArray {- var norm = 0f- for (v in values) norm += v * v- norm = sqrt(norm)- if (norm == 0f) return values- return FloatArray(values.size) { values[it] / norm }- }-- fun floatsToBytes(values: FloatArray): ByteArray {- val buffer = ByteBuffer.allocate(values.size * FLOAT_BYTES).order(ByteOrder.LITTLE_ENDIAN)- for (v in values) buffer.putFloat(v)- return buffer.array()- }-}
openassistant/src/main/res/xml/data_extraction_rules.xml
diff --git a/openassistant/src/main/res/xml/data_extraction_rules.xml b/openassistant/src/main/res/xml/data_extraction_rules.xmlindex 32ff184ff4..873559d053 100644--- a/openassistant/src/main/res/xml/data_extraction_rules.xml+++ b/openassistant/src/main/res/xml/data_extraction_rules.xml@@ -6,10 +6,9 @@ conversation history plus remembered facts. Free-form user text, so it can contain anything. external/ on-demand model downloads in getExternalFilesDir(null):- the gemma4/ maml model files, the SigLIP2 ONNX encoders and- tokenizer.model. Gigabytes, and re-downloadable.+ the gemma4/ maml model files. Gigabytes, and re-downloadable. file/datastore_default.preferences_pb model download progress and version markers- (progress_*, dlid_*, siglip_model_version). Meaningless once+ (progress_*, dlid_*). Meaningless once the models are gone. cache/ recordings and attachment scratch files; Android never backs up cacheDir.
openassistant/src/test/java/com/vayunmathur/openassistant/util/EmbeddingChunkTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/EmbeddingChunkTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/EmbeddingChunkTest.ktdeleted file mode 100644index 4bcc8d8ba5..0000000000--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/EmbeddingChunkTest.kt+++ /dev/null@@ -1,87 +0,0 @@-package com.vayunmathur.openassistant.util--import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertTrue--/**- * Pins embedding-input chunking for the SigLIP2 text tower.- *- * Long passages are split into word-bounded chunks that each fit the fixed- * context length, so nothing is silently dropped and no chunk overruns the- * model. Mirrors the split/pad/truncate contract without ONNX or files.- */-class EmbeddingChunkTest {-- private fun chunkWords(text: String, maxWords: Int): List<String> {- require(maxWords > 0)- val words = text.trim().split(Regex("\\s+")).filter { it.isNotEmpty() }- if (words.isEmpty()) return emptyList()- val out = mutableListOf<String>()- var i = 0- while (i < words.size) {- val end = minOf(i + maxWords, words.size)- out.add(words.subList(i, end).joinToString(" "))- i = end- }- return out- }-- private fun padToLength(ids: List<Int>, seqLen: Int, padId: Int): List<Int> {- require(seqLen >= 0)- if (ids.size >= seqLen) return ids.take(seqLen)- return ids + List(seqLen - ids.size) { padId }- }-- @Test- fun emptyAndBlankInputsYieldNoChunks() {- assertEquals(emptyList(), chunkWords("", 64))- assertEquals(emptyList(), chunkWords(" \n\t ", 64))- }-- @Test- fun shortInputIsOneChunk() {- assertEquals(listOf("hello world"), chunkWords("hello world", 64))- assertEquals(listOf("hello world"), chunkWords(" hello world ", 64))- }-- @Test- fun exactFitDoesNotSplit() {- val text = (1..64).joinToString(" ") { "w$it" }- assertEquals(listOf(text), chunkWords(text, 64))- }-- @Test- fun oversizedInputSplitsOnWordBoundaries() {- val text = (1..130).joinToString(" ") { "w$it" }- val chunks = chunkWords(text, 64)- assertEquals(3, chunks.size)- assertEquals(64, chunks[0].split(" ").size)- assertEquals(64, chunks[1].split(" ").size)- assertEquals(2, chunks[2].split(" ").size)- val rejoined = chunks.joinToString(" ")- assertEquals(text, rejoined)- }-- @Test- fun singleWordChunksNeverMerge() {- val chunks = chunkWords("a b c", 1)- assertEquals(listOf("a", "b", "c"), chunks)- }-- @Test- fun paddingFillsShortSequences() {- assertEquals(listOf(1, 2, 0, 0), padToLength(listOf(1, 2), 4, 0))- assertEquals(emptyList(), padToLength(emptyList(), 0, 0))- assertEquals(listOf(0, 0, 0), padToLength(emptyList(), 3, 0))- }-- @Test- fun truncationKeepsTheHead() {- val ids = (1..100).toList()- val out = padToLength(ids, 64, 0)- assertEquals(64, out.size)- assertEquals((1..64).toList(), out)- assertTrue(out.all { it != 0 })- }-}