cache_test.go 14.5 KB
Newer Older
Jesse Gross's avatar
Jesse Gross committed
1
package ollamarunner
2
3

import (
4
5
	"errors"
	"fmt"
6
	"slices"
7
8
	"testing"
	"time"
9

10
	"github.com/ollama/ollama/ml"
11
	"github.com/ollama/ollama/model/input"
12
13
14
15
16
)

func TestCountCommon(t *testing.T) {
	tests := []struct {
		name     string
17
18
		t1       []*input.Input
		t2       []*input.Input
Jesse Gross's avatar
Jesse Gross committed
19
		expected int32
20
21
22
	}{
		{
			name:     "Equal",
23
24
			t1:       []*input.Input{{Token: 1}, {Token: 2}, {Token: 3}},
			t2:       []*input.Input{{Token: 1}, {Token: 2}, {Token: 3}},
25
26
27
28
			expected: 3,
		},
		{
			name:     "Prefix",
29
30
			t1:       []*input.Input{{Token: 1}},
			t2:       []*input.Input{{Token: 1}, {Token: 2}, {Token: 3}},
31
32
33
			expected: 1,
		},
		{
Jesse Gross's avatar
Jesse Gross committed
34
			name:     "Image Prefix",
35
36
			t1:       []*input.Input{{MultimodalHash: 1}},
			t2:       []*input.Input{{MultimodalHash: 1}, {MultimodalHash: 2}, {MultimodalHash: 3}},
37
38
39
40
			expected: 1,
		},
		{
			name:     "Mixed",
41
42
			t1:       []*input.Input{{Token: 1}, {MultimodalHash: 1}},
			t2:       []*input.Input{{Token: 1}, {MultimodalHash: 1}, {Token: 5}},
43
44
			expected: 2,
		},
45
46
		{
			name:     "Mixed, Same Length",
47
48
			t1:       []*input.Input{{Token: 1}, {MultimodalHash: 1}},
			t2:       []*input.Input{{Token: 1}, {MultimodalHash: 2}},
49
50
			expected: 1,
		},
51
52
		{
			name:     "Empty",
53
54
			t1:       []*input.Input{},
			t2:       []*input.Input{{Token: 1}, {Token: 2}, {Token: 3}},
55
56
57
58
			expected: 0,
		},
		{
			name:     "Both Empty",
59
60
			t1:       []*input.Input{},
			t2:       []*input.Input{},
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
			expected: 0,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := countCommonPrefix(tt.t1, tt.t2)
			if result != tt.expected {
				t.Errorf("countCommonPrefix(%v, %v): have %v; want %v", tt.t1, tt.t2, result, tt.expected)
			}
		})
	}
}

