cache.go 6.73 KB
Newer Older
Jesse Gross's avatar
Jesse Gross committed
1
package ollamarunner
2
3
4

import (
	"errors"
5
	"fmt"
6
	"log/slog"
Jesse Gross's avatar
Jesse Gross committed
7
	"math"
8
9
	"time"

Jesse Gross's avatar
Jesse Gross committed
10
11
12
	"github.com/ollama/ollama/kvcache"
	"github.com/ollama/ollama/ml"
	"github.com/ollama/ollama/model"
13
14
15
16
)

type InputCache struct {
	// context window size (per slot)
Jesse Gross's avatar
Jesse Gross committed
17
18
19
20
21
22
	numCtx int32

	// does the cache store data or do we need to always send the full input?
	// note that when enabled is false the underlying cache may either be nil
	// or a non-nil dummy that doesn't actually store anything
	enabled bool
23
24
25
26
27
28
29

	// individual KV caches
	slots []InputCacheSlot

	// optimize cache eviction for multiple users
	multiUserCache bool

Jesse Gross's avatar
Jesse Gross committed
30
	cache kvcache.Cache
31
32
}

Jesse Gross's avatar
Jesse Gross committed
33
34
func NewInputCache(model model.Model, kvCacheType string, kvSize int32, numSlots int, multiUserCache bool) (*InputCache, error) {
	if kvSize/int32(numSlots) < 1 {
35
36
37
		return nil, fmt.Errorf("must have at least one kv cache entry per parallel sequence (kv: %v parallel: %v)", kvSize, numSlots)
	}

38
39
40
	slots := make([]InputCacheSlot, numSlots)

	for i := range slots {
41
		slots[i] = InputCacheSlot{Id: i}
42
43
	}

Jesse Gross's avatar
Jesse Gross committed
44
45
46
47
48
	cache := model.Config().Cache
	if cache != nil {
		cache.Init(model.Backend(), kvCacheTypeFromStr(kvCacheType), kvSize)
	}

49
	return &InputCache{
Jesse Gross's avatar
Jesse Gross committed
50
51
		numCtx:         kvSize / int32(numSlots),
		enabled:        cache != nil,
52
53
		slots:          slots,
		multiUserCache: multiUserCache,
Jesse Gross's avatar
Jesse Gross committed
54
		cache:          cache,
55
	}, nil
56
57
}

Jesse Gross's avatar
Jesse Gross committed
58
59
60
func kvCacheTypeFromStr(s string) ml.DType {
	switch s {
	case "q8_0":
61
		return ml.DTypeQ80
Jesse Gross's avatar
Jesse Gross committed
62
	case "q4_0":
63
		return ml.DTypeQ40
Jesse Gross's avatar
Jesse Gross committed
64
65
66
67
68
69
70
71
72
	default:
		return ml.DTypeF16
	}
}

func (c *InputCache) Close() {
	c.cache.Close()
}

73
74
// Locking: Operations on InputCacheSlot (including finding one
// through LoadCacheSlot) require a lock to be be held that serializes
Jesse Gross's avatar
Jesse Gross committed
75
// these operations with each other and processBatch
76
77
78
79
80
81

type InputCacheSlot struct {
	// Index in the KV cache
	Id int

	// Inputs that are stored in the KV cache
82
	Inputs []model.Input
83
84
85
86
87
88
89
90

	// is this cache actively being processed as part of a sequence?
	InUse bool

	// last time this cache was used (as of start of processing)
	lastUsed time.Time
}

91
func (c *InputCache) LoadCacheSlot(prompt []model.Input, cachePrompt bool) (*InputCacheSlot, []model.Input, error) {
92
	var slot *InputCacheSlot
Jesse Gross's avatar
Jesse Gross committed
93
	var numPast int32
94
95
96
	var err error

	// In single-user scenarios, the longest cache slot works fine for getting good input
Jesse Gross's avatar
Jesse Gross committed
97
	// cache hit rates and it keeps the footprint of the cache small, which improves throughput.
98
	// For multiple users, the "best" cache slot produces better input cache hit rates
Jesse Gross's avatar
Jesse Gross committed
99
	// at the cost of worse performance when we miss the input cache.
100
101
102
103
104
105
	if !c.multiUserCache {
		slot, numPast, err = c.findLongestCacheSlot(prompt)
	} else {
		slot, numPast, err = c.findBestCacheSlot(prompt)
	}
	if err != nil {
106
		return nil, nil, err
107
108
109
110
111
112
113
114
115
	}

	if !cachePrompt {
		numPast = 0
	}

	slot.InUse = true
	slot.lastUsed = time.Now()

Jesse Gross's avatar
Jesse Gross committed
116
	if numPast == int32(len(prompt)) {
117
118
119
120
		// Leave one input to sample so we can get a response
		numPast--
	}

Jesse Gross's avatar
Jesse Gross committed
121
122
123
124
125
126
127
128
129
130
	if c.cache != nil {
		err = c.cache.Remove(slot.Id, numPast, math.MaxInt32)
		if err != nil {
			// Some models don't support partial erasure
			err = c.cache.Remove(slot.Id, 0, math.MaxInt32)
			if err != nil {
				return nil, nil, err
			}
			numPast = 0
		}
131
132
133
	}

	slog.Debug("loading cache slot", "id", slot.Id, "cache", len(slot.Inputs), "prompt", len(prompt),
Jesse Gross's avatar
Jesse Gross committed
134
		"used", numPast, "remaining", int32(len(prompt))-numPast)
135
136
137
138

	prompt = prompt[numPast:]
	slot.Inputs = slot.Inputs[:numPast]

139
	return slot, prompt, nil
140
141
}

