causal_test.go 23.6 KB
Newer Older
Jesse Gross's avatar
Jesse Gross committed
1
2
3
4
5
6
7
8
package kvcache

import (
	"math"
	"slices"
	"testing"

	"github.com/ollama/ollama/ml"
9
	"github.com/ollama/ollama/model/input"
Jesse Gross's avatar
Jesse Gross committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
)

type testCase struct {
	name          string
	in            []float32
	inShape       []int
	seqs          []int
	pos           []int32
	expected      []float32
	expectedShape []int
	expectedMask  []float32
}

func TestStore(t *testing.T) {
	backend := &testBackend{}
	cache := NewCausalCache(nil)
	defer cache.Close()

28
	cache.Init(backend, ml.DTypeF16, 1, 16, 16)
Jesse Gross's avatar
Jesse Gross committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

	tests := []testCase{
		{
			name:          "FirstBatch",
			in:            []float32{111, 211, 121, 221, 131, 231, 112, 212, 122, 222, 132, 232, 113, 213, 123, 223, 133, 233, 114, 214, 124, 224, 134, 234},
			inShape:       []int{2, 3, 4},
			seqs:          []int{0, 0, 0, 0},
			pos:           []int32{0, 1, 2, 3},
			expected:      []float32{111, 211, 121, 221, 131, 231, 112, 212, 122, 222, 132, 232, 113, 213, 123, 223, 133, 233, 114, 214, 124, 224, 134, 234},
			expectedShape: []int{2, 3, 4},
			expectedMask:  []float32{0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, float32(math.Inf(-1)), 0, 0, 0, 0},
		},
		{
			name:          "SecondBatch",
			in:            []float32{115, 215, 125, 225, 135, 235},
			inShape:       []int{2, 3, 1},
			seqs:          []int{0},
			pos:           []int32{4},
			expected:      []float32{111, 211, 121, 221, 131, 231, 112, 212, 122, 222, 132, 232, 113, 213, 123, 223, 133, 233, 114, 214, 124, 224, 134, 234, 115, 215, 125, 225, 135, 235},
			expectedShape: []int{2, 3, 5},
			expectedMask:  []float32{0, 0, 0, 0, 0},
		},
	}

	testCache(t, backend, cache, tests)
}