func TestFindCacheSlot(t *testing.T) {
	type expected struct {
		result int
Jesse Gross's avatar
Jesse Gross committed
78
		len    int32
79
80
81
82
83
	}

	tests := []struct {
		name    string
		cache   InputCache
84
		prompt  []*input.Input
85
86
87
88
89
90
91
92
		longest expected
		best    expected
	}{
		{
			name: "Empty",
			cache: InputCache{slots: []InputCacheSlot{
				{
					Id:       0,
93
					Inputs:   []*input.Input{},
94
95
96
97
98
					InUse:    false,
					lastUsed: time.Time{},
				},
				{
					Id:       1,
99
					Inputs:   []*input.Input{},
100
101
102
103
					InUse:    false,
					lastUsed: time.Time{},
				},
			}},
104
			prompt:  []*input.Input{{Token: 1}},
105
106
107
108
109
110
111
112
			longest: expected{result: 0, len: 0},
			best:    expected{result: 0, len: 0},
		},
		{
			name: "Extend",
			cache: InputCache{slots: []InputCacheSlot{
				{
					Id:       0,
113
					Inputs:   []*input.Input{{Token: 1}},
114
115
116
117
118
					InUse:    false,
					lastUsed: time.Now().Add(-time.Second),
				},
				{
					Id:       1,
119
					Inputs:   []*input.Input{{Token: 1}, {Token: 2}},
120
121
122
123
					InUse:    false,
					lastUsed: time.Now().Add(-2 * time.Second),
				},
			}},
124
			prompt:  []*input.Input{{Token: 1}, {Token: 2}},
125
126
127
128
129
130
131
132
			longest: expected{result: 1, len: 2},
			best:    expected{result: 1, len: 2},
		},
		{
			name: "New",
			cache: InputCache{slots: []InputCacheSlot{
				{
					Id:       0,
133
					Inputs:   []*input.Input{{Token: 1}, {Token: 2}},
134
135
136
137
138
					InUse:    false,
					lastUsed: time.Now().Add(-time.Second),
				},
				{
					Id:       1,
139
					Inputs:   []*input.Input{},
140
141
142
143
					InUse:    false,
					lastUsed: time.Time{},
				},
			}},
144
			prompt:  []*input.Input{{Token: 2}},
145
146
147
148
149
150
151
152
153
			longest: expected{result: 0, len: 0},
			best:    expected{result: 1, len: 0},
		},
		{
			name: "Fork",
			cache: InputCache{
				slots: []InputCacheSlot{
					{
						Id:       0,
154
						Inputs:   []*input.Input{{Token: 1}, {Token: 2}},
155
156
157
158
159
						InUse:    false,
						lastUsed: time.Now().Add(-time.Second),
					},
					{
						Id:       1,
160
						Inputs:   []*input.Input{},
161
162
163
164
165
						InUse:    false,
						lastUsed: time.Time{},
					},
				},
			},
166
			prompt:  []*input.Input{{Token: 1}},
167
168
169
170
171
172
173
174
			longest: expected{result: 0, len: 1},
			best:    expected{result: 1, len: 1},
		},
		{
			name: "Evict",
			cache: InputCache{slots: []InputCacheSlot{
				{
					Id:       0,
175
					Inputs:   []*input.Input{{Token: 1}},
176
177
178
179
180
					InUse:    false,
					lastUsed: time.Now().Add(-time.Second),
				},
				{
					Id:       1,
181
					Inputs:   []*input.Input{{Token: 1}, {Token: 2}},
182
183
184
185
					InUse:    false,
					lastUsed: time.Now().Add(-2 * time.Second),
				},
			}},
186
			prompt:  []*input.Input{{Token: 2}, {Token: 3}},
187
188
189
190
191
192
193
194
			longest: expected{result: 0, len: 0},
			best:    expected{result: 1, len: 0},
		},
		{
			name: "In use",
			cache: InputCache{slots: []InputCacheSlot{
				{
					Id:       0,
195
					Inputs:   []*input.Input{{Token: 1}, {Token: 2}},
196
197
198
199
200
					InUse:    true,
					lastUsed: time.Now().Add(-time.Second),
				},
				{
					Id:       1,
201
					Inputs:   []*input.Input{{Token: 1}},
202
203
204
205
					InUse:    false,
					lastUsed: time.Now().Add(-2 * time.Second),
				},
			}},
206
			prompt:  []*input.Input{{Token: 1}, {Token: 2}},
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
			longest: expected{result: 1, len: 1},
			best:    expected{result: 1, len: 2},
		},
	}

	for _, tt := range tests {
		t.Run("Longest-"+tt.name, func(t *testing.T) {
			result, resultLen, err := tt.cache.findLongestCacheSlot(tt.prompt)
			if err != nil {
				t.Errorf("findLongestCacheSlot: err %v", err)
			} else if result.Id != tt.longest.result || resultLen != tt.longest.len {
				t.Errorf("findLongestCacheSlot: slot have %v, want %v len have %v, want %v",
					result.Id, tt.longest.result, resultLen, tt.longest.len)
			}
		})
	}

	for _, tt := range tests {
		t.Run("Best-"+tt.name, func(t *testing.T) {
			result, resultLen, err := tt.cache.findBestCacheSlot(tt.prompt)
			if err != nil {
				t.Errorf("findBestCacheSlot: err %v", err)
			} else if result.Id != tt.best.result || resultLen != tt.best.len {
				t.Errorf("findBestCacheSlot: slot have %v, want %v len have %v, want %v",
					result.Id, tt.best.result, resultLen, tt.best.len)
			}
		})
	}
}
236
237
238
239

