library:ml: Bonsai-8B q1 ONNX handle plus BPE tokenizer
- Commit
fea3fa39315928293ae3e1cad1d6f0fa9bada6b7- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-14 20:20 UTC (2 months ago)
- Parents
fb6b2db
Diff
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.ktnew file mode 100644index 0000000000..477e2a7861--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/BonsaiHandle.kt@@ -0,0 +1,394 @@+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.ktnew file mode 100644index 0000000000..2887fe015f--- /dev/null+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/BonsaiTokenizer.kt@@ -0,0 +1,213 @@+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)+ }+ }+}