func TestSWA(t *testing.T) {
	backend := &testBackend{}
	cache := NewSWACache(1, nil)
	defer cache.Close()

61
	cache.Init(backend, ml.DTypeF16, 1, 16, 16)
Jesse Gross's avatar
Jesse Gross committed
62

63
64
	x := float32(math.Inf(-1))

Jesse Gross's avatar
Jesse Gross committed
65
66
	tests := []testCase{
		{
67
			name:          "FirstBatch",
Jesse Gross's avatar
Jesse Gross committed
68
69
70
71
72
73
			in:            []float32{1, 2, 3, 4},
			inShape:       []int{1, 1, 4},
			seqs:          []int{0, 0, 0, 0},
			pos:           []int32{0, 1, 2, 3},
			expected:      []float32{1, 2, 3, 4},
			expectedShape: []int{1, 1, 4},
74
75
76
77
78
79
			expectedMask: []float32{
				0, x, x, x,
				0, 0, x, x,
				x, 0, 0, x,
				x, x, 0, 0,
			},
Jesse Gross's avatar
Jesse Gross committed
80
		},
81
82
83
84
85
86
87
88
		{
			name:          "SecondBatch",
			in:            []float32{5, 6},
			inShape:       []int{1, 1, 2},
			seqs:          []int{0, 0},
			pos:           []int32{4, 5},
			expected:      []float32{5, 6, 3, 4},
			expectedShape: []int{1, 1, 4},
89
90
91
92
93
94
95
96
97
98
			expectedMask: []float32{
				0, x, x, 0,
				0, 0, x, x,
			},
		},
	}

	testCache(t, backend, cache, tests)
}

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
func TestSWASeparateBatches(t *testing.T) {
	backend := &testBackend{}
	cache := NewSWACache(1, nil)
	defer cache.Close()

	cache.Init(backend, ml.DTypeF16, 2, 16, 2)

	x := float32(math.Inf(-1))

	tests := []testCase{
		{
			name:          "First seq 0",
			in:            []float32{1, 2},
			inShape:       []int{1, 1, 2},
			seqs:          []int{0, 0},
			pos:           []int32{0, 1},
			expected:      []float32{1, 2},
			expectedShape: []int{1, 1, 2},
			expectedMask: []float32{
				0, x,
				0, 0,
			},
		},
		{
			name:          "Second seq 0",
			in:            []float32{3, 4},
			inShape:       []int{1, 1, 2},
			seqs:          []int{0, 0},
			pos:           []int32{2, 3},
			expected:      []float32{2, 3, 4},
			expectedShape: []int{1, 1, 3},
			expectedMask: []float32{
				0, 0, x,
				x, 0, 0,
			},
		},
		{
			name:          "First seq 1",
			in:            []float32{5, 6},
			inShape:       []int{1, 1, 2},
			seqs:          []int{1, 1},
			pos:           []int32{0, 1},
			expected:      []float32{5, 6},
			expectedShape: []int{1, 1, 2},
			expectedMask: []float32{
				0, x,
				0, 0,
			},
		},
		{
			name:          "Second seq 1",
			in:            []float32{7, 8},
			inShape:       []int{1, 1, 2},
			seqs:          []int{1, 1},
			pos:           []int32{2, 3},
			expected:      []float32{6, 3, 4, 7, 8},
			expectedShape: []int{1, 1, 5},
			expectedMask: []float32{
				0, x, x, 0, x,
				x, x, x, 0, 0,
			},
		},
		{
			name:          "Third seq 0",
			in:            []float32{9, 10},
			inShape:       []int{1, 1, 2},
			seqs:          []int{0, 0},
			pos:           []int32{4, 5},
			expected:      []float32{9, 10, 3, 4},
			expectedShape: []int{1, 1, 4},
			expectedMask: []float32{
				0, x, x, 0,
				0, 0, x, x,
			},
		},
	}

	testCache(t, backend, cache, tests)
}

179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
func TestSWAMem(t *testing.T) {
	backend := &testBackend{}
	cache := NewSWAMemCache(1, 3, nil)
	defer cache.Close()

	cache.Init(backend, ml.DTypeF16, 1, 16, 16)

	x := float32(math.Inf(-1))

	tests := []testCase{
		{
			name:          "FirstBatch",
			in:            []float32{1, 2, 3, 4},
			inShape:       []int{1, 1, 4},
			seqs:          []int{0, 0, 0, 0},
			pos:           []int32{0, 1, 2, 3},
			expected:      []float32{1, 2, 3, 4},
			expectedShape: []int{1, 1, 4},
			expectedMask: []float32{
				0, x, x, x,
				0, 0, x, x,
				x, 0, 0, x,
				x, x, 0, 0,
			},
		},
		{
			name:          "SecondBatch",
			in:            []float32{5, 6},
			inShape:       []int{1, 1, 2},
			seqs:          []int{0, 0},
			pos:           []int32{4, 5},
			expected:      []float32{4, 5, 6},
			expectedShape: []int{1, 1, 3},
			expectedMask: []float32{
				0, 0, x,
				x, 0, 0,
			},
216
		},
Jesse Gross's avatar
Jesse Gross committed
217
218
219
220
221
	}

	testCache(t, backend, cache, tests)
}

