Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.
mlxrunner: grow the prefix trie by whole child nodes so restore points survive resumed prefills
Jesse Gross81f9a394e974
diff --git a/x/mlxrunner/cache_trie.go b/x/mlxrunner/cache_trie.goindex c312af601..535a0a2cd 100644--- a/x/mlxrunner/cache_trie.go+++ b/x/mlxrunner/cache_trie.go@@ -159,23 +159,17 @@ func findBestMatch(root *trieNode, tokens []trieKey) (path []*trieNode, matchedreturn path, pos}-// appendTokens either creates a new child node or extends the leaf in place,-// returning the node that now holds the tokens.-func (n *trieNode) appendTokens(root *trieNode, tokens []trieKey, endOffset int) *trieNode {- if n == root || len(n.children) > 0 || n.hasSnapshots() {- child := &trieNode{- tokens: make([]trieKey, len(tokens)),- endOffset: endOffset,- parent: n,- lastUsed: n.lastUsed,- }- copy(child.tokens, tokens)- n.children = append(n.children, child)- return child+// appendChild creates a child node holding the tokens.+func (n *trieNode) appendChild(tokens []trieKey, endOffset int) *trieNode {+ child := &trieNode{+ tokens: make([]trieKey, len(tokens)),+ endOffset: endOffset,+ parent: n,+ lastUsed: n.lastUsed,}- n.tokens = append(n.tokens, tokens...)- n.endOffset = endOffset- return n+ copy(child.tokens, tokens)+ n.children = append(n.children, child)+ return child}// removeNode removes a leaf node from the trie.diff --git a/x/mlxrunner/cache_trie_test.go b/x/mlxrunner/cache_trie_test.goindex e5280aeac..2232af41e 100644--- a/x/mlxrunner/cache_trie_test.go+++ b/x/mlxrunner/cache_trie_test.go@@ -170,7 +170,7 @@ func TestFindSplitAppendSequence(t *testing.T) {matchedInEdge := matched - lastNode.startOffset()split := splitNode(lastNode, matchedInEdge, nil, nil)- split.appendTokens(root, []trieKey{6, 7}, 5)+ split.appendChild([]trieKey{6, 7}, 5)if len(root.children) != 1 {t.Fatalf("root should have 1 child, got %d", len(root.children))@@ -200,7 +200,7 @@ func TestFindSplitAppendSequence(t *testing.T) {func TestRepeatedBranching(t *testing.T) {root := &trieNode{lastUsed: time.Now()}- root.appendTokens(root, []trieKey{1, 2, 3, 4, 5}, 5)+ root.appendChild([]trieKey{1, 2, 3, 4, 5}, 5)_, matchedB := findBestMatch(root, []trieKey{1, 2, 3, 6, 7})if matchedB != 3 {@@ -208,14 +208,14 @@ func TestRepeatedBranching(t *testing.T) {}nodeA := root.children[0]split1 := splitNode(nodeA, 3, nil, nil)- split1.appendTokens(root, []trieKey{6, 7}, 5)+ split1.appendChild([]trieKey{6, 7}, 5)_, matchedC := findBestMatch(root, []trieKey{1, 2, 8, 9})if matchedC != 2 {t.Fatalf("C: expected 2 matched, got %d", matchedC)}split2 := splitNode(split1, 2, nil, nil)- split2.appendTokens(root, []trieKey{8, 9}, 4)+ split2.appendChild([]trieKey{8, 9}, 4)_, mA := findBestMatch(root, []trieKey{1, 2, 3, 4, 5})if mA != 5 {diff --git a/x/mlxrunner/prefix_cache.go b/x/mlxrunner/prefix_cache.goindex f6e8d2dec..f48f3e2f5 100644--- a/x/mlxrunner/prefix_cache.go+++ b/x/mlxrunner/prefix_cache.go@@ -7,7 +7,9 @@// - Only one path through the trie is "active" (backed by live MLX arrays)// at a time. Switching paths pages in the new path from its snapshots.// - Every node carries its snapshots from creation: prefill captures for-// prompt segments, a page-out at close for generated ones.+// prompt segments, a page-out at close for generated ones. Sliceable+// (KV) layers always span exactly the node's edge; whole-state layers+// (recurrent, rotating) keep entries only at node ends.// - All cache layers must stay at the same token offset.// - Sibling edges must not share a common token prefix (compressed trie// invariant).@@ -406,7 +408,9 @@ func (s *cacheSession) attachPrefillSnapshots() {frontier.user = true}s.attachCapturedSnapshots(frontier, rows[i])+ c.compactPath()}+ c.enforceEvictionPolicy()}// attachCapturedSnapshots stores pre-captured snapshots on a trie node. Unlike@@ -441,12 +445,11 @@ func (s *cacheSession) attachCapturedSnapshots(node *trieNode, snaps []cache.Sna}node.lastUsed = time.Now()slog.Debug("created snapshot", "offset", node.endOffset)- c.enforceEvictionPolicy()}// advancePath advances the active path from the current frontier by matching// tokens against existing trie children, splitting partial matches, and-// appending any remaining tokens as new nodes. Returns the new frontier.+// appending any remaining tokens as a new child node. Returns the new frontier.func (c *prefixCache) advancePath(frontier *trieNode, tokens []trieKey, endOffset int) *trieNode {// Check if existing children already cover some or all of tokens.// tokens may span multiple trie nodes when extending a previous run's@@ -469,20 +472,28 @@ func (c *prefixCache) advancePath(frontier *trieNode, tokens []trieKey, endOffsedest := matchPath[len(matchPath)-1]if len(remaining) > 0 {- // Drop non-user snapshots so appendTokens can extend in-place- // rather than creating a new child node.- if len(dest.children) == 0 && !dest.user {- dest.setSnapshots(nil, &c.pagedOutBytes)- }- newDest := dest.appendTokens(c.root, remaining, endOffset)- if newDest != dest {- c.activePath = append(c.activePath, newDest)- }- dest = newDest+ dest = dest.appendChild(remaining, endOffset)+ c.activePath = append(c.activePath, dest)}return dest}+// compactPath absorbs the active path's last node into its parent when the+// parent is a non-user node with no other children, keeping consecutive+// non-user segments compressed into one node.+func (c *prefixCache) compactPath() {+ n := len(c.activePath)+ if n < 2 {+ return+ }+ parent := c.activePath[n-2]+ if parent == c.root || parent.user || len(parent.children) != 1 {+ return+ }+ mergeWithChild(parent, c.caches, &c.pagedOutBytes)+ c.activePath = c.activePath[:n-1]+}+// pageOut captures a fresh node's state from the live caches, which rest// exactly at its end. Nodes reached by traversal already carry snapshots.func (c *prefixCache) pageOut(node *trieNode) {@@ -561,12 +572,14 @@ func (s *cacheSession) close() {}// Advance the trie frontier with any newly generated tokens and page- // the new segment out.+ // the new segment out. Merging after the page-out combines covered+ // snapshots.if len(c.activePath) > 0 {frontier := c.activePath[len(c.activePath)-1]if offset > frontier.endOffset {newTokens := stored[frontier.endOffset:offset]c.pageOut(c.advancePath(frontier, newTokens, offset))+ c.compactPath()}c.activePath[len(c.activePath)-1].lastUsed = time.Now()}diff --git a/x/mlxrunner/prefix_cache_scenario_test.go b/x/mlxrunner/prefix_cache_scenario_test.gonew file mode 100644index 000000000..d0ee003b7--- /dev/null+++ b/x/mlxrunner/prefix_cache_scenario_test.go@@ -0,0 +1,267 @@+package mlxrunner++import (+ "bytes"+ "fmt"+ "log/slog"+ "slices"+ "strings"+ "testing"++ "github.com/ollama/ollama/x/mlxrunner/cache"+)++// Scenario tests drive prefixCache through multi-request timelines on the+// production cache layout of a hybrid model with MTP speculation: interleaved+// recurrent (GDN) and rewindable (attention KV) target layers plus a draft KV+// cache with one token of look-ahead. They verify the cache lifecycle+// invariants: a request extending the active conversation resumes exactly, a+// request diverging below the frontier restores to within the capture cadence+// of its match, and every stored snapshot spans exactly its node's edge.++// The capture cadence of the scenario prompts: a snapshot every interval+// tokens plus one preThinking tokens before each prompt's end.+const (+ interval = 8+ preThinking = 4+)++// restoreBound is how far a restore may trail its match. Captures land every+// interval tokens and preThinking tokens before a prompt's end, shifted back+// by the draft look-ahead, and the tokens generated or dropped since the last+// prompt have no user capture of their own.+func (e *hybridEnv) restoreBound(prevGen, dropped int) int {+ return interval + preThinking + e.pc.draftLookahead + prevGen + dropped+}++// captureWarns redirects slog to a buffer for the duration of the test and+// returns a func that reports captured output.+func captureWarns(t *testing.T) func() string {+ t.Helper()+ var buf bytes.Buffer+ old := slog.Default()+ slog.SetDefault(slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelDebug})))+ t.Cleanup(func() { slog.SetDefault(old) })+ return func() string { return buf.String() }+}++// hybridEnv mirrors the production layout for a hybrid model with MTP:+// interleaved recurrent (GDN) and rewindable (attention KV) target layers,+// then the draft KV cache last, with draftLookahead=1.+type hybridEnv struct {+ pc *prefixCache+ draft *fakeRewindableCache+}++func newHybridEnv() *hybridEnv {+ tr := &snapshotTracker{}+ targets := []cache.Cache{+ &fakeRecurrentCache{tracker: tr},+ &fakeRewindableCache{tracker: tr},+ &fakeRecurrentCache{tracker: tr},+ &fakeRewindableCache{tracker: tr},+ }+ draft := &fakeRewindableCache{tracker: tr}+ pc := &prefixCache{caches: append(targets, draft)}+ pc.draftLookahead = 1+ return &hybridEnv{pc: pc, draft: draft}+}++// kvLayers returns the cache indices whose snapshots are position-sliceable.+func (e *hybridEnv) kvLayers() []int {+ var layers []int+ for i, c := range e.pc.caches {+ if _, ok := c.(*fakeRewindableCache); ok {+ layers = append(layers, i)+ }+ }+ return layers+}++// tokenStream hands out distinct tokens so prompts never collide by accident.+type tokenStream struct{ next int32 }++func (ts *tokenStream) fresh(n int) []int32 {+ out := make([]int32, n)+ for i := range out {+ ts.next+++ out[i] = ts.next+ }+ return out+}++// periodic returns the scenario capture schedule for a prompt: every interval+// tokens, plus one preThinking tokens before the end.+func periodic(promptLen int) []int {+ var offs []int+ for o := interval; o < promptLen; o += interval {+ offs = append(offs, o)+ }+ if end := promptLen - preThinking; end > 0 {+ offs = append(offs, end)+ }+ return offs+}++// parseBeginLine extracts the counters from a begin log line. ok is false for+// any other line.+func parseBeginLine(line string) (total, matched, cached, left int, ok bool) {+ if !strings.Contains(line, "cache hit") && !strings.Contains(line, "cache miss") {+ return 0, 0, 0, 0, false+ }+ for _, f := range strings.Fields(line) {+ fmt.Sscanf(f, "total=%d", &total)+ fmt.Sscanf(f, "matched=%d", &matched)+ fmt.Sscanf(f, "cached=%d", &cached)+ fmt.Sscanf(f, "left=%d", &left)+ }+ return total, matched, cached, left, true+}++// beginLog scans the captured log for begin lines, one call per request.+type beginLog struct {+ t *testing.T+ logs func() string+ mark int+}++// next returns the counters of the begin line logged since the previous call.+func (b *beginLog) next() (total, matched, cached, left int) {+ b.t.Helper()+ out := b.logs()+ seg := out[b.mark:]+ b.mark = len(out)+ for _, l := range strings.Split(seg, "\n") {+ if total, matched, cached, left, ok := parseBeginLine(l); ok {+ return total, matched, cached, left+ }+ }+ b.t.Fatalf("no begin line in:\n%s", seg)+ return 0, 0, 0, 0+}++// runRequest mirrors the production pipeline for a successful request:+// begin -> schedule periodic snapshots -> prefill all but the last prompt+// token -> attach -> decode generated tokens (all caches level, last token+// unforwarded) -> close.+func (e *hybridEnv) runRequest(t *testing.T, inputs, generated []int32) *cacheSession {+ t.Helper()+ pc := e.pc+ session := pc.begin(inputs, nil)++ session.schedulePrefillSnapshots(periodic(len(inputs)))+ base := pc.minCacheOffset()+ seed := len(inputs) - 1+ if base < seed {+ feedAll(pc.caches, inputs[base:seed])+ }+ session.attachPrefillSnapshots()++ if len(generated) > 0 {+ session.outputs = generated+ feedAll(pc.caches, inputs[seed:])+ feedAll(pc.caches, generated[:len(generated)-1])+ }+ session.close()+ return session+}++// checkSnapshotCoverage asserts the snapshot invariant over the trie: every+// node carries a snapshot for each position-sliceable (KV) layer, spanning+// exactly its edge.+func checkSnapshotCoverage(t *testing.T, pc *prefixCache, kvLayers []int) {+ t.Helper()+ walkNodes(pc.root, func(n *trieNode) bool {+ if n.endOffset == n.startOffset() { // root has an empty edge+ return true+ }+ for _, layer := range kvLayers {+ var snap *fakeSnapshot+ if layer < len(n.snapshots) && n.snapshots[layer] != nil {+ snap = n.snapshots[layer].(*fakeSnapshot)+ }+ if snap == nil {+ t.Errorf("node [%d,%d) layer %d has no snapshot", n.startOffset(), n.endOffset, layer)+ continue+ }+ if snap.from != n.startOffset() || snap.to != n.endOffset {+ t.Errorf("node [%d,%d) layer %d snapshot [%d,%d) does not span the edge", n.startOffset(), n.endOffset, layer, snap.from, snap.to)+ }+ }+ return true+ })+}++// TestScenarioConversationTurns advances a conversation turn by turn. A turn+// keeping the whole previous response extends the frontier and must resume+// exactly; a turn dropping part of it diverges below the frontier and must+// restore to within the capture cadence of its match; and a switch to an+// unrelated session must not cost the conversation more than that same bound+// when the next turn returns to it.+func TestScenarioConversationTurns(t *testing.T) {+ logs := captureWarns(t)+ e := newHybridEnv()+ ts := &tokenStream{}+ begins := &beginLog{t: t, logs: logs}++ type turn struct {+ keepGen int // previous generation kept in the prompt (-1 = all)+ newTail int+ genLen int+ away bool // an unrelated session runs before this turn+ }+ turns := []turn{+ {keepGen: 3, newTail: 9, genLen: 6},+ {keepGen: -1, newTail: 4, genLen: 5},+ {keepGen: 4, newTail: 6, genLen: 7},+ {keepGen: -1, newTail: 5, genLen: 6},+ {keepGen: 5, newTail: 8, genLen: 8},+ {keepGen: 4, newTail: 7, genLen: 6, away: true},+ {keepGen: -1, newTail: 6, genLen: 7},+ {keepGen: 3, newTail: 8, genLen: 6},+ {keepGen: -1, newTail: 5, genLen: 5},+ {keepGen: 4, newTail: 9, genLen: 6},+ }++ prompt := ts.fresh(50)+ gen := ts.fresh(6)+ e.runRequest(t, prompt, gen)+ begins.next()+ stream := prompt // committed conversation, minus the latest response+ lastGen := gen // latest response++ for i, tn := range turns {+ if tn.away {+ e.runRequest(t, ts.fresh(24), ts.fresh(4))+ begins.next()+ }++ dropped := 0+ var p []int32+ if tn.keepGen < 0 {+ p = slices.Concat(stream, lastGen, ts.fresh(tn.newTail))+ } else {+ dropped = len(lastGen) - tn.keepGen+ p = slices.Concat(stream, slices.Clone(lastGen[:tn.keepGen]), ts.fresh(tn.newTail))+ }+ bound := e.restoreBound(len(lastGen), dropped)+ g := ts.fresh(tn.genLen)+ e.runRequest(t, p, g)++ _, matched, cached, _ := begins.next()+ if dropped == 0 && !tn.away && cached != matched {+ t.Errorf("turn %d: extension resumed cached=%d != matched=%d", i, cached, matched)+ }+ if cached < matched-bound {+ t.Errorf("turn %d: cached=%d fell more than %d below matched=%d", i, cached, bound, matched)+ }++ stream = p+ lastGen = g+ }++ if out := logs(); strings.Contains(out, "failed to restore cache") {+ t.Errorf("freeAll warn fired:\n%s", out)+ }+ checkSnapshotCoverage(t, e.pc, e.kvLayers())+}