func TestShiftDiscard(t *testing.T) {
	tests := []struct {
		name     string
Jesse Gross's avatar
Jesse Gross committed
240
241
		numCtx   int32
		numKeep  int32
242
		inputs   []*input.Input
Jesse Gross's avatar
Jesse Gross committed
243
		expected int32
244
245
246
247
248
	}{
		{
			name:     "Shift",
			numCtx:   2048,
			numKeep:  5,
249
			inputs:   slices.Repeat([]*input.Input{{}}, 2048),
250
251
252
253
254
255
			expected: 1021,
		},
		{
			name:     "Max Keep",
			numCtx:   2048,
			numKeep:  2047,
256
			inputs:   slices.Repeat([]*input.Input{{}}, 2048),
257
258
259
260
261
262
			expected: 1,
		},
		{
			name:     "No Keep",
			numCtx:   2048,
			numKeep:  0,
263
			inputs:   slices.Repeat([]*input.Input{{}}, 2048),
264
265
266
267
268
269
			expected: 1024,
		},
		{
			name:     "Truncate",
			numCtx:   2048,
			numKeep:  5,
270
			inputs:   slices.Repeat([]*input.Input{{}}, 5000),
271
272
273
274
275
276
			expected: 3973,
		},
		{
			name:     "Truncate Keep",
			numCtx:   2048,
			numKeep:  2047,
277
			inputs:   slices.Repeat([]*input.Input{{}}, 5000),
278
279
280
281
282
283
			expected: 2953,
		},
		{
			name:     "No Op",
			numCtx:   2048,
			numKeep:  5,
284
			inputs:   slices.Repeat([]*input.Input{{}}, 512),
285
286
			expected: 0,
		},
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
		{
			name:    "Same Batch",
			numCtx:  2048,
			numKeep: 5,
			inputs: slices.Collect(func(yield func(*input.Input) bool) {
				for range 1024 {
					if !yield(&input.Input{}) {
						return
					}
				}

				if !yield(&input.Input{SameBatch: 512 - 1}) {
					return
				}

				for range 2048 - 1024 - 1 {
					if !yield(&input.Input{}) {
						return
					}
				}
			}),
			expected: 1531,
		},
		{
			name:    "Same Batch Near Start",
			numCtx:  2048,
			numKeep: 5,
			inputs: slices.Collect(func(yield func(*input.Input) bool) {
				for range 10 {
					if !yield(&input.Input{}) {
						return
					}
				}

				if !yield(&input.Input{SameBatch: 512 - 1}) {
					return
				}

				for range 2048 - 10 - 1 {
					if !yield(&input.Input{}) {
						return
					}
				}
			}),
			expected: 1021,
		},
		{
			name:   "Consecutive Same Batch",
			numCtx: 32,
			inputs: slices.Collect(func(yield func(*input.Input) bool) {
				for i := range 32 {
					input := input.Input{}
					if i%10 == 0 {
						input.SameBatch = 10 - 1
					}
					if !yield(&input) {
						return
					}
				}
			}),
			expected: 20,
		},
		{
			name:   "Overlapping Same Batch",
			numCtx: 32,
			inputs: slices.Collect(func(yield func(*input.Input) bool) {
				for i := range 32 {
					input := input.Input{}
					if slices.Contains([]int{4, 8, 14}, i) {
						input.SameBatch = 10 - 1
					}
					if !yield(&input) {
						return
					}
				}
			}),
			expected: 24,
		},
365
366
367
368
369
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			c := InputCache{numCtx: tt.numCtx}
370
			result := c.ShiftDiscard(tt.inputs, tt.numKeep)
371
			if result != tt.expected {
372
				t.Errorf("shiftDiscard(ctx: %v, keep: %v inputs: %v): have %v; want %v", tt.numCtx, tt.numKeep, len(tt.inputs), result, tt.expected)
373
374
375
376
			}
		})
	}
}
377
378
379
380
381