Michael Yang's avatar
Michael Yang committed
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
func TestChunkedAttention(t *testing.T) {
	cache := NewChunkedAttentionCache(2, nil)
	defer cache.Close()

	var b testBackend
	cache.Init(&b, ml.DTypeF16, 1, 16, 16)

	x := float32(math.Inf(-1))

	testCache(
		t, &b, cache,
		[]testCase{
			{
				name:          "FirstBatch",
				in:            []float32{1, 2, 3, 4},
				inShape:       []int{1, 1, 4},
				seqs:          []int{0, 0, 0, 0},
				pos:           []int32{0, 1, 2, 3},
				expected:      []float32{1, 2, 3, 4},
				expectedShape: []int{1, 1, 4},
				expectedMask: []float32{
					0, x, x, x,
					0, 0, x, x,
					x, x, 0, x,
					x, x, 0, 0,
				},
			},
			{
				name:          "SecondBatch",
				in:            []float32{5, 6, 7},
				inShape:       []int{1, 1, 3},
				seqs:          []int{0, 0, 0},
				pos:           []int32{4, 5, 6},
				expected:      []float32{1, 2, 3, 4, 5, 6, 7},
				expectedShape: []int{1, 1, 7},
				expectedMask: []float32{
					x, x, x, x, 0, x, x,
					x, x, x, x, 0, 0, x,
					x, x, x, x, x, x, 0,
				},
			},
			{
				name:          "ThirdBatch",
				in:            []float32{8, 9},
				inShape:       []int{1, 1, 2},
				seqs:          []int{0, 0},
				pos:           []int32{7, 8},
				expected:      []float32{1, 2, 3, 4, 5, 6, 7, 8, 9},
				expectedShape: []int{1, 1, 9},
				expectedMask: []float32{
					x, x, x, x, x, x, 0, 0, x,
					x, x, x, x, x, x, x, x, 0,
				},
			},
		},
	)
}

Jesse Gross's avatar
Jesse Gross committed
280
281
282
283
284
func TestSequences(t *testing.T) {
	backend := &testBackend{}
	cache := NewCausalCache(nil)
	defer cache.Close()

285
	cache.Init(backend, ml.DTypeF16, 1, 16, 16)
Jesse Gross's avatar
Jesse Gross committed
286
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

	tests := []testCase{
		{
			name:          "FirstBatch",
			in:            []float32{1, 2, 3, 4},
			inShape:       []int{1, 1, 4},
			seqs:          []int{0, 0, 1, 1},
			pos:           []int32{0, 1, 0, 1},
			expected:      []float32{1, 2, 3, 4},
			expectedShape: []int{1, 1, 4},
			expectedMask:  []float32{0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0},
		},
		{
			name:          "SecondBatch",
			in:            []float32{5, 6},
			inShape:       []int{1, 1, 2},
			seqs:          []int{0, 1},
			pos:           []int32{2, 2},
			expected:      []float32{1, 2, 3, 4, 5, 6},
			expectedShape: []int{1, 1, 6},
			expectedMask:  []float32{0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, float32(math.Inf(-1)), 0},
		},
	}

	testCache(t, backend, cache, tests)
}

func TestRemove(t *testing.T) {
	backend := &testBackend{}
	cache := NewCausalCache(func(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error) {
		return key.Add(ctx, shift), nil
	})
	defer cache.Close()

320
	cache.Init(backend, ml.DTypeF16, 1, 16, 16)
Jesse Gross's avatar
Jesse Gross committed
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384

	tests := []testCase{
		{
			name:          "FirstBatch",
			in:            []float32{1, 2, 3, 4},
			inShape:       []int{1, 1, 4},
			seqs:          []int{0, 0, 1, 1},
			pos:           []int32{0, 1, 0, 1},
			expected:      []float32{1, 2, 3, 4},
			expectedShape: []int{1, 1, 4},
			expectedMask:  []float32{0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0},
		},
	}

	testCache(t, backend, cache, tests)

	err := cache.Remove(0, 1, math.MaxInt32)
	if err != nil {
		panic(err)
	}

	tests = []testCase{
		{
			name:          "RemoveEnd",
			in:            []float32{5, 6},
			inShape:       []int{1, 1, 2},
			seqs:          []int{0, 1},
			pos:           []int32{1, 2},
			expected:      []float32{1, 2, 3, 4, 5, 6},
			expectedShape: []int{1, 1, 6},
			expectedMask:  []float32{0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, float32(math.Inf(-1)), 0},
		},
	}

	testCache(t, backend, cache, tests)

	err = cache.Remove(0, 0, 1)
	if err != nil {
		panic(err)
	}

	tests = []testCase{
		{
			name:          "RemoveMiddle",
			in:            []float32{7, 8},
			inShape:       []int{1, 1, 2},
			seqs:          []int{0, 0},
			pos:           []int32{1, 2},
			expected:      []float32{7, 8, 3, 4, 4},
			expectedShape: []int{1, 1, 5},
			expectedMask:  []float32{0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), 0},
		},
	}

	testCache(t, backend, cache, tests)
}

