revert Bonsai LLM track, keep Gemma 4 with LiteRT-LM; restore TinyCLIP ONNX
- Commit
a7d063cf618b236fe4e1dd24201453a21dfe1451- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-14 21:13 UTC (2 months ago)
- Parents
b6a3e0e
Diff
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 9dc1efee98..12e328f7ff 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@@ -6,85 +6,126 @@ package com.vayunmathur.library.downloadservice * The server must host each file under https://data.vayunmathur.com/models/ * and set Content-Length + ETag. *- * # Bonsai 8B is three files, not one+ * # Gemma 4 is five files, not one *- * The chat LLM is `onnx-community/Bonsai-8B-ONNX` (Qwen3 8B, Apache-2.0 and ungated),- * specifically the 1-bit quant `onnx/model_q1.onnx` (+ its external-data companion) with- * the HuggingFace `tokenizer.json`. It runs on `:library:ml`'s reduced ONNX Runtime build- * via `BonsaiHandle` (prefill + KV-cached decode), with the chat turn and tool loop in- * `BonsaiEngine`.+ * The single `.litertlm` was replaced by this repo's own `.maml` format when `:openassistant`+ * moved off `com.google.ai.edge.litertlm` onto `:library:ml`. Several files rather than one because+ * they have different lifetimes and different readers: *- * To populate the mirror, download from the upstream repo at the pinned revision and upload:+ * * the decoder, which the GPU binds,+ * * the embedding, which only the host reads a row at a time and which is therefore its own+ * graph rather than tensors inside the decoder,+ * * the tokenizer table, which is tiny and is read once into memory,+ * * the vision tower and the audio tower, each of which is a separate encoder that produces+ * soft tokens in the decoder's embedding space. *- * models/bonsai_q1.onnx <- onnx/model_q1.onnx- * models/bonsai_q1.onnx_data <- onnx/model_q1.onnx_data (~1.33 GB)- * models/bonsai_tokenizer.json <- tokenizer.json (~9 MB)+ * The first three must be present before the assistant will start - see `Gemma4Handle.FILES`.+ * The two encoders are optional at load: a device that never sends a picture or a clip still+ * answers text. *- * The first three must be present before the assistant will start - see `BonsaiHandle.FILES`.+ * To populate the mirror, produce the files from the ONNX export and upload them:+ *+ * models/gemma4_text.maml+ * <- python3 scripts/ml/maml_convert.py decoder_model_merged_fp16.onnx \+ * --graph gemma4_text -o gemma4_text.maml+ * models/gemma4_embed.maml+ * <- python3 scripts/ml/maml_convert.py embed_tokens_fp16.onnx \+ * --graph gemma4_embed -o gemma4_embed.maml+ * models/gemma4_tokenizer.spm1+ * <- python3 scripts/ml/gemma4_tokenizer.py --tokenizer tokenizer.json \+ * -o gemma4_tokenizer.spm1+ * models/gemma4_vision.maml+ * <- python3 scripts/ml/maml_convert.py vision_encoder_fp16.onnx \+ * --graph gemma4_vision -o gemma4_vision.maml+ * models/gemma4_audio.maml+ * <- python3 scripts/ml/maml_convert.py audio_encoder_fp16.onnx \+ * --graph gemma4_audio -o gemma4_audio.maml+ *+ * The ONNX inputs are `onnx-community/gemma-4-E2B-it-ONNX`, which is Apache-2.0 and ungated. */ object ModelUrls { const val MIRROR_BASE = "https://data.vayunmathur.com/models/" - /** The decoder export (graph only; weights ride alongside in the `.onnx_data`). */- const val BONSAI_MODEL_FILE = "bonsai_q1.onnx"- const val BONSAI_MODEL_URL = "${MIRROR_BASE}bonsai_q1.onnx"- const val BONSAI_MODEL_SHA256 = "REPLACE_WITH_MIRRORED_SHA256"+ /** The decoder: 35 layers at int4 with per-block scales. */+ const val GEMMA_TEXT_FILE = "gemma4_text.maml"+ const val GEMMA_TEXT_URL = "${MIRROR_BASE}gemma4_text.maml"+ const val GEMMA_TEXT_SHA256 =+ "f9043d69180c209ac57db30179bbca75342991a8a2fa6899916cff05cc155620" - /** The 1-bit weights for the export above. */- const val BONSAI_DATA_FILE = "bonsai_q1.onnx_data"- const val BONSAI_DATA_URL = "${MIRROR_BASE}bonsai_q1.onnx_data"- const val BONSAI_DATA_SHA256 = "REPLACE_WITH_MIRRORED_SHA256"+ /** The two embedding tables, gathered on the host. */+ const val GEMMA_EMBED_FILE = "gemma4_embed.maml"+ const val GEMMA_EMBED_URL = "${MIRROR_BASE}gemma4_embed.maml"+ const val GEMMA_EMBED_SHA256 =+ "b1ca4f34c3f2a05a71cb231e8b1e3795267b2550b87dd51d49ea15f84c0ef90a" - /** The BPE table: 151,643 entries plus 26 added tokens. */- const val BONSAI_TOKENIZER_FILE = "bonsai_tokenizer.json"- const val BONSAI_TOKENIZER_URL = "${MIRROR_BASE}bonsai_tokenizer.json"- const val BONSAI_TOKENIZER_SHA256 = "REPLACE_WITH_MIRRORED_SHA256"+ /** The BPE table: 262144 pieces, 514906 merges, byte fallback. */+ const val GEMMA_TOKENIZER_FILE = "gemma4_tokenizer.spm1"+ const val GEMMA_TOKENIZER_URL = "${MIRROR_BASE}gemma4_tokenizer.spm1"+ const val GEMMA_TOKENIZER_SHA256 =+ "bfb34775a267c98b4062edbd91848865fdf05583b9df3a49e6eab7a0ee251383" /**- * Everything downloaded on OpenAssistant first launch.+ * The vision tower: 16 layers at int4, with the patch and output projections left at fp16. *- * Smallest first, so a user on a slow connection sees progress early and so the two large- * files are the ones a resume is most likely to land in the middle of. The two encoders go- * after the tokenizer and before the two large ones: together they are 259 MB, they are what- * make the assistant able to answer about a photograph or a recording, and a resume that- * stalls in the decoder should not leave them unfetched.+ * Optional, and deliberately not in the same download as the decoder. It is 93 MB on top of+ * 2.8 GB, a device that never sends a picture never needs it, and the assistant answers text+ * perfectly well without it - see `Gemma4Engine.canSeeImages`.+ */+ const val GEMMA_VISION_FILE = "gemma4_vision.maml"+ const val GEMMA_VISION_URL = "${MIRROR_BASE}gemma4_vision.maml"+ const val GEMMA_VISION_SHA256 =+ "4c53c0a8383f2ea99f8beed50bd5eac203565436313d0c2dd77b389ea1cf38e3"++ /**+ * The audio tower: a 12-layer conformer at int4, with the three end projections, the two+ * subsampling convolutions, the twelve depthwise convolutions and the twelve+ * relative-position tables all left at fp16.+ *+ * Optional on the same terms as the vision tower. 166 MB, and a device that never sends a+ * clip never needs it. */- val BONSAI_MODEL =- ModelDownloadItem(BONSAI_MODEL_URL, BONSAI_MODEL_FILE, "Model", BONSAI_MODEL_SHA256)- val BONSAI_DATA =- ModelDownloadItem(BONSAI_DATA_URL, BONSAI_DATA_FILE, "Weights", BONSAI_DATA_SHA256)- val BONSAI_TOKENIZER = ModelDownloadItem(- BONSAI_TOKENIZER_URL,- BONSAI_TOKENIZER_FILE,+ const val GEMMA_AUDIO_FILE = "gemma4_audio.maml"+ const val GEMMA_AUDIO_URL = "${MIRROR_BASE}gemma4_audio.maml"+ const val GEMMA_AUDIO_SHA256 =+ "be3ac4f968835fa257291f0845be642750f71e63e197a6e199ad5210316cb4f2"++ val GEMMA_TEXT =+ ModelDownloadItem(GEMMA_TEXT_URL, GEMMA_TEXT_FILE, "Model", GEMMA_TEXT_SHA256)+ val GEMMA_EMBED =+ ModelDownloadItem(GEMMA_EMBED_URL, GEMMA_EMBED_FILE, "Embeddings", GEMMA_EMBED_SHA256)+ val GEMMA_TOKENIZER = ModelDownloadItem(+ GEMMA_TOKENIZER_URL,+ GEMMA_TOKENIZER_FILE, "Tokenizer",- BONSAI_TOKENIZER_SHA256,+ GEMMA_TOKENIZER_SHA256, )+ val GEMMA_VISION =+ ModelDownloadItem(GEMMA_VISION_URL, GEMMA_VISION_FILE, "Vision", GEMMA_VISION_SHA256)+ val GEMMA_AUDIO =+ ModelDownloadItem(GEMMA_AUDIO_URL, GEMMA_AUDIO_FILE, "Audio", GEMMA_AUDIO_SHA256) /** * Everything downloaded on OpenAssistant first launch. *- * Smallest first, so a user on a slow connection sees progress early and so the large- * weights file is the one a resume is most likely to land in the middle of.+ * Smallest first, so a user on a slow connection sees progress early and so the two large+ * files are the ones a resume is most likely to land in the middle of. The two encoders go+ * after the tokenizer and before the two large ones: together they are 259 MB, they are what+ * make the assistant able to answer about a photograph or a recording, and a resume that+ * stalls in the decoder should not leave them unfetched. */- val INITIAL = listOf(BONSAI_TOKENIZER, BONSAI_MODEL, BONSAI_DATA)+ val INITIAL = listOf(GEMMA_TOKENIZER, GEMMA_VISION, GEMMA_AUDIO, GEMMA_TEXT, GEMMA_EMBED) /** * Files an earlier build downloaded and this one does not use. *- * Deleted on startup rather than left to rot: the Gemma `.maml` files alone were 2.8 GB,- * and a user upgrading would otherwise carry both copies forever.+ * Deleted on startup rather than left to rot: the litertlm bundle alone was several+ * gigabytes, and a user upgrading would otherwise carry both copies forever. */ val OBSOLETE = listOf( "gemma4-2b.litertlm", "gemma-4-E2B-it.litertlm", "gemma4.litertlm", "gemma4-4b.litertlm",- "gemma4_text.maml",- "gemma4_embed.maml",- "gemma4_tokenizer.spm1",- "gemma4_vision.maml",- "gemma4_audio.maml",- "gemma4_prefix.kv", ) }
library/ml/src/main/java/com/vayunmathur/library/ml/BonsaiHandle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/BonsaiHandle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/BonsaiHandle.ktdeleted file mode 100644index 477e2a7861..0000000000--- a/library/ml/src/main/java/com/vayunmathur/library/ml/BonsaiHandle.kt+++ /dev/null@@ -1,394 +0,0 @@-package com.vayunmathur.library.ml--import ai.onnxruntime.OnnxTensor-import ai.onnxruntime.OrtEnvironment-import ai.onnxruntime.OrtSession-import android.util.Log-import java.io.File-import java.nio.LongBuffer-import kotlin.math.exp-import kotlin.math.max--/**- * On-device chat LLM: Bonsai-8B 1-bit (`onnx-community/Bonsai-8B-ONNX`, Qwen3) on the reduced- * ONNX Runtime build.- *- * A standard HuggingFace decoder export with full KV cache: `input_ids [B, S]` +- * `attention_mask [B, T]` + `num_logits_to_keep []` + 72 `past_key_values.* [B, 8, P, 128]`- * in, `logits [B, K, 151669]` + 72 `present.*` out (36 layers, GQA 8 KV heads of 128).- * Generation is a prefill of the whole prompt followed by one-token decode steps threading- * the cache — the same shape as the Whisper decoder port.- *- * # Files, downloaded rather than bundled- *- * `model_q1.onnx` + `model_q1.onnx_data` (~1.33 GB) and `tokenizer.json`, fetched to- * `getExternalFilesDir` by `:library:downloadservice` like the Gemma files were — hence- * [inDirectory] and no asset path. See `ModelUrls` for the mirror pins.- *- * # Sampling- *- * Temperature + top-k + top-p from the export's `generation_config.json` (0.5 / 20 / 0.85),- * greedy when temperature is 0. The sampler runs on the host over the final position's- * logits; `num_logits_to_keep = 1` on decode steps so the 151k-wide head only scores one- * position.- *- * # Threading- *- * Not thread-safe: the KV cache is per-handle state. A caller must hold a lock across- * [generate] and [close].- */-class BonsaiHandle private constructor(private val directory: File) : AutoCloseable {- private var session: OrtSession? = null- private var tokenizer: BonsaiTokenizer? = null-- /** True if the session opened and the tokenizer parsed. */- val isAvailable: Boolean get() = session != null && tokenizer != null-- /**- * Generate a reply to [promptIds] with [GeneratorConfig], streaming pieces to [onPiece].- *- * [onPiece] returning false stops generation. Returns the full reply, or null on failure.- * The prompt is prefilled in one call; each step after decodes a single token with the- * cache. Stops at EOS, [config] stop ids, or [config] max tokens.- */- fun generate(- promptIds: IntArray,- config: GeneratorConfig = GeneratorConfig(),- onPiece: (String) -> Boolean = { true },- ): String? {- val live = session ?: return null- val tok = tokenizer ?: return null- if (promptIds.isEmpty()) return null- return try {- val env = OrtEnvironment.getEnvironment()- val past = emptyPast(env)- try {- // Prefill the whole prompt, keeping all logits (needed for the first token- // only, but the slice is cheap relative to the matmul).- var result = runStep(- live, env, promptIds, totalLen = promptIds.size,- keepLogits = promptIds.size, past = past,- ) ?: return null- var produced = ArrayList<Int>(config.maxTokens)- var next = sample(lastLogits(result, promptIds.size), config)- // `past` takes ownership of the result: its `present.*` tensors are the next- // step's inputs, so the caller must not close it. `replace` closes the- // previous generation's result.- past.replace(result)- val output = StringBuilder()- var step = 0- while (step < config.maxTokens) {- if (next == BonsaiTokenizer.EOS || next in config.stopIds) break- produced.add(next)- val piece = tok.decode(intArrayOf(next))- output.append(piece)- if (!onPiece(output.toString())) break- step++- if (step >= config.maxTokens) break- // One-token decode with the cache.- result = runStep(- live, env, intArrayOf(next),- totalLen = promptIds.size + produced.size,- keepLogits = 1, past = past,- ) ?: break- next = sample(lastLogits(result, 1), config)- past.replace(result)- }- output.toString()- } finally {- past.close()- }- } catch (e: Throwable) {- Log.e(TAG, "bonsai generation failed", e)- null- }- }-- /** Token ids for [text], without specials. */- fun encode(text: String): IntArray? = tokenizer?.encode(text)-- /** Text for [ids]. */- fun decode(ids: IntArray): String? = tokenizer?.decode(ids)-- /** Free the session. Idempotent. */- override fun close() {- val live = session- session = null- if (live != null) runCatching { live.close() }- }-- override fun toString(): String = "Bonsai-8B in $directory"-- // -- One model step --------------------------------------------------------- private fun runStep(- session: OrtSession,- env: OrtEnvironment,- ids: IntArray,- totalLen: Int,- keepLogits: Int,- past: Past,- ): OrtSession.Result? {- val longIds = LongArray(ids.size) { ids[it].toLong() }- val idTensor = OnnxTensor.createTensor(- env, LongBuffer.wrap(longIds), longArrayOf(1, ids.size.toLong()),- )- val mask = LongArray(totalLen) { 1L }- val maskTensor = OnnxTensor.createTensor(- env, LongBuffer.wrap(mask), longArrayOf(1, totalLen.toLong()),- )- val keepTensor = OnnxTensor.createTensor(env, longArrayOf(keepLogits.toLong()))- val inputs = LinkedHashMap<String, OnnxTensor>(4 + past.tensors().size)- inputs["input_ids"] = idTensor- inputs["attention_mask"] = maskTensor- inputs["num_logits_to_keep"] = keepTensor- for ((name, tensor) in past.tensors()) inputs[name] = tensor- return try {- // All outputs: `logits` for sampling plus every `present.*` for the next step's- // cache. Restricting to `logits` alone would leave the cache unfed.- session.run(inputs)- } finally {- runCatching { idTensor.close() }- runCatching { maskTensor.close() }- runCatching { keepTensor.close() }- }- }-- private fun lastLogits(result: OrtSession.Result, positions: Int): FloatArray {- val out = result.get("logits").get() as OnnxTensor- val shape = out.info.shape- val vocab = shape.last().toInt()- val row = FloatArray(vocab)- out.floatBuffer.position((positions - 1) * vocab)- out.floatBuffer.get(row)- return row- }-- private fun sample(logits: FloatArray, config: GeneratorConfig): Int {- if (config.temperature <= 0f) {- var best = 0- var peak = logits[0]- for (i in 1 until logits.size) {- if (logits[i] > peak) {- peak = logits[i]- best = i- }- }- return best- }- val scaled = FloatArray(logits.size) { logits[it] / config.temperature }- // Top-k truncation.- val order = scaled.indices.sortedByDescending { scaled[it] }- val kept = order.take(max(config.topK, 1)).toSet()- // Softmax over the kept, with the peak subtracted for range.- var peak = Float.NEGATIVE_INFINITY- for (i in kept) if (scaled[i] > peak) peak = scaled[i]- var total = 0.0- val probs = HashMap<Int, Double>(kept.size)- for (i in kept) {- val p = exp((scaled[i] - peak).toDouble())- probs[i] = p- total += p- }- // Top-p (nucleus) cutoff in probability order.- var cutoff = total- var nucleus = ArrayList<Int>(kept.size)- for (i in order) {- if (i !in kept) continue- nucleus.add(i)- cutoff -= probs[i] ?: 0.0- if (cutoff <= (1.0 - config.topP) * total) break- }- if (nucleus.isEmpty()) nucleus = ArrayList(kept)- var sum = 0.0- for (i in nucleus) sum += probs[i] ?: 0.0- var draw = Math.random() * sum- for (i in nucleus) {- draw -= probs[i] ?: 0.0- if (draw <= 0.0) return i- }- return nucleus.last()- }-- // -- KV cache --------------------------------------------------------------- private fun emptyPast(env: OrtEnvironment): Past = Past(env, null)-- private inner class Past(- private val env: OrtEnvironment,- private var result: OrtSession.Result?,- ) {- fun tensors(): List<Pair<String, OnnxTensor>> = PAST_NAMES.map { name ->- val live = result- val tensor = if (live == null) {- emptyKv(env).also { empties.add(it) }- } else {- live.get(name.replace("past_key_values", "present")).get() as OnnxTensor- }- name to tensor- }-- fun replace(newResult: OrtSession.Result) {- runCatching { result?.close() }- empties.forEach { runCatching { it.close() } }- empties.clear()- result = newResult- }-- fun close() {- runCatching { result?.close() }- result = null- empties.forEach { runCatching { it.close() } }- empties.clear()- }-- private val empties = ArrayList<OnnxTensor>()- }-- /** Sampling knobs for one reply. Defaults from the export's `generation_config.json`. */- data class GeneratorConfig(- val maxTokens: Int = 512,- val temperature: Float = 0.5f,- val topK: Int = 20,- val topP: Float = 0.85f,- val stopIds: IntArray = intArrayOf(),- )-- /** Tool declaration in the Qwen chat template's `<tools>` block. */- data class ToolDeclaration(- val name: String,- val description: String,- val parameters: List<Parameter>,- ) {- data class Parameter(- val name: String,- val description: String,- val type: String,- val required: Boolean,- )- }-- /** A parsed `<tool_call>` request. */- data class ToolCall(val name: String, val arguments: Map<String, String>)-- companion object {- private const val TAG = "BonsaiHandle"-- /** The decoder export. */- const val MODEL_FILE = "model_q1.onnx"-- /** The external-data companion. */- const val MODEL_DATA = "model_q1.onnx_data"-- /** The HuggingFace tokenizer. */- const val TOKENIZER_FILE = BonsaiTokenizer.TOKENIZER_FILE-- /** The files [inDirectory] needs, for a caller checking a download is complete. */- val FILES: List<String> = listOf(MODEL_FILE, MODEL_DATA, TOKENIZER_FILE)-- /** 36 layers × key/value, 8 GQA heads of 128. */- const val N_LAYERS = 36- const val N_KV_HEADS = 8L- const val HEAD_DIM = 128L-- private val EMPTY_KV = longArrayOf(1, N_KV_HEADS, 0, HEAD_DIM)-- private fun emptyKv(env: OrtEnvironment): OnnxTensor =- OnnxTensor.createTensor(env, java.nio.FloatBuffer.allocate(0), EMPTY_KV)-- private val PAST_NAMES: List<String> = buildList {- for (i in 0 until N_LAYERS) {- for (kv in listOf("key", "value")) add("past_key_values.$i.$kv")- }- }-- /**- * The model in a folder on disk, which is the only place it lives.- *- * No `inAssets` counterpart: at ~1.33 GB this is a runtime download to- * `getExternalFilesDir`, so there is no APK entry to open.- */- fun inDirectory(directory: File): BonsaiHandle {- val instance = BonsaiHandle(directory)- val model = File(directory, MODEL_FILE)- if (!model.isFile) {- Log.w(TAG, "$MODEL_FILE is missing from $directory")- return instance- }- instance.tokenizer = BonsaiTokenizer.inDirectory(directory)- if (instance.tokenizer == null) return instance- // External data loads relative to the model path: pass the file path, not bytes.- instance.session = try {- val env = OrtEnvironment.getEnvironment()- val opts = OrtSession.SessionOptions().apply {- setIntraOpNumThreads(4)- setInterOpNumThreads(1)- }- env.createSession(model.absolutePath, opts)- } catch (e: Throwable) {- Log.e(TAG, "cannot open $MODEL_FILE", e)- null- }- if (!instance.isAvailable) {- Log.w(TAG, "bonsai did not load from $directory")- instance.close()- }- return instance- }-- /**- * Parse a `<tool_call>{"name": ..., "arguments": {...}}</tool_call>` request.- *- * Returns null when the reply holds no complete call. Tolerates a trailing- * `</tool_call>` close tag and JSON values of any scalar type (numbers and booleans- * arrive as their JSON spelling, matching the Double convention `ToolRegistry` keeps).- */- fun parseToolCall(reply: String): ToolCall? {- val open = reply.indexOf("<tool_call>")- if (open < 0) return null- var body = reply.substring(open + "<tool_call>".length)- val close = body.indexOf("</tool_call>")- if (close >= 0) body = body.substring(0, close)- return try {- val json = org.json.JSONObject(body)- val name = json.optString("name").ifEmpty { return null }- val args = json.optJSONObject("arguments")- val map = HashMap<String, String>()- if (args != null) {- val keys = args.keys()- while (keys.hasNext()) {- val key = keys.next()- map[key] = args.opt(key)?.toString() ?: ""- }- }- ToolCall(name, map)- } catch (e: Throwable) {- null- }- }-- /** Render one tool declaration for the `<tools>` block (OpenAI-style JSON schema). */- fun renderTool(declaration: ToolDeclaration): String {- val properties = declaration.parameters.joinToString(",") { parameter ->- val type = when (parameter.type) {- "NUMBER" -> "number"- "BOOLEAN" -> "boolean"- else -> "string"- }- "\"${parameter.name}\":{\"type\":\"$type\",\"description\":${jsonString(parameter.description)}}"- }- val required = declaration.parameters.filter { it.required }- .joinToString(",", "[", "]") { "\"${it.name}\"" }- return "{\"type\":\"function\",\"function\":{\"name\":\"${declaration.name}\"," +- "\"description\":${jsonString(declaration.description)}," +- "\"parameters\":{\"type\":\"object\",\"properties\":{$properties},\"required\":$required}}}"- }-- /** Render a tool result for the `<tool_response>` turn. */- fun renderToolResponse(name: String, result: String): String =- "<tool_response>$result</tool_response>"-- private fun jsonString(value: String): String =- org.json.JSONObject.quote(value)- }-}
library/ml/src/main/java/com/vayunmathur/library/ml/BonsaiTokenizer.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/BonsaiTokenizer.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/BonsaiTokenizer.ktdeleted file mode 100644index 2887fe015f..0000000000--- a/library/ml/src/main/java/com/vayunmathur/library/ml/BonsaiTokenizer.kt+++ /dev/null@@ -1,213 +0,0 @@-package com.vayunmathur.library.ml--import android.util.Log-import java.io.File-import org.json.JSONObject--/**- * The Bonsai/Qwen3 chat tokenizer: byte-level BPE from the HuggingFace `tokenizer.json`.- *- * Vocabulary is 151,643 BPE entries plus 26 added tokens (`<|im_start|>`, `<|im_end|>`,- * `<|endoftext|>`, `<tool_call>`/`</tool_call>`, vision/FIM markers) for 151,669 — the model's- * own width. The pre-tokenizer is the GPT-2 split regex, the normalizer is NFC, and decode is- * byte-level (byte tokens map back through the byte decoder).- *- * The BPE core (greedy lowest-rank merge, byte→unicode map) follows the same shape as- * `:photos`' `ClipTokenizer`, but nothing is shared: CLIP lower-cases and pads to 77, Qwen- * neither.- *- * `tokenizer.json` (~17 MB) ships with the model download rather than in the APK, and is read- * from the same directory as the weights.- */-class BonsaiTokenizer private constructor(- private val encoder: Map<String, Int>,- private val decoder: Map<Int, ByteArray>,- private val bpeRanks: Map<Pair<String, String>, Int>,-) {- private val cache = HashMap<String, List<Int>>()-- /** Token ids for [text], without any special tokens. */- fun encode(text: String): IntArray {- val normalized = java.text.Normalizer.normalize(text, java.text.Normalizer.Form.NFC)- val ids = ArrayList<Int>()- val matcher = SPLIT_PATTERN.matcher(normalized)- while (matcher.find()) {- val piece = matcher.group()- if (piece.isEmpty()) continue- ids.addAll(encodePiece(piece))- }- return ids.toIntArray()- }-- /** Text for [ids], skipping special tokens. */- fun decode(ids: IntArray): String {- val bytes = ArrayList<Byte>()- for (id in ids) {- val chunk = decoder[id] ?: continue- for (b in chunk) bytes.add(b)- }- return String(bytes.toByteArray(), Charsets.UTF_8)- }-- private fun encodePiece(piece: String): List<Int> {- cache[piece]?.let { return it }- val bytes = piece.toByteArray(Charsets.UTF_8)- // Map bytes to the visible unicode chars the merges were trained on.- val token = StringBuilder(bytes.size)- for (b in bytes) token.append(byteEncoder[b.toInt() and 0xFF])- val out = bpe(token.toString()).split(' ').mapNotNull { encoder[it] }- cache[piece] = out- return out- }-- private fun bpe(token: String): String {- if (token.length <= 1) return token- var word = ArrayList<String>(token.length)- for (i in token.indices) word.add(token[i].toString())- while (true) {- var bestRank = Int.MAX_VALUE- var bestPair: Pair<String, String>? = null- for (i in 0 until word.size - 1) {- val pair = word[i] to word[i + 1]- val rank = bpeRanks[pair] ?: continue- if (rank < bestRank) {- bestRank = rank- bestPair = pair- }- }- val (first, second) = bestPair ?: break- val merged = ArrayList<String>(word.size)- var i = 0- while (i < word.size) {- if (i < word.size - 1 && word[i] == first && word[i + 1] == second) {- merged.add(first + second)- i += 2- } else {- merged.add(word[i])- i += 1- }- }- word = merged- if (word.size == 1) break- }- return word.joinToString(" ")- }-- companion object {- private const val TAG = "BonsaiTokenizer"-- const val TOKENIZER_FILE = "tokenizer.json"-- /** End of text / generation stop. */- const val EOS = 151645-- /** Turn markers. */- const val IM_START = 151644- const val IM_END = 151645-- /** Tool-call markers. */- const val TOOL_CALL_OPEN = 151657- const val TOOL_CALL_CLOSE = 151658-- private val SPLIT_PATTERN = java.util.regex.Pattern.compile(- "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",- )-- /** Reversible bytes→unicode table (GPT-2 `bytes_to_unicode`). */- private val byteEncoder: Array<String> = run {- val bs = ArrayList<Int>()- for (i in '!'.code..'~'.code) bs.add(i)- for (i in '¡'.code..'¬'.code) bs.add(i)- for (i in '®'.code..'ÿ'.code) bs.add(i)- val cs = ArrayList<Int>(bs)- var n = 0- for (b in 0..255) {- if (b !in bs) {- bs.add(b)- cs.add(256 + n)- n++- }- }- Array(256) { "" }.also { out ->- for (i in bs.indices) out[bs[i]] = cs[i].toChar().toString()- }- }-- /**- * Load `tokenizer.json` from [directory].- *- * Returns null when the file is absent or malformed — the engine then reports- * unavailable rather than crashing.- */- fun inDirectory(directory: File): BonsaiTokenizer? {- val file = File(directory, TOKENIZER_FILE)- if (!file.isFile) {- Log.w(TAG, "$TOKENIZER_FILE is missing from $directory")- return null- }- return try {- parse(JSONObject(file.readText(Charsets.UTF_8)))- } catch (e: Throwable) {- Log.e(TAG, "cannot parse $TOKENIZER_FILE", e)- null- }- }-- private fun parse(json: JSONObject): BonsaiTokenizer? {- val model = json.optJSONObject("model") ?: return null- val vocabJson = model.optJSONObject("vocab") ?: return null- val mergesJson = model.optJSONArray("merges") ?: return null- val encoder = HashMap<String, Int>(vocabJson.length() * 2)- val keys = vocabJson.keys()- while (keys.hasNext()) {- val token = keys.next()- encoder[token] = vocabJson.optInt(token)- }- val bpeRanks = HashMap<Pair<String, String>, Int>(mergesJson.length() * 2)- for (i in 0 until mergesJson.length()) {- val line = mergesJson.optString(i)- val space = line.indexOf(' ')- if (space < 0) continue- // Merges may carry a trailing score; only the pair matters.- val rest = line.substring(space + 1)- val space2 = rest.indexOf(' ')- val pair = if (space2 < 0) {- line.substring(0, space) to rest- } else {- line.substring(0, space) to rest.substring(0, space2)- }- bpeRanks[pair] = i- }- // Added tokens live outside `model.vocab`.- val added = json.optJSONArray("added_tokens")- if (added != null) {- for (i in 0 until added.length()) {- val entry = added.optJSONObject(i) ?: continue- encoder[entry.optString("content")] = entry.optInt("id")- }- }- // Byte-level decode table: single-byte vocab entries map to their byte.- val byteDecoder = HashMap<Int, String>()- for ((token, id) in encoder) {- if (token.length == 1) byteDecoder[id] = token- }- val byteToByte = HashMap<String, Byte>()- for (i in 0..255) byteToByte[byteEncoder[i]] = i.toByte()- val decoder = HashMap<Int, ByteArray>(encoder.size)- for ((token, id) in encoder) {- val bytes = ArrayList<Byte>(token.length)- var ok = true- for (ch in token) {- val b = byteToByte[ch.toString()]- if (b == null) {- ok = false- break- }- bytes.add(b)- }- if (ok) decoder[id] = bytes.toByteArray()- }- return BonsaiTokenizer(encoder, decoder, bpeRanks)- }- }-}
openassistant/src/main/java/com/vayunmathur/openassistant/util/BonsaiEngine.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/BonsaiEngine.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/BonsaiEngine.ktdeleted file mode 100644index 48832839dc..0000000000--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/BonsaiEngine.kt+++ /dev/null@@ -1,252 +0,0 @@-package com.vayunmathur.openassistant.util--import android.util.Log-import com.vayunmathur.library.ml.BonsaiHandle-import java.io.File-import java.util.concurrent.locks.ReentrantLock-import kotlin.concurrent.withLock--/**- * A chat turn on Bonsai-8B, replacing `Gemma4Engine`.- *- * The same shape: the tool loop lives here ([ask] is generate / parse / invoke / resume),- * one conversation at a time behind a whole-turn lock, history re-rendered every turn so a- * stale cache can never answer a conversation that never happened.- *- * # What changed with the model- *- * The prompt is the Qwen3 chat template (`<|im_start|>system … <|im_end|>`, tools in a- * `<tools>` JSON block, calls as `<tool_call>{"name": …, "arguments": …}</tool_call>`)- * instead of Gemma's markers. Tokenizer, sampler and tool-call parse/render live in- * [BonsaiHandle]; the reflection-built [ToolRegistry] declarations are rendered through- * [BonsaiHandle.renderTool].- *- * Multimodal input is text-only for now: Bonsai ships no vision/audio tower, so there is no- * `encodeImages`/`encodeAudio`. Callers that passed attachments get the text with a note.- */-class BonsaiEngine(private val directory: File) : AutoCloseable {-- private val lock = ReentrantLock()- private var handle: BonsaiHandle? = null-- /** Whether the model is loaded and usable. */- val isReady: Boolean- get() = lock.withLock { handle?.isAvailable == true }-- /**- * Load the model if it is not loaded. Returns whether it is usable afterwards.- *- * Idempotent, so `onCreate` can pre-warm and the first turn can call it again without cost.- * Loading is slow - over a gigabyte of weights - so callers should pre-warm off the main- * thread.- */- fun ensureLoaded(): Boolean = lock.withLock {- val live = handle- if (live != null && live.isAvailable) return@withLock true- live?.close()- val opened = BonsaiHandle.inDirectory(directory)- if (!opened.isAvailable) {- Log.w(TAG, "bonsai did not load from $directory")- opened.close()- handle = null- return@withLock false- }- handle = opened- true- }-- /**- * Positions the prompt for [conversation] would occupy, against [promptCeiling].- *- * For a caller dropping history before a turn.- */- fun positionsFor(- conversation: List<Turn>,- system: String?,- tools: ToolRegistry?,- limit: Int = DEFAULT_REPLY,- ): Int = lock.withLock {- val live = handle ?: return@withLock 0- val declarations = tools?.declarations?.map { toBonsai(it) } ?: emptyList()- live.encode(renderPrompt(conversation, system, declarations, ""))?.size ?: 0- }-- /** What [positionsFor] must not exceed if the reply is to keep its [limit]. */- fun promptCeiling(limit: Int = DEFAULT_REPLY): Int = MAX_CONTEXT - maxOf(limit, 3)-- /**- * Run a turn, resolving any tool calls, and stream the visible reply to [onPartial].- *- * [onPartial] returning false stops generation. Returns the reply with all tool syntax- * stripped, or null if the model is unavailable.- */- fun ask(- conversation: List<Turn>,- system: String?,- tools: ToolRegistry?,- limit: Int = DEFAULT_REPLY,- onPartial: (String) -> Boolean = { true },- ): String? = lock.withLock {- val live = handle ?: return@withLock null- if (!live.isAvailable) return@withLock null- val declarations = tools?.declarations?.map { toBonsai(it) } ?: emptyList()-- var pending = ""- var visible = ""- for (hop in 0..MAX_TOOL_HOPS) {- val prompt = renderPrompt(conversation, system, declarations, pending)- val promptIds = live.encode(prompt) ?: return@withLock null- if (promptIds.size + limit + 2 > MAX_CONTEXT) {- Log.w(TAG, "a prompt of ${promptIds.size} positions does not fit $MAX_CONTEXT")- return@withLock null- }- Log.i(- TAG,- "prompt ${promptIds.size} positions, ${conversation.size} turns, " +- "${declarations.size} tools, reply budget $limit",- )- var stopped = false- val reply = live.generate(- promptIds,- BonsaiHandle.GeneratorConfig(maxTokens = limit),- ) { partial ->- val shown = visible + strip(partial)- if (onPartial(shown)) {- BonsaiHandle.parseToolCall(partial) == null- } else {- stopped = true- false- }- } ?: return@withLock null-- visible += strip(reply)- if (stopped) return@withLock visible- val call = BonsaiHandle.parseToolCall(reply)- if (call == null || tools == null) return@withLock visible- if (hop == MAX_TOOL_HOPS) {- Log.w(TAG, "stopping after $MAX_TOOL_HOPS tool hops")- return@withLock visible- }- val adapted = com.vayunmathur.library.ml.Gemma4Handle.ToolCall(call.name, call.arguments)- val result = tools.invoke(adapted)- Log.d(TAG, "tool ${call.name}(${call.arguments}) -> ${result.take(120)}")- pending += reply.substringBefore("<tool_call>") + "<tool_call>" +- BonsaiHandle.renderToolResponse(call.name, result)- }- visible- }-- /** Discard the conversation state. Cheap — the next turn re-prefills from scratch. */- fun reset() = lock.withLock { /* stateless across turns: nothing cached */ }-- override fun close() = lock.withLock {- handle?.close()- handle = null- }-- companion object {- private const val TAG = "BonsaiEngine"-- /** Positions the model was exported with. */- const val MAX_CONTEXT = 65536-- /** Default reply budget, in tokens. */- const val DEFAULT_REPLY = 512-- /** Tool calls one turn may make before the loop gives up. */- const val MAX_TOOL_HOPS = 8-- /** A turn of the conversation. Images/audio are noted, not encoded (text-only model). */- data class Turn(- val role: Role,- val text: String,- val note: String = "",- )-- enum class Role { USER, MODEL }-- private fun toBonsai(declaration: com.vayunmathur.library.ml.Gemma4Handle.ToolDeclaration) =- BonsaiHandle.ToolDeclaration(- name = declaration.name,- description = declaration.description,- parameters = declaration.parameters.map {- BonsaiHandle.ToolDeclaration.Parameter(- name = it.name,- description = it.description,- type = it.type,- required = it.required,- )- },- )-- /**- * The Qwen3 chat prompt: system block, `<tools>` JSON, history, generation header.- *- * `pending` is the model's own half-written turn (its call plus the tool result) and- * goes in as a continuation inside the open assistant turn.- */- fun renderPrompt(- conversation: List<Turn>,- system: String?,- tools: List<BonsaiHandle.ToolDeclaration>,- pending: String,- ): String {- val out = StringBuilder()- out.append("<|im_start|>system\n")- if (!system.isNullOrEmpty()) out.append(system).append("\n\n")- if (tools.isNotEmpty()) {- out.append("# Tools\n\nYou may call one or more functions to assist with the user query.\n\n")- out.append("You are provided with function signatures within <tools></tools> XML tags:\n<tools>")- for (tool in tools) {- out.append("\n")- out.append(BonsaiHandle.renderTool(tool))- }- out.append(- "\n</tools>\n\nFor each function call, return a json object with function name and " +- "arguments within <tool_call></tool_call> XML tags:\n" +- "<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n" +- "</tool_call><|im_end|>\n",- )- } else {- out.append("<|im_end|>\n")- }- for (turn in conversation) {- when (turn.role) {- Role.USER -> out.append("<|im_start|>user\n").append(turn.text)- Role.MODEL -> out.append("<|im_start|>assistant\n").append(turn.text)- }- if (turn.note.isNotEmpty()) out.append("\n").append(turn.note)- out.append("<|im_end|>\n")- }- out.append("<|im_start|>assistant\n")- out.append(pending)- return out.toString()- }-- /**- * The prose in a reply, with the tool markers and everything inside them removed.- *- * Streamed partials arrive mid-marker, so a half-written `<tool_call>` must not flash- * up in the UI: anything from an opening marker onwards is dropped whether or not it- * has been closed yet.- */- fun strip(reply: String): String {- var out = reply- for (marker in listOf("<tool_call>", "<tool_response>", "</tool_call>", "</tool_response>")) {- val at = out.indexOf(marker)- if (at >= 0) out = out.substring(0, at)- }- val open = out.lastIndexOf('<')- if (open >= 0 && out.length - open <= "</tool_response>".length) {- val tail = out.substring(open)- if ("<tool_call>".startsWith(tail) || "</tool_call>".startsWith(tail) ||- "<tool_response>".startsWith(tail) || "</tool_response>".startsWith(tail) ||- "<|im_end|>".startsWith(tail)- ) {- out = out.substring(0, open)- }- }- return out- }- }-}
photos/src/main/assets/clip/model_int8.onnx
diff --git a/photos/src/main/assets/clip/model_int8.onnx b/photos/src/main/assets/clip/model_int8.onnxnew file mode 100644index 0000000000..9f513c2ebdBinary files /dev/null and b/photos/src/main/assets/clip/model_int8.onnx differ