142
func (c *InputCache) findLongestCacheSlot(prompt []model.Input) (*InputCacheSlot, int32, error) {
Jesse Gross's avatar
Jesse Gross committed
143
	longest := int32(-1)
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
	var longestSlot *InputCacheSlot

	for i, s := range c.slots {
		if s.InUse {
			continue
		}

		count := countCommonPrefix(s.Inputs, prompt)
		if count > longest {
			longest = count
			longestSlot = &c.slots[i]
		}
	}

	if longestSlot == nil {
		return nil, 0, errors.New("no available cache slots")
	}

	return longestSlot, longest, nil
}

165
func (c *InputCache) findBestCacheSlot(prompt []model.Input) (*InputCacheSlot, int32, error) {
166
167
168
	oldest := time.Now()
	var oldestSlot *InputCacheSlot

Jesse Gross's avatar
Jesse Gross committed
169
	longest := int32(-1)
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
	var longestSlot *InputCacheSlot

	for i, s := range c.slots {
		count := countCommonPrefix(s.Inputs, prompt)
		if count > longest {
			longest = count
			longestSlot = &c.slots[i]
		}

		if s.lastUsed.Compare(oldest) < 0 && !s.InUse {
			oldest = s.lastUsed
			oldestSlot = &c.slots[i]
		}
	}

Jesse Gross's avatar
Jesse Gross committed
185
	if longest == int32(len(longestSlot.Inputs)) && !longestSlot.InUse {
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
		return longestSlot, longest, nil
	}

	if oldestSlot.InUse {
		return nil, 0, errors.New("no available cache slots")
	}

	if len(oldestSlot.Inputs) != 0 {
		slog.Debug("evicting cache slot", "id", oldestSlot.Id, "inputs", len(oldestSlot.Inputs),
			"used", oldestSlot.lastUsed)
	}

	if longest > 0 && longestSlot != oldestSlot {
		slog.Debug("forking cache slot", "src", longestSlot.Id, "dst", oldestSlot.Id, "inputs", longest, "total",
			len(longestSlot.Inputs))
201
		oldestSlot.Inputs = make([]model.Input, longest)
202
		copy(oldestSlot.Inputs, longestSlot.Inputs[:longest])
Jesse Gross's avatar
Jesse Gross committed
203
204
		if c.cache != nil {
			c.cache.CopyPrefix(longestSlot.Id, oldestSlot.Id, longest)
205
206
207
208
209
210
		}
	}

	return oldestSlot, longest, nil
}

211
func countCommonPrefix(a []model.Input, b []model.Input) int32 {
Jesse Gross's avatar
Jesse Gross committed
212
	var count int32
213
214
215
216
217
218

	for i := range a {
		if i >= len(b) {
			break
		}

219
		if a[i].Token != b[i].Token || a[i].MultimodalHash != b[i].MultimodalHash {
220
221
222
223
224
225
226
227
228
			break
		}

		count++
	}

	return count
}

Jesse Gross's avatar
Jesse Gross committed
229
func (c *InputCache) ShiftDiscard(inputLen int32, numKeep int32) int32 {
230
231
232
233
234
235
236
237
238
239
240
241
242
	targetFree := (c.numCtx - numKeep) / 2
	targetFree = max(targetFree, 1)

	currentFree := c.numCtx - inputLen
	discard := targetFree - currentFree

	if discard < 0 {
		discard = 0
	}

	return discard
}

243
244
245
246
// Frees up space in the KV cache by deleting the oldest half of history and shifting
// the newest half into that space (saving numKeep inputs at the beginning).
//
// Assumes that at least 1 entry can be freed up by shifting (i.e. numKeep < numCtx)
Jesse Gross's avatar
Jesse Gross committed
247
func (c *InputCache) ShiftCacheSlot(slot *InputCacheSlot, numKeep int32) error {
248
249
250
251
	if numKeep >= c.numCtx {
		return fmt.Errorf("unable to shift context - keep exceeds context (keep: %v context: %v)", numKeep, c.numCtx)
	}

Jesse Gross's avatar
Jesse Gross committed
252
253
	inputLen := int32(len(slot.Inputs))
	discard := c.ShiftDiscard(inputLen, numKeep)
254
255

	if discard <= 0 {
256
		return nil
257
258
	}

259
	slog.Debug("context limit hit - shifting", "id", slot.Id, "limit", c.numCtx, "input", len(slot.Inputs),
260
261
		"keep", numKeep, "discard", discard)

262
	// TODO (jessegross): KV cache removal can fail for certain types of models
Jesse Gross's avatar
Jesse Gross committed
263
264
265
266
267
	if c.cache != nil {
		err := c.cache.Remove(slot.Id, numKeep, numKeep+discard)
		if err != nil {
			return fmt.Errorf("unable to remove old kv cache entries (id: %v, keep: %v discard: %v): %w", slot.Id, numKeep, discard, err)
		}
268
	}
269

Jesse Gross's avatar
Jesse Gross committed
270
	for i := numKeep + discard; i < inputLen; i++ {
271
		slot.Inputs[i-discard] = slot.Inputs[i]
272
	}
Jesse Gross's avatar
Jesse Gross committed
273
	slot.Inputs = slot.Inputs[:inputLen-discard]
274
275

	return nil
276
}