func TestDefrag(t *testing.T) {
	backend := &testBackend{}
	cache := NewCausalCache(func(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error) {
		return key.Add(ctx, shift), nil
	})
	defer cache.Close()

385
	cache.Init(backend, ml.DTypeF16, 1, 16, 16)
Jesse Gross's avatar
Jesse Gross committed
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432

	tests := []testCase{
		{
			name:          "FirstBatch",
			in:            []float32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
			inShape:       []int{1, 1, 16},
			seqs:          []int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
			pos:           []int32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15},
			expected:      []float32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
			expectedShape: []int{1, 1, 16},
			expectedMask:  []float32{0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, 0, 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, 0, 0, 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, 0, 0, 0, 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, float32(math.Inf(-1)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
		},
	}

	testCache(t, backend, cache, tests)

	err := cache.Remove(0, 2, 4)
	if err != nil {
		panic(err)
	}

	err = cache.Remove(0, 13, math.MaxInt32)
	if err != nil {
		panic(err)
	}

	tests = []testCase{
		{
			name:          "Defrag",
			in:            []float32{17, 18, 19},
			inShape:       []int{1, 1, 3},
			seqs:          []int{0, 0, 0},
			pos:           []int32{16, 17, 18},
			expected:      []float32{1, 2, 12, 13, 3, 4, 5, 6, 7, 8, 9, 10, 11, 17, 18, 19},
			expectedShape: []int{1, 1, 16},
			expectedMask:  []float32{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, float32(math.Inf(-1)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
		},
	}

	testCache(t, backend, cache, tests)
}

func TestCopy(t *testing.T) {
	backend := &testBackend{}
	cache := NewCausalCache(func(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error) { return key, nil })
	defer cache.Close()

433
	cache.Init(backend, ml.DTypeF16, 1, 16, 16)
Jesse Gross's avatar
Jesse Gross committed
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473

	tests := []testCase{
		{
			name:          "FirstBatch",
			in:            []float32{1, 2, 3, 4},
			inShape:       []int{1, 1, 4},
			seqs:          []int{0, 0, 0, 0},
			pos:           []int32{0, 1, 2, 3},
			expected:      []float32{1, 2, 3, 4},
			expectedShape: []int{1, 1, 4},
			expectedMask:  []float32{0, float32(math.Inf(-1)), float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0, 0, float32(math.Inf(-1)), 0, 0, 0, 0},
		},
	}

	testCache(t, backend, cache, tests)

	cache.CopyPrefix(0, 1, 2)

	tests = []testCase{
		{
			name:          "Copy",
			in:            []float32{5, 6},
			inShape:       []int{1, 1, 2},
			seqs:          []int{1, 1},
			pos:           []int32{3, 4},
			expected:      []float32{1, 2, 3, 4, 5, 6},
			expectedShape: []int{1, 1, 6},
			expectedMask:  []float32{0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), 0, float32(math.Inf(-1)), 0, 0, float32(math.Inf(-1)), float32(math.Inf(-1)), 0, 0},
		},
	}

	testCache(t, backend, cache, tests)
}

func testCache(t *testing.T, backend ml.Backend, cache Cache, tests []testCase) {
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			context := backend.NewContext()
			defer context.Close()

474
			err := cache.StartForward(context, input.Batch{Positions: test.pos, Sequences: test.seqs}, false)
Jesse Gross's avatar
Jesse Gross committed
475
476
477
478
479
			if err != nil {
				panic(err)
			}

			cache.SetLayer(0)
480
			tensor := context.FromFloatSlice(test.in, test.inShape...)
Jesse Gross's avatar
Jesse Gross committed
481
482
483
484
			cache.Put(context, tensor, tensor)

			out, _, mask := cache.Get(context)

485
			context.Forward(out, mask).Compute(out, mask)
Jesse Gross's avatar
Jesse Gross committed
486

Michael Yang's avatar
Michael Yang committed
487
488
489
490
491
492
493
494
495
496
			if !slices.Equal(out.Floats(), test.expected) {
				t.Errorf("TestCache: have %v; want %v", out.Floats(), test.expected)
			}

			if !slices.Equal(out.Shape(), test.expectedShape) {
				t.Errorf("TestCache: has shape %v; want %v", out.Shape(), test.expectedShape)
			}

			if !slices.Equal(mask.Floats(), test.expectedMask) {
				t.Errorf("TestCache: have mask: have %v want %v", mask.Floats(), test.expectedMask)
Jesse Gross's avatar
Jesse Gross committed
497
498
499
500
501
			}
		})
	}
}

