Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

mlxrunner: fold media identity into prefix-trie keys

Jesse Gross694487c65b62
diff --git a/x/mlxrunner/media.go b/x/mlxrunner/media.go
new file mode 100644
index 000000000..5bfa13440
--- /dev/null
+++ b/x/mlxrunner/media.go
@@ -0,0 +1,31 @@
+package mlxrunner
+
+import (
+ "encoding/binary"
+ "hash/fnv"
+
+ "github.com/ollama/ollama/x/mlxrunner/model/base"
+)
+
+// mediaItem is one media occurrence in a request's token stream.
+type mediaItem struct {
+ pos int
+ length int
+ fold uint32
+ item *base.PreparedItem
+}
+
+// foldValue derives an item's trie-key substitute: a hash of the raw
+// bytes and preprocessing dims, with bit 31 forced so it can never equal
+// a token ID.
+func foldValue(data []byte, dims []int) uint32 {
+ h := fnv.New64a()
+ h.Write(data)
+ var b [8]byte
+ for _, d := range dims {
+ binary.LittleEndian.PutUint64(b[:], uint64(d))
+ h.Write(b[:])
+ }
+ sum := h.Sum64()
+ return (uint32(sum>>32) ^ uint32(sum)) | 1<<31
+}
diff --git a/x/mlxrunner/media_test.go b/x/mlxrunner/media_test.go
new file mode 100644
index 000000000..2fea06c11
--- /dev/null
+++ b/x/mlxrunner/media_test.go
@@ -0,0 +1,68 @@
+package mlxrunner
+
+import (
+ "slices"
+ "testing"
+)
+
+func TestEffectiveKeyTokens(t *testing.T) {
+ tokens := []int32{10, 20, 500, 500, 500, 30}
+ items := []mediaItem{{pos: 2, length: 3, fold: foldValue([]byte("img"), []int{1})}}
+
+ eff := effectiveKeyTokens(tokens, items)
+ want := []uint32{10, 20, items[0].fold, items[0].fold, items[0].fold, 30}
+ if !slices.Equal(eff, want) {
+ t.Fatalf("got %v, want %v", eff, want)
+ }
+
+ // Text-only streams never alias a media stream: folds carry bit 31.
+ for _, e := range effectiveKeyTokens(tokens, nil) {
+ if e&(1<<31) != 0 {
+ t.Fatalf("token key %d has bit 31 set", e)
+ }
+ }
+}
+
+// Two prompts that differ only in their image diverge at the expansion's
+// first key — one position earlier under bigram packing — and prompts with
+// the same image share keys through the whole expansion.
+func TestKeyFoldDivergence(t *testing.T) {
+ prompt := func(fold uint32) []uint32 {
+ tokens := []int32{1, 2, 900, 900, 900, 3, 4}
+ return effectiveKeyTokens(tokens, []mediaItem{{pos: 2, length: 3, fold: fold}})
+ }
+ imgA := foldValue([]byte("a"), []int{1})
+ imgB := foldValue([]byte("b"), []int{1})
+ if imgA != foldValue([]byte("a"), []int{1}) {
+ t.Fatal("fold not deterministic")
+ }
+ if imgA == foldValue([]byte("a"), []int{2}) {
+ t.Fatal("different dims produced the same fold under identical bytes")
+ }
+
+ for _, lookahead := range []int{0, 1} {
+ pc := &prefixCache{draftLookahead: lookahead}
+ keysA := pc.key(prompt(imgA))
+ keysB := pc.key(prompt(imgB))
+ keysA2 := pc.key(prompt(imgA))
+
+ if !slices.Equal(keysA, keysA2) {
+ t.Fatalf("lookahead %d: same image produced different keys", lookahead)
+ }
+
+ // Bigram packing pulls the divergence one position early: the key
+ // before the expansion packs (token, fold). Keys re-converge in value
+ // after the expansion (shared trailing text), which is fine — the trie
+ // paths forked at the first difference.
+ divergeAt, convergeAt := 2-lookahead, 5
+ for i := range keysA {
+ same := keysA[i] == keysB[i]
+ if i < divergeAt && !same {
+ t.Fatalf("lookahead %d: keys diverge at %d, before the expansion", lookahead, i)
+ }
+ if i >= divergeAt && i < convergeAt && same {
+ t.Fatalf("lookahead %d: keys agree at %d, inside the expansion", lookahead, i)
+ }
+ }
+ }
+}
diff --git a/x/mlxrunner/pipeline.go b/x/mlxrunner/pipeline.go
index 1a3df8e95..d9cf6ef47 100644
--- a/x/mlxrunner/pipeline.go
+++ b/x/mlxrunner/pipeline.go
@@ -82,7 +82,7 @@ func (r *Runner) TextGenerationPipeline(ctx context.Context, request Request) er
inputs := request.Tokens
- session := r.cache.begin(inputs)
+ session := r.cache.begin(inputs, nil)
defer session.close()
caches := session.caches
diff --git a/x/mlxrunner/prefix_cache.go b/x/mlxrunner/prefix_cache.go
index 1e559538d..3da72704b 100644
--- a/x/mlxrunner/prefix_cache.go
+++ b/x/mlxrunner/prefix_cache.go
@@ -52,9 +52,10 @@ type pendingSnapshot struct {
// Callers should append generated tokens to outputs and
// defer close to save the cache state.
type cacheSession struct {
- cache *prefixCache
- inputs []int32
- outputs []int32
+ cache *prefixCache
+ inputs []int32
+ effInputs []uint32 // inputs' key alphabet, media folds applied
+ outputs []int32
caches []cache.Cache
remaining []int32
@@ -81,10 +82,11 @@ func (c *prefixCache) ensureRoot() {
// begin prepares caches for a new request. It finds the nearest
// matching cache or creates new caches if none match.
-func (c *prefixCache) begin(inputs []int32) *cacheSession {
+func (c *prefixCache) begin(inputs []int32, items []mediaItem) *cacheSession {
c.ensureRoot()
- keys := c.key(inputs)
+ effInputs := effectiveKeyTokens(inputs, items)
+ keys := c.key(effInputs)
matchPath, matched := findBestMatch(c.root, keys)
originalMatched := matched
@@ -104,6 +106,7 @@ func (c *prefixCache) begin(inputs []int32) *cacheSession {
session := &cacheSession{
cache: c,
inputs: inputs,
+ effInputs: effInputs,
caches: c.caches,
remaining: remaining,
}
@@ -123,12 +126,26 @@ func (c *prefixCache) begin(inputs []int32) *cacheSession {
return session
}
-// key converts tokens to trie keys, one per restorable cache offset. A model
-// that drafts through MTP-style draft caches pairs each cache slot with the
-// token after it, so slot i is reusable only if token i+1 also matched. The
-// key for offset i then packs (token i, token i+1): matching k keys verifies
-// k+1 tokens, making every match a valid restore point.
-func (c *prefixCache) key(tokens []int32) []trieKey {
+// effectiveKeyTokens returns the per-position key alphabet: the token ID
+// outside media expansions, the item's fold value across each expansion's
+// whole range.
+func effectiveKeyTokens(tokens []int32, items []mediaItem) []uint32 {
+ eff := make([]uint32, len(tokens))
+ for i, t := range tokens {
+ eff[i] = uint32(t)
+ }
+ for _, item := range items {
+ for i := item.pos; i < item.pos+item.length; i++ {
+ eff[i] = item.fold
+ }
+ }
+ return eff
+}
+
+// key packs (token i, token i+1) per restorable offset: draft caches
+// pair each slot with the next token, so matching k keys verifies k+1
+// tokens and every match is a valid restore point.
+func (c *prefixCache) key(tokens []uint32) []trieKey {
keys := make([]trieKey, max(len(tokens)-c.draftLookahead, 0))
switch c.draftLookahead {
case 0:
@@ -137,7 +154,7 @@ func (c *prefixCache) key(tokens []int32) []trieKey {
}
case 1:
for i := range keys {
- keys[i] = trieKey(uint32(tokens[i]))<<32 | trieKey(uint32(tokens[i+1]))
+ keys[i] = trieKey(tokens[i])<<32 | trieKey(tokens[i+1])
}
default:
panic(fmt.Sprintf("prefixCache: unsupported draft look-ahead %d", c.draftLookahead))
@@ -145,6 +162,20 @@ func (c *prefixCache) key(tokens []int32) []trieKey {
return keys
}
+// storedKeys keys the session's evaluated stream: the prompt's effective
+// tokens plus generated tokens, which are never media.
+func (s *cacheSession) storedKeys() []trieKey {
+ eff := s.effInputs
+ if len(s.outputs) > 0 {
+ eff = make([]uint32, 0, len(s.effInputs)+len(s.outputs))
+ eff = append(eff, s.effInputs...)
+ for _, t := range s.outputs {
+ eff = append(eff, uint32(t))
+ }
+ }
+ return s.cache.key(eff)
+}
+
// switchToPath transitions from the current active path to a new path,
// paging out diverging segments and paging in the new path.
func (c *prefixCache) switchToPath(newPath []*trieNode, matched int) {
@@ -381,7 +412,7 @@ func (s *cacheSession) attachPrefillSnapshots() {
// no captured state. Skip it rather than materialize a node whose edge
// claims tokens the cache never wrote. Closing its (nil) row is a no-op.
reached := c.minCacheOffset()
- stored := c.key(append(s.inputs, s.outputs...))
+ stored := s.storedKeys()
for i, p := range pending {
if p.offset > reached {
// Never crossed by a write, so the row is nil; close any entry
@@ -511,7 +542,7 @@ func (s *cacheSession) close() {
// The caches never advance past the stored keys; anything more
// means positions desynced.
c := s.cache
- stored := c.key(append(s.inputs, s.outputs...))
+ stored := s.storedKeys()
if offset > len(stored) {
panic(fmt.Sprintf("cache: offset %d exceeds %d stored keys", offset, len(stored)))
}
diff --git a/x/mlxrunner/prefix_cache_test.go b/x/mlxrunner/prefix_cache_test.go
index 1f5a5703f..31708c7b6 100644
--- a/x/mlxrunner/prefix_cache_test.go
+++ b/x/mlxrunner/prefix_cache_test.go
@@ -479,7 +479,7 @@ type requestResult struct {
func simulateRequest(t *testing.T, pc *prefixCache, inputs, generated []int32, userSnapshotAt ...int) requestResult {
t.Helper()
- session := pc.begin(inputs)
+ session := pc.begin(inputs, nil)
var snapshotOffsets []int
for _, at := range userSnapshotAt {
if at > 0 {
@@ -692,7 +692,7 @@ func TestBranchCreationAndReuse(t *testing.T) {
// Verify trie was populated by close(): everything in the caches
// is findable; the last generated token is not.
seqA := []int32{1, 2, 3, 4, 5, 6, 7, 8, 20, 21}
- _, mA := findBestMatch(pc.root, pc.key(seqA))
+ _, mA := findBestMatch(pc.root, pc.key(effectiveKeyTokens(seqA, nil)))
if want := len(seqA) - 1; mA != want {
t.Fatalf("A findable: expected %d matched, got %d", want, mA)
}
@@ -721,11 +721,11 @@ func TestBranchCreationAndReuse(t *testing.T) {
env.assertAllTokens(t, "after B", []int32{1, 2, 3, 4, 5, 10, 11, 12, 30})
// Both A and B should be findable in the trie.
- _, mA2 := findBestMatch(pc.root, pc.key(seqA))
+ _, mA2 := findBestMatch(pc.root, pc.key(effectiveKeyTokens(seqA, nil)))
if mA2 < 5 {
t.Fatalf("A still findable: expected >= 5 matched, got %d", mA2)
}
- _, mB := findBestMatch(pc.root, pc.key([]int32{1, 2, 3, 4, 5, 10, 11, 12, 30, 31}))
+ _, mB := findBestMatch(pc.root, pc.key(effectiveKeyTokens([]int32{1, 2, 3, 4, 5, 10, 11, 12, 30, 31}, nil)))
if mB < 5 {
t.Fatalf("B findable: expected >= 5 matched, got %d", mB)
}
@@ -853,8 +853,8 @@ func TestEvictionPreservesActiveConversations(t *testing.T) {
// System prompt prefix should still be findable (multi-child
// branch points are protected from eviction entirely).
- _, matched := findBestMatch(pc.root, pc.key(systemPrompt))
- if want := len(pc.key(systemPrompt)); matched < want {
+ _, matched := findBestMatch(pc.root, pc.key(effectiveKeyTokens(systemPrompt, nil)))
+ if want := len(pc.key(effectiveKeyTokens(systemPrompt, nil))); matched < want {
t.Fatalf("system prompt match = %d, want %d", matched, want)
}
@@ -952,7 +952,7 @@ func TestSnapshotBeyondPrefillSkipped(t *testing.T) {
pc := env.pc
inputs := []int32{1, 2, 3, 4, 5}
- session := pc.begin(inputs)
+ session := pc.begin(inputs, nil)
// Request a snapshot at 3 and one at len(inputs); captures land at
// the requested prefix minus the look-ahead.
session.schedulePrefillSnapshots([]int{3, len(inputs)})
@@ -987,7 +987,7 @@ func TestPrefillSnapshotsDiscardedOnCancel(t *testing.T) {
pc := env.pc
inputs := []int32{1, 2, 3, 4, 5}
- session := pc.begin(inputs)
+ session := pc.begin(inputs, nil)
session.schedulePrefillSnapshots([]int{3})
// Cross offset 3 so the caches capture it, then close the session as a
// canceled prefill would, before the captures are attached to the trie.