Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.
mlxrunner: keep cache boundaries out of non-causal media items
Jesse Gross45a02807e2dd
diff --git a/x/mlxrunner/prefix_cache.go b/x/mlxrunner/prefix_cache.goindex b149ad896..79050de6f 100644--- a/x/mlxrunner/prefix_cache.go+++ b/x/mlxrunner/prefix_cache.go@@ -19,6 +19,8 @@// - All cache layers must stay at the same token offset.// - Draft caches are settled whenever the trie captures, pages out, or// rewinds: no entry is still waiting on the next token.+// - A non-causal media item's tokens are evaluated in one batch: no node+// boundary or resume point lies strictly inside them.// - Sibling edges must not share a common token prefix (compressed trie// invariant).// - begin() always re-evaluates at least one token so the pipeline can seed@@ -64,6 +66,7 @@ type cacheSession struct {cache *prefixCacheinputs []int32effInputs []uint32 // inputs' key alphabet, media folds applied+ items []mediaItemoutputs []int32caches []cache.Cache@@ -104,6 +107,10 @@ func (c *prefixCache) begin(inputs []int32, items []mediaItem) *cacheSession {if matched == len(inputs) && matched > 0 {matchPath, matched = findBestMatch(c.root, keys[:matched-1])}+ // A match ending inside a non-causal media item resumes before it.+ if item := insideAtomicItem(items, matched); item != nil {+ matchPath, matched = findBestMatch(c.root, keys[:item.pos])+ }// Switch to the matched path, paging in/out as needed.c.switchToPath(matchPath, matched)@@ -116,6 +123,7 @@ func (c *prefixCache) begin(inputs []int32, items []mediaItem) *cacheSession {cache: c,inputs: inputs,effInputs: effInputs,+ items: items,caches: c.caches,remaining: remaining,}@@ -135,6 +143,18 @@ func (c *prefixCache) begin(inputs []int32, items []mediaItem) *cacheSession {return session}+// insideAtomicItem returns the non-causal media item that offset lies strictly+// inside, or nil.+func insideAtomicItem(items []mediaItem, offset int) *mediaItem {+ for i := range items {+ item := &items[i]+ if item.atomic() && item.pos < offset && offset < item.pos+item.length {+ return item+ }+ }+ return nil+}+// effectiveKeyTokens returns the per-position key alphabet: the token ID// outside media expansions, the item's fold value across each expansion's// whole range.@@ -287,7 +307,8 @@ pageIn:// prefill records interior states without the caller breaking the batch. A// passed offset names a token prefix; the capture lands at the deepest// state that prefix alone determines (offset - draftLookahead), which is where-// a prompt sharing exactly that prefix restores. The offsets are merged with+// a prompt sharing exactly that prefix restores. An offset inside a non-causal+// media item's tokens moves past them. The offsets are merged with// any snapshots begin already scheduled (e.g. a branch point), with coinciding// offsets upgraded to user so compaction keeps them.//@@ -299,6 +320,9 @@ func (s *cacheSession) schedulePrefillSnapshots(offsets []int) {base := c.minCacheOffset()for _, offset := range offsets {offset -= c.draftLookahead+ if item := insideAtomicItem(s.items, offset); item != nil {+ offset = item.pos + item.length+ }if offset <= base || offset > len(s.inputs) {continue}diff --git a/x/mlxrunner/prefix_cache_test.go b/x/mlxrunner/prefix_cache_test.goindex cb7165b66..e5617534b 100644--- a/x/mlxrunner/prefix_cache_test.go+++ b/x/mlxrunner/prefix_cache_test.go@@ -7,6 +7,7 @@ import ("github.com/ollama/ollama/x/mlxrunner/cache""github.com/ollama/ollama/x/mlxrunner/mlx"+ "github.com/ollama/ollama/x/mlxrunner/model/base")// snapshotTracker records every fakeSnapshot created and every Close() call@@ -1011,6 +1012,46 @@ func TestSnapshotBeyondPrefillSkipped(t *testing.T) {})}+// TestAtomicMediaBoundaries verifies that a non-causal media item is never+// split by the cache: a capture scheduled inside its tokens lands at their+// end, and a prompt whose match ends inside them resumes before them.+func TestAtomicMediaBoundaries(t *testing.T) {+ forEachEnv(t, func(t *testing.T, env *testEnv) {+ pc := env.pc+ inputs := []int32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}+ const itemPos, itemLen = 3, 6+ items := []mediaItem{{pos: itemPos, length: itemLen, fold: 1 << 31, item: &base.PreparedItem{}}}++ session := pc.begin(inputs, items)+ session.schedulePrefillSnapshots([]int{itemPos + itemLen/2})+ feedAll(pc.caches, inputs[pc.minCacheOffset():len(inputs)-1])+ session.attachPrefillSnapshots()+ session.close()++ walkNodes(pc.root, func(n *trieNode) bool {+ if itemPos < n.endOffset && n.endOffset < itemPos+itemLen {+ t.Errorf("trie node ends at %d, inside the item's tokens [%d,%d)", n.endOffset, itemPos, itemPos+itemLen)+ }+ return true+ })+ if !nodeExistsAtOffset(pc.root, itemPos+itemLen) {+ t.Errorf("capture inside the item did not move to its end %d", itemPos+itemLen)+ }++ // A prompt ending inside the item matches the stored path through its+ // last token, which would put the resume point inside the item.+ short := inputs[:itemPos+itemLen-2]+ shortItems := []mediaItem{{pos: itemPos, length: len(short) - itemPos, fold: 1 << 31, item: &base.PreparedItem{}}}+ session = pc.begin(short, shortItems)+ if resumed := len(short) - len(session.remaining); resumed > itemPos {+ t.Errorf("resumed at %d, inside the item's tokens starting at %d", resumed, itemPos)+ }+ session.close()++ checkTrieInvariants(t, pc.root)+ })+}+// TestPrefillSnapshotsKeptOnCancel mirrors a prefill canceled after the caches// captured interior snapshots but before the success-path attach ran. Closing// the session attaches the crossed captures so a retry can resume from them,