502
503
504
505
506
507
508
509
510
511
512
513
func TestCanResume(t *testing.T) {
	backend := &testBackend{}
	windowSize := int32(4)
	cache := NewSWACache(windowSize, nil)
	defer cache.Close()

	cache.Init(backend, ml.DTypeF16, 1, 16, 16)

	context := backend.NewContext()
	defer context.Close()

	err := cache.StartForward(context, input.Batch{
514
515
		Positions: []int32{0, 1, 2, 3, 4},
		Sequences: []int{0, 0, 0, 0, 0},
516
	}, false)
517
518
519
520
521
	if err != nil {
		t.Fatalf("StartForward failed: %v", err)
	}

	cache.SetLayer(0)
522
	tensor := context.FromFloatSlice([]float32{1, 2, 3, 4, 5}, 1, 1, 5)
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
	cache.Put(context, tensor, tensor)

	// with window size 4, nothing has slid out of the window yet
	if !cache.CanResume(0, 0) {
		t.Errorf("CanResume(0, 0) = false, want true (within window)")
	}
	if !cache.CanResume(0, 1) {
		t.Errorf("CanResume(0, 1) = false, want true (within window)")
	}
	if !cache.CanResume(0, 2) {
		t.Errorf("CanResume(0, 2) = false, want true (within window)")
	}
	if !cache.CanResume(0, 3) {
		t.Errorf("CanResume(0, 3) = false, want true (latest position)")
	}
538
539
540
	if !cache.CanResume(0, 4) {
		t.Errorf("CanResume(0, 4) = false, want true (latest position)")
	}
541

542
	// shift window by adding position 5
543
	err = cache.StartForward(context, input.Batch{
544
545
		Positions: []int32{5},
		Sequences: []int{0},
546
	}, false)
547
548
549
550
551
	if err != nil {
		t.Fatalf("StartForward failed: %v", err)
	}

	cache.SetLayer(0)
552
	tensor = context.FromFloatSlice([]float32{6}, 1, 1, 1)
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
	cache.Put(context, tensor, tensor)

	// only the latest position has overlapping windows
	if cache.CanResume(0, 0) {
		t.Errorf("after shift: CanResume(0, 0) = true, want false (outside window)")
	}
	if cache.CanResume(0, 1) {
		t.Errorf("after shift: CanResume(0, 1) = true, want false (outside window)")
	}
	if cache.CanResume(0, 2) {
		t.Errorf("after shift: CanResume(0, 2) = true, want false (outside window)")
	}
	if cache.CanResume(0, 3) {
		t.Errorf("after shift: CanResume(0, 3) = true, want false (outside window)")
	}
	if cache.CanResume(0, 4) {
		t.Errorf("after shift: CanResume(0, 4) = true, want false (outside window)")
	}
	if !cache.CanResume(0, 5) {
		t.Errorf("after shift: CanResume(0, 5) = false, want true (latest position)")
	}
}

