openassistant: prefill the gemma4 system block when the service starts
- Commit
8fc61607f129d9216c805ee70bdd534e136b5021- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-27 01:34 UTC (1 month ago)
- Parents
1c92318
Diff
library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.ktindex 5edc0453f7..adde81defa 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Gemma4Handle.kt@@ -159,6 +159,31 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose return generateTokens(tail, limit, sampling, onToken) } + /**+ * Prefill the system block ([system] + [tools]) now, so the first [generate] with the same+ * pair reuses it and only feeds its own turn.+ *+ * The block is the bulk of a first prompt - about 1,900 positions with 25 tools - and without+ * this it is prefilled after the user has already sent the message. Also grows the cache to+ * the tier a first turn with a [limit] reply needs, so that turn does not re-plan either.+ * Returns false when the model is unavailable or the prefill fails.+ */+ fun prime(system: String?, tools: List<ToolDeclaration> = emptyList(), limit: Int = DEFAULT_REPLY): Boolean {+ if (handle == 0L) return false+ val ids = encodePrompt(PromptBuilder().apply { appendHeader(system, declareTools(tools)) }.text())+ val prior = cachedIds+ if (prior != null && prior.size >= ids.size && ids.indices.all { prior[it] == ids[it] }) return true+ val wanted = ids.size + limit + PromptConstants.PROMPT_SLACK_POSITIONS+ if (MlNative.capacityGemma4(handle) in 1 until wanted) MlNative.growGemma4(handle, wanted)+ reset()+ if (MlNative.pushGemma4(handle, ids) < 0 || MlNative.flushGemma4(handle) != ids.size) {+ reset()+ return false+ }+ cachedIds = ids+ return true+ }+ /** Last text part of the prompt, or null (with a log) when the prompt is empty. */ private fun validatePromptTail(parts: List<Part>): Part.Tokens? { // The last part is always the generation prompt, so it is text and it is not empty.@@ -495,6 +520,9 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose text.append(continuation) } + /** The text so far, for a builder that holds no media. */+ fun text(): String = text.toString()+ fun build(): List<Part> { if (text.isNotEmpty()) { parts.add(Part.Text(text.toString()))
library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktindex 1d5912310e..4c8d1ac11f 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt@@ -710,6 +710,9 @@ internal object MlNative { */ external fun seekGemma4(handle: Long, position: Int): Int + /** Prefill what [pushGemma4] deferred, now rather than with the next step. Position, or -1. */+ external fun flushGemma4(handle: Long): Int+ /** * Time a decode pass with and without the logits head, and log both. *
library/ml/src/main/rust/src/bridge_part8.rs
diff --git a/library/ml/src/main/rust/src/bridge_part8.rs b/library/ml/src/main/rust/src/bridge_part8.rsindex 9808c5840e..9c8dd44f6f 100644--- a/library/ml/src/main/rust/src/bridge_part8.rs+++ b/library/ml/src/main/rust/src/bridge_part8.rs@@ -172,6 +172,34 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_seekGemma } } +/// Run the pushed tokens now instead of with the next step. Returns the position, or -1.+///+/// For warming a prompt prefix ahead of the first turn: without this the prefill would wait+/// for the step that ends the user's turn.+///+/// # Safety+///+/// Called only by the JVM, with a live handle from `createGemma4`.+#[no_mangle]+pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_flushGemma4<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+ handle: jlong,+) -> jint {+ if handle == 0 {+ return -1;+ }+ // SAFETY: the caller guarantees the handle came from `createGemma4` and is still live.+ let handle = unsafe { &mut *(handle as *mut Gemma4Handle) };+ match handle.flush() {+ Ok(()) => jint::try_from(handle.position).unwrap_or(-1),+ Err(e) => {+ log(&format!("gemma4 cannot flush: {e}"));+ -1+ }+ }+}+ /// Start a new conversation on the same handle. /// /// Only the position is reset. Attention reads `[window_start, prefix]`, so cache rows past the
openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.ktindex 5b8790d26f..ff75bea453 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/MamlChatEngine.kt@@ -62,12 +62,40 @@ class MamlChatEngine(private val modelDir: File) : AutoCloseable { private var audio: Gemma4AudioHandle? = null private var towerIdleJob: Job? = null private var prefixKey: Int? = null+ private var warm: Pair<String, AssistantTools>? = null /** Loads the model if needed; false when it cannot come up. */ suspend fun load(): Boolean = mutex.withLock { withContext(engineThread) { model() != null } } + /**+ * Prefills the chat system block now, so the first message only feeds its own turn.+ *+ * Remembered, so [extract] (a different system prompt, which replaces the cache) can put it+ * back afterwards.+ */+ suspend fun warmUp(system: String, tools: AssistantTools): Boolean = mutex.withLock {+ warm = system to tools+ withContext(engineThread) { primeLocked(system, tools) }+ }++ private fun primeLocked(system: String, tools: AssistantTools): Boolean {+ val model = model() ?: return false+ val declarations = tools.declarations+ seedPrefix(model, system, declarations)+ val started = System.nanoTime()+ val primed = model.prime(system, declarations, CHAT_REPLY_LIMIT)+ Log.status(TAG, "warm-up ${if (primed) "done" else "failed"} in ${(System.nanoTime() - started) / NANOS_PER_MILLI} ms")+ return primed+ }++ private fun rewarmAfterExtract() {+ val (system, tools) = warm ?: return+ scope.launch { mutex.withLock { withContext(engineThread) { primeLocked(system, tools) } } }+ }+ suspend fun chat(request: ChatRequest, tools: AssistantTools, onText: (String) -> Boolean): ChatResult = mutex.withLock {+ warm = request.system to tools val model = withContext(engineThread) { model() } ?: return@withLock ChatResult.Unavailable val declarations = tools.declarations val current = withContext(engineThread) { currentTurn(request) }@@ -116,7 +144,7 @@ class MamlChatEngine(private val modelDir: File) : AutoCloseable { val turn = currentTurn(ChatRequest(system, emptyList(), userText, imagePaths)) model.generate(listOf(turn), system, emptyList(), EXTRACT_REPLY_LIMIT, "", Sampling.Greedy, onText) }- }+ }.also { rewarmAfterExtract() } private fun model(): Gemma4Handle? { handle?.takeIf { it.isAvailable }?.let { return it }@@ -215,6 +243,7 @@ class MamlChatEngine(private val modelDir: File) : AutoCloseable { const val TOWER_IDLE_MILLIS = 3 * 60_000L const val MAX_IMAGE_SIDE = 1024 const val LOG_CHARS = 120+ const val NANOS_PER_MILLI = 1_000_000L fun decodeDownscaled(path: String): Bitmap? { val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
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..add0f0fb5e 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -153,6 +153,7 @@ class InferenceService : Service() { serviceScope.launch { try { ensureEngineInitialized()+ engine?.warmUp(systemPrompt(), tools) } catch (expected: Exception) { Log.error("InferenceService", "Error pre-warming engine", expected) }