Modern Apps git

← Modern-Apps.git

library/ml: multimodal turns reset the Gemma 4 KV cache instead of appending to it

Commit
17b6f515888dff601a4a2f2aa4df502b05ec1863
Author
Vayun Mathur <[email protected]>
When
2026-12-01 10:01 UTC (4 days ago)
Parents
5593e54
generate() re-feeds the whole prompt every turn, but
reuseSharedCache returned early for multimodal prompts
(flattenTextParts null) with no seek and no reset — while
native push appends at the current position. Turn 1 (text)
left the cache at position P; turn 2 (same conversation plus
an image) re-fed the full prompt starting at P, so the model
attended over [turn-1 history, turn-2 full prompt] —
duplicated history at shifted positions and spuriously
inflated context use — 'a fluent reply to a conversation
that never happened', against the handle's own docs.
cachedIds also survived, so later prefix matching described
tokens the arena does not hold at those positions.

The prefix computation is extracted to a pure reuseLength
returning 0 for multimodal, so the existing reset branch
runs (native rewind plus cachedIds = null) before
re-feeding; text-path arithmetic is unchanged. Four tests
pin multimodal = 0, no-record = 0, the shared-prefix/final-
token cap and the shorter-side bound; the handle cannot be
constructed on the JVM (documented), so the tests pin the
pure seam, as with fitAudio. Other handles' close/use
contracts were audited and cleared. Verified:
:library:ml unit+native suites and lint BUILD SUCCESSFUL.

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 8b21aff9cf..ad2cb2b11d 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@@ -280,15 +280,13 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose      * correct, because the tokens that produced it have not changed.      */     private fun reuseSharedCache(flat: IntArray?, length: Int): Int {-        if (flat == null) return 0-        var reused = 0-        val prior = cachedIds-        if (prior != null) {-            // Never reuse the final token: its logits are the prediction this turn needs, so it-            // has to be fed through `stepGemma4` rather than sat in the cache.-            val ceiling = minOf(prior.size, flat.size - 1)-            while (reused < ceiling && prior[reused] == flat[reused]) reused++-        }+        // A multimodal prompt (flat == null) reuses nothing, so it lands in the reset+        // branch below like any other cache miss: the re-rendered prompt is re-fed from+        // position zero. It used to return early here, skipping the reset, so the new+        // prompt was appended after the previous turn's cache — the model attended over+        // the old conversation plus a second copy of the history, at shifted positions —+        // and the stale cachedIds record survived to misdescribe the arena afterwards.+        var reused = reuseLength(cachedIds, flat)         if (reused > 0 && MlNative.seekGemma4(handle, reused) == reused) {             Log.status(TAG, "reused $reused of $length positions, feeding ${length - reused}")         } else {@@ -682,6 +680,25 @@ class Gemma4Handle private constructor(internal val directory: File) : AutoClose             return out         } +        /**+         * How many leading positions of [flat] the cache may keep from [prior].+         *+         * Zero for a multimodal prompt ([flat] null: its soft tokens cannot be compared+         * against recorded ids, so the turn re-feeds after a reset) and when there is no+         * record. Never the final token: its logits are the prediction the turn needs,+         * so it has to be fed through `stepGemma4` rather than sat in the cache.+         *+         * Pure and `internal`, like [fitAudio], so the unit tests can pin the multimodal+         * case on the JVM — a `Gemma4Handle` itself cannot be constructed there.+         */+        internal fun reuseLength(prior: IntArray?, flat: IntArray?): Int {+            if (prior == null || flat == null) return 0+            val ceiling = minOf(prior.size, flat.size - 1)+            var reused = 0+            while (reused < ceiling && prior[reused] == flat[reused]) reused+++            return reused+        }+         /** The decoder. Native checks its graph id, so a wrong file fails at load. */         const val TEXT = "gemma4_text.maml" 
library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4CacheReuseTest.kt
diff --git a/library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4CacheReuseTest.kt b/library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4CacheReuseTest.ktnew file mode 100644index 0000000000..8444f0dde7--- /dev/null+++ b/library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4CacheReuseTest.kt@@ -0,0 +1,48 @@+package com.vayunmathur.library.ml++import com.vayunmathur.library.ml.Gemma4Handle.Companion.reuseLength+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Which leading cache positions [Gemma4Handle.generate] may keep between turns.+ *+ * A multimodal turn cannot flatten its prompt to token ids (`flat == null`), so it+ * re-feeds the whole prompt. That re-feed only starts a fresh conversation when the+ * reuse length is zero, because zero is what routes `reuseSharedCache` into its+ * reset branch. It used to return early for multimodal prompts instead, skipping+ * the reset: the re-rendered prompt was appended after the previous turn's cache+ * and the model attended over the old conversation plus a second copy of the+ * history, at shifted positions. These pin the zero, plus the text-path prefix+ * arithmetic it shares. Pure, following the `fitAudio` pattern: a `Gemma4Handle`+ * cannot be constructed on the JVM (see HandlesUnavailableTest).+ */+class Gemma4CacheReuseTest {+    @Test+    fun `a multimodal prompt reuses no cache positions`() {+        val prior = intArrayOf(11, 22, 33, 44)+        assertEquals(0, reuseLength(prior, null))+    }++    @Test+    fun `no recorded ids reuses nothing`() {+        assertEquals(0, reuseLength(null, intArrayOf(1, 2, 3)))+        assertEquals(0, reuseLength(null, null))+    }++    @Test+    fun `a shared text prefix is kept except the final token`() {+        val prior = intArrayOf(5, 6, 7, 8)+        // Identical prompts: all but the last position may stay, because the final+        // token's logits are the prediction the turn needs.+        assertEquals(3, reuseLength(prior, intArrayOf(5, 6, 7, 8)))+        assertEquals(2, reuseLength(prior, intArrayOf(5, 6, 99, 8)))+        assertEquals(0, reuseLength(prior, intArrayOf(42, 6, 7, 8)))+    }++    @Test+    fun `reuse never passes the shorter side`() {+        assertEquals(2, reuseLength(intArrayOf(1, 2), intArrayOf(1, 2, 3, 4)))+        assertEquals(0, reuseLength(intArrayOf(1), intArrayOf(1)))+    }+}