576
577
578
579
580
581
582
583
584
585
586
587
588
func TestCanResumeSWAMem(t *testing.T) {
	backend := &testBackend{}
	windowSize := int32(4)
	memSize := int32(5)
	cache := NewSWAMemCache(windowSize, memSize, nil)
	defer cache.Close()

	cache.Init(backend, ml.DTypeF16, 1, 16, 16)

	context := backend.NewContext()
	defer context.Close()

	err := cache.StartForward(context, input.Batch{
589
590
		Positions: []int32{0, 1, 2, 3, 4, 5, 6},
		Sequences: []int{0, 0, 0, 0, 0, 0, 0},
591
592
593
594
595
596
	}, false)
	if err != nil {
		t.Fatalf("StartForward failed: %v", err)
	}

	cache.SetLayer(0)
597
	tensor := context.FromFloatSlice([]float32{1, 2, 3, 4, 5, 6, 7}, 1, 1, 7)
598
599
	cache.Put(context, tensor, tensor)

600
	// shift window by adding position 7
601
	err = cache.StartForward(context, input.Batch{
602
603
		Positions: []int32{7},
		Sequences: []int{0},
604
605
606
607
608
609
	}, false)
	if err != nil {
		t.Fatalf("StartForward failed: %v", err)
	}

	cache.SetLayer(0)
610
	tensor = context.FromFloatSlice([]float32{8}, 1, 1, 1)
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
	cache.Put(context, tensor, tensor)

	// only the latest position has overlapping windows
	if cache.CanResume(0, 0) {
		t.Errorf("after shift: CanResume(0, 0) = true, want false (outside window)")
	}
	if cache.CanResume(0, 1) {
		t.Errorf("after shift: CanResume(0, 1) = true, want false (outside window)")
	}
	if cache.CanResume(0, 2) {
		t.Errorf("after shift: CanResume(0, 2) = true, want false (outside window)")
	}
	if cache.CanResume(0, 3) {
		t.Errorf("after shift: CanResume(0, 3) = true, want false (outside window)")
	}
	if cache.CanResume(0, 4) {
		t.Errorf("after shift: CanResume(0, 4) = true, want false (outside window)")
	}
	if cache.CanResume(0, 5) {
		t.Errorf("after shift: CanResume(0, 5) = true, want false (outside window)")
	}
	if !cache.CanResume(0, 6) {
		t.Errorf("after shift: CanResume(0, 6) = false, want true (inside window)")
	}
	if !cache.CanResume(0, 7) {
		t.Errorf("after shift: CanResume(0, 7) = false, want true (latest position)")
	}
}

Michael Yang's avatar
Michael Yang committed
640
641
type testBackend struct {
	ml.Backend
Jesse Gross's avatar
Jesse Gross committed
642
643
644
645
646
647
}

func (b *testBackend) NewContext() ml.Context {
	return &testContext{}
}

Michael Yang's avatar
Michael Yang committed
648
649
650
651
func (b *testBackend) NewContextSize(int) ml.Context {
	return &testContext{}
}

Michael Yang's avatar
Michael Yang committed
652
653
type testContext struct {
	ml.Context
654
655
}

656
func (c *testContext) Empty(dtype ml.DType, shape ...int) ml.Tensor {
Jesse Gross's avatar
Jesse Gross committed
657
658
659
660
661
662
663
664
665
666
667
668
	total := 0

	if len(shape) > 0 {
		total = 1
		for _, s := range shape {
			total *= s
		}
	}

	return &testTensor{dtype: dtype, elementSize: 4, data: make([]float32, total), shape: shape}
}

669
670
671
672
func (c *testContext) Zeros(dtype ml.DType, shape ...int) ml.Tensor {
	return c.Empty(dtype, shape...)
}

673
func (c *testContext) FromFloatSlice(s []float32, shape ...int) ml.Tensor {
674
	t := c.Empty(ml.DTypeF32, shape...).(*testTensor)
Jesse Gross's avatar
Jesse Gross committed
675
676
677

	copy(t.data, s)

678
	return t
Jesse Gross's avatar
Jesse Gross committed
679
680
}