func TestLoadCacheSlot(t *testing.T) {
	tests := []struct {
		name           string
		cache          InputCache
382
		prompt         []*input.Input
383
384
385
386
387
388
389
390
391
392
393
		wantErr        bool
		expectedSlotId int
		expectedPrompt int // expected length of remaining prompt
	}{
		{
			name: "Basic cache hit - single user",
			cache: InputCache{
				multiUserCache: false,
				slots: []InputCacheSlot{
					{
						Id:       0,
394
						Inputs:   []*input.Input{{Token: 1}, {Token: 2}},
395
396
397
398
399
						InUse:    false,
						lastUsed: time.Now().Add(-time.Second),
					},
					{
						Id:       1,
400
						Inputs:   []*input.Input{},
401
402
403
404
405
						InUse:    false,
						lastUsed: time.Now().Add(-2 * time.Second),
					},
				},
			},
406
			prompt:         []*input.Input{{Token: 1}, {Token: 2}, {Token: 3}},
407
408
409
410
411
412
413
414
415
416
417
			wantErr:        false,
			expectedSlotId: 0,
			expectedPrompt: 1, // Only token 3 remains
		},
		{
			name: "Basic cache hit - multi user",
			cache: InputCache{
				multiUserCache: true,
				slots: []InputCacheSlot{
					{
						Id:       0,
418
						Inputs:   []*input.Input{{Token: 1}, {Token: 2}},
419
420
421
422
423
						InUse:    false,
						lastUsed: time.Now().Add(-time.Second),
					},
					{
						Id:       1,
424
						Inputs:   []*input.Input{},
425
426
427
428
429
						InUse:    false,
						lastUsed: time.Now().Add(-2 * time.Second),
					},
				},
			},
430
			prompt:         []*input.Input{{Token: 1}, {Token: 2}, {Token: 3}},
431
432
433
434
435
436
437
438
439
440
441
			wantErr:        false,
			expectedSlotId: 0,
			expectedPrompt: 1, // Only token 3 remains
		},
		{
			name: "Exact match - leave one input",
			cache: InputCache{
				multiUserCache: false,
				slots: []InputCacheSlot{
					{
						Id:       0,
442
						Inputs:   []*input.Input{{Token: 1}, {Token: 2}},
443
444
445
446
447
						InUse:    false,
						lastUsed: time.Now().Add(-time.Second),
					},
				},
			},
448
			prompt:         []*input.Input{{Token: 1}, {Token: 2}},
449
450
451
452
453
454
455
456
457
458
459
			wantErr:        false,
			expectedSlotId: 0,
			expectedPrompt: 1, // Should leave 1 token for sampling
		},
		{
			name: "No available slots",
			cache: InputCache{
				multiUserCache: false,
				slots: []InputCacheSlot{
					{
						Id:       0,
460
						Inputs:   []*input.Input{{Token: 1}, {Token: 2}},
461
462
463
464
465
						InUse:    true,
						lastUsed: time.Now().Add(-time.Second),
					},
				},
			},
466
			prompt:         []*input.Input{{Token: 1}, {Token: 2}, {Token: 3}},
467
468
469
470
471
472
473
474
			wantErr:        true,
			expectedSlotId: -1,
			expectedPrompt: -1,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
Michael Yang's avatar
Michael Yang committed
475
			slot, remainingPrompt, err := tt.cache.LoadCacheSlot(tt.prompt, true)
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504

			// Check error state
			if (err != nil) != tt.wantErr {
				t.Errorf("LoadCacheSlot() error = %v, wantErr %v", err, tt.wantErr)
				return
			}

			if tt.wantErr {
				return // Skip further checks if we expected an error
			}

			// Verify slot ID
			if slot.Id != tt.expectedSlotId {
				t.Errorf("LoadCacheSlot() slot ID = %v, expected %v", slot.Id, tt.expectedSlotId)
			}

			// Verify slot is now marked in use
			if !slot.InUse {
				t.Errorf("LoadCacheSlot() slot not marked InUse")
			}

			// Verify remaining prompt length
			if len(remainingPrompt) != tt.expectedPrompt {
				t.Errorf("LoadCacheSlot() remaining prompt length = %v, expected %v",
					len(remainingPrompt), tt.expectedPrompt)
			}
		})
	}
}
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524