681
func (c *testContext) FromIntSlice(s []int32, shape ...int) ml.Tensor {
Jesse Gross's avatar
Jesse Gross committed
682
683
684
685
686
	f := make([]float32, len(s))
	for i := range f {
		f[i] = float32(s[i])
	}

687
	out := c.FromFloatSlice(f, shape...)
Jesse Gross's avatar
Jesse Gross committed
688
689
	out.(*testTensor).dtype = ml.DTypeI32

690
	return out
Jesse Gross's avatar
Jesse Gross committed
691
692
}

Michael Yang's avatar
arange  
Michael Yang committed
693
694
695
696
697
698
func (c *testContext) Arange(start, stop, step float32, dtype ml.DType) ml.Tensor {
	s := make([]float32, 0, int((stop-start)/step))
	for i := start; i < stop; i += step {
		s = append(s, i)
	}

699
	out := c.FromFloatSlice(s, len(s))
Michael Yang's avatar
arange  
Michael Yang committed
700
701
702
703
	out.(*testTensor).dtype = dtype
	return out
}

Michael Yang's avatar
Michael Yang committed
704
705
706
func (c *testContext) Input() ml.Context    { return c }
func (c *testContext) Layer(int) ml.Context { return c }

Michael Yang's avatar
Michael Yang committed
707
func (c *testContext) Forward(...ml.Tensor) ml.Context { return c }
Jesse Gross's avatar
Jesse Gross committed
708
709
710

func (c *testContext) Compute(...ml.Tensor) {}

711
func (c *testContext) Reserve() {}
712

Michael Yang's avatar
Michael Yang committed
713
func (c *testContext) MaxGraphNodes() int {
Jesse Gross's avatar
Jesse Gross committed
714
715
716
717
718
719
	return 10
}

func (c *testContext) Close() {}

type testTensor struct {
Michael Yang's avatar
Michael Yang committed
720
721
	ml.Tensor

Jesse Gross's avatar
Jesse Gross committed
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
	dtype       ml.DType
	elementSize int
	data        []float32
	shape       []int
}

func (t *testTensor) Dim(n int) int {
	return t.shape[n]
}

func (t *testTensor) Stride(n int) int {
	stride := t.elementSize
	for i := range n {
		stride *= t.shape[i]
	}

	return stride
}

func (t *testTensor) Shape() []int {
	return t.shape
}

func (t *testTensor) DType() ml.DType {
	return t.dtype
}

func (t *testTensor) Floats() []float32 {
	out := make([]float32, len(t.data))
	copy(out, t.data)
	return out
}

755
756
757
758
759
760
761
762
func (t *testTensor) Neg(ctx ml.Context) ml.Tensor {
	out := ctx.Empty(t.DType(), t.Shape()...).(*testTensor)
	for i := range out.data {
		out.data[i] = -t.data[i]
	}
	return out
}

Jesse Gross's avatar
Jesse Gross committed
763
func (t *testTensor) Add(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
764
	out := ctx.Empty(t.DType(), t.Shape()...).(*testTensor)
Jesse Gross's avatar
Jesse Gross committed
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788

	for i := range out.data {
		out.data[i] = t.data[i] + t2.(*testTensor).data[i]
	}

	return out
}

func (t *testTensor) View(ctx ml.Context, offset int, shape ...int) ml.Tensor {
	offset /= t.elementSize

	var s []int

	switch len(shape) {
	case 1:
		s = []int{shape[0]}
	case 5:
		s = []int{shape[0], shape[2], shape[4]}
	default:
		panic("unsupported number of dimensions")
	}

	context := &testContext{}

789
	view := context.Empty(t.dtype, s...).(*testTensor)
Jesse Gross's avatar
Jesse Gross committed
790
791
792
793
794
795
796
797
798
	view.data = t.data[offset : offset+len(view.data)]

	return view
}

func (t *testTensor) Copy(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
	copy(t2.(*testTensor).data, t.data)
	return nil
}