// Mock implementation of the Cache interface
type mockCache struct {
	shouldFail bool
}

// Implement only the methods needed for the test
func (m *mockCache) Remove(seq int, beginIndex, endIndex int32) error {
	if m.shouldFail {
		return fmt.Errorf("mock cache removal error")
	}
	return nil
}

// Stub implementations for other interface methods
func (m *mockCache) SetLayer(layer int)                                                            {}
func (m *mockCache) Get(ctx ml.Context) (ml.Tensor, ml.Tensor, ml.Tensor)                          { return nil, nil, nil }
func (m *mockCache) Put(ctx ml.Context, key, value ml.Tensor)                                      {}
func (m *mockCache) Init(backend ml.Backend, dtype ml.DType, maxSequences, capacity, maxBatch int) {}
func (m *mockCache) Close()                                                                        {}
525
func (m *mockCache) StartForward(ctx ml.Context, batch input.Batch, reserve bool) error            { return nil }
526
527
func (m *mockCache) CopyPrefix(srcSeq, dstSeq int, len int32)                                      {}
func (m *mockCache) SetConfig(ml.CacheConfig)                                                      {}
528
func (m *mockCache) CanResume(seq int, pos int32) bool                                             { return true }
529
530
531
532
533

func TestShiftCacheSlot(t *testing.T) {
	tests := []struct {
		name          string
		numCtx        int32
534
		inputs        []*input.Input
535
536
537
538
539
540
541
542
		numKeep       int32
		cacheErr      bool
		wantErr       any
		wantInputsLen int
	}{
		{
			name:          "Normal shift",
			numCtx:        10,
543
			inputs:        []*input.Input{{Token: 1}, {Token: 2}, {Token: 3}, {Token: 4}, {Token: 5}, {Token: 6}, {Token: 7}, {Token: 8}, {Token: 9}, {Token: 10}},
544
545
546
547
548
549
550
551
			numKeep:       2,
			cacheErr:      false, // No error
			wantErr:       nil,
			wantInputsLen: 6, // After discarding 4 tokens
		},
		{
			name:          "Cache removal fails",
			numCtx:        10,
552
			inputs:        []*input.Input{{Token: 1}, {Token: 2}, {Token: 3}, {Token: 4}, {Token: 5}, {Token: 6}, {Token: 7}, {Token: 8}, {Token: 9}, {Token: 10}},
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
			numKeep:       2,
			cacheErr:      true,
			wantErr:       &ErrReprocessInputs{},
			wantInputsLen: 0, // Original inputs should be cleared
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			mock := &mockCache{shouldFail: tt.cacheErr}
			c := InputCache{
				numCtx: tt.numCtx,
				cache:  mock,
			}
			slot := &InputCacheSlot{
				Id:     123,
569
				Inputs: make([]*input.Input, len(tt.inputs)),
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
			}
			copy(slot.Inputs, tt.inputs)

			err := c.ShiftCacheSlot(slot, tt.numKeep)

			if tt.wantErr != nil {
				if err == nil {
					t.Errorf("Expected error but got nil")
					return
				}

				if !errors.As(err, &tt.wantErr) {
					t.Errorf("Expected error of type %T but got %T: %v", tt.wantErr, err, err)
				}
			} else if err != nil {
				t.Errorf("Unexpected error: %v", err)
			}

			if len(slot.Inputs) != tt.wantInputsLen {
				t.Errorf("Slot inputs length after operation: got %v, want %v", len(slot.Inputs), tt.wantInputsLen)
			}
		})
	}
}