causal_test.go 24.1 KB
Newer Older
Jesse Gross's avatar
Jesse Gross committed
1
2
3
package kvcache

import (
4
	"fmt"
Jesse Gross's avatar
Jesse Gross committed
5
6
7
8
9
	"math"
	"slices"
	"testing"

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

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

24
25
26
27
28
29
func runPermutedVariants(t *testing.T, fn func(t *testing.T, backend *testBackend)) {
	t.Helper()
	for _, permuted := range []bool{false, true} {
		t.Run(fmt.Sprintf("PermutedV=%t", permuted), func(t *testing.T) {
			fn(t, &testBackend{permutedV: permuted})
		})
Jesse Gross's avatar
Jesse Gross committed
30
	}
31
32
33
34
35
36
}

func TestStore(t *testing.T) {
	runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
		cache := NewCausalCache(nil)
		defer cache.Close()
Jesse Gross's avatar
Jesse Gross committed
37

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
		cache.Init(backend, ml.DTypeF16, 1, 16, 16)

		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)
	})
Jesse Gross's avatar
Jesse Gross committed
65
66
67
}

func TestSWA(t *testing.T) {
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
	runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
		cache := NewSWACache(1, 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,
				},
91
			},
92
93
94
95
96
97
98
99
100
101
102
103
			{
				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},
				expectedMask: []float32{
					0, x, x, 0,
					0, 0, x, x,
				},
104
			},
105
		}
106

107
108
		testCache(t, backend, cache, tests)
	})
109
110
}

111
func TestSWASeparateBatches(t *testing.T) {
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
	runPermutedVariants(t, func(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,
				},
133
			},
134
135
136
137
138
139
140
141
142
143
144
145
			{
				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,
				},
146
			},
147
148
149
150
151
152
153
154
155
156
157
158
			{
				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,
				},
159
			},
160
161
162
163
164
165
166
167
168
169
170
171
			{
				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,
				},
172
			},
173
174
175
176
177
178
179
180
181
182
183
184
			{
				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,
				},
185
			},
186
		}
187

188
189
		testCache(t, backend, cache, tests)
	})
190
191
}

192
func TestSWAMem(t *testing.T) {
193
194
195
	runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
		cache := NewSWAMemCache(1, 3, nil)
		defer cache.Close()
Michael Yang's avatar
Michael Yang committed
196

197
		cache.Init(backend, ml.DTypeF16, 1, 16, 16)
Michael Yang's avatar
Michael Yang committed
198

199
		x := float32(math.Inf(-1))
Michael Yang's avatar
Michael Yang committed
200

201
		tests := []testCase{
Michael Yang's avatar
Michael Yang committed
202
203
204
205
206
207
208
209
210
211
212
			{
				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,
213
					x, 0, 0, x,
Michael Yang's avatar
Michael Yang committed
214
215
216
217
218
					x, x, 0, 0,
				},
			},
			{
				name:          "SecondBatch",
219
				in:            []float32{5, 6},
Michael Yang's avatar
Michael Yang committed
220
221
				inShape:       []int{1, 1, 2},
				seqs:          []int{0, 0},
222
223
224
				pos:           []int32{4, 5},
				expected:      []float32{5, 2, 3, 4, 6},
				expectedShape: []int{1, 1, 5},
Michael Yang's avatar
Michael Yang committed
225
				expectedMask: []float32{
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
280
281
282
283
284
285
286
287
288
					0, x, x, 0, x,
					0, x, x, x, 0,
				},
			},
		}

		testCache(t, backend, cache, tests)
	})
}

func TestChunkedAttention(t *testing.T) {
	runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
		cache := NewChunkedAttentionCache(2, nil)
		defer cache.Close()

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

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

		testCache(
			t, backend, 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,
					},
Michael Yang's avatar
Michael Yang committed
289
290
				},
			},
291
292
		)
	})
Michael Yang's avatar
Michael Yang committed
293
294
}

Jesse Gross's avatar
Jesse Gross committed
295
func TestSequences(t *testing.T) {
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
	runPermutedVariants(t, func(t *testing.T, backend *testBackend) {
		cache := NewCausalCache(nil)
		defer cache.Close()

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

		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},
			},
		}
Jesse Gross's avatar
Jesse Gross committed
324

325
326
		testCache(t, backend, cache, tests)
	})
Jesse Gross's avatar
Jesse Gross committed
327
328
329
}

func TestRemove(t *testing.T) {
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
	runPermutedVariants(t, func(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()

		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, 1, 1},
				pos:           []int32{0, 1, 0, 1},
				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,
				},
355
			},
356
		}
Jesse Gross's avatar
Jesse Gross committed
357

358
		testCache(t, backend, cache, tests)
Jesse Gross's avatar
Jesse Gross committed
359

360
361
362
363
		err := cache.Remove(0, 1, math.MaxInt32)
		if err != nil {
			panic(err)
		}
Jesse Gross's avatar
Jesse Gross committed
364

365
366
367
368
369
370
371
372
373
374
375
376
377
		tests = []testCase{
			{
				name:          "RemoveEnd",
				in:            []float32{5, 6},
				inShape:       []int{1, 1, 2},
				seqs:          []int{0, 1},
				pos:           []int32{1, 2},
				expected:      []float32{1, 5, 3, 4, 6},
				expectedShape: []int{1, 1, 5},
				expectedMask: []float32{
					0, 0, x, x, x,
					x, x, 0, 0, 0,
				},
378
			},
379
		}
Jesse Gross's avatar
Jesse Gross committed
380

381
		testCache(t, backend, cache, tests)
Jesse Gross's avatar
Jesse Gross committed
382

383
384
385
386
		err = cache.Remove(0, 0, 1)
		if err != nil {
			panic(err)
		}
Jesse Gross's avatar
Jesse Gross committed
387

388
389
390
391
392
393
394
395
396
397
398
399
400
		tests = []testCase{
			{
				name:          "RemoveMiddle",
				in:            []float32{7, 8},
				inShape:       []int{1, 1, 2},
				seqs:          []int{0, 0},
				pos:           []int32{1, 2},
				expected:      []float32{7, 4, 3, 4, 6, 8},
				expectedShape: []int{1, 1, 6},
				expectedMask: []float32{
					0, 0, x, x, x, x,
					0, 0, x, x, x, 0,
				},
401
			},
402
		}
Jesse Gross's avatar
Jesse Gross committed
403

404
405
		testCache(t, backend, cache, tests)
	})
Jesse Gross's avatar
Jesse Gross committed
406
407
408
}

func TestCopy(t *testing.T) {
409
410
411
	runPermutedVariants(t, func(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()
Jesse Gross's avatar
Jesse Gross committed
412

413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
		cache.Init(backend, ml.DTypeF16, 1, 16, 16)

		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},
			},
		}
Jesse Gross's avatar
Jesse Gross committed
444

445
446
		testCache(t, backend, cache, tests)
	})
Jesse Gross's avatar
Jesse Gross committed
447
448
449
450
451
452
453
454
}

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()

455
			err := cache.StartForward(context, input.Batch{Positions: test.pos, Sequences: test.seqs}, false)
Jesse Gross's avatar
Jesse Gross committed
456
457
458
459
460
			if err != nil {
				panic(err)
			}

			cache.SetLayer(0)
Michael Yang's avatar
Michael Yang committed
461
			tensor := context.FromFloats(test.in, test.inShape...)
Jesse Gross's avatar
Jesse Gross committed
462
463
464
465
			cache.Put(context, tensor, tensor)

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

466
			context.Forward(out, mask).Compute(out, mask)
Jesse Gross's avatar
Jesse Gross committed
467

Michael Yang's avatar
Michael Yang committed
468
469
470
471
472
473
474
475
476
477
			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
478
479
480
481
482
			}
		})
	}
}

483
func TestCanResume(t *testing.T) {
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
	runPermutedVariants(t, func(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{
			Positions: []int32{0, 1, 2, 3, 4},
			Sequences: []int{0, 0, 0, 0, 0},
		}, false)
		if err != nil {
			t.Fatalf("StartForward failed: %v", err)
		}
501

502
503
504
		cache.SetLayer(0)
		tensor := context.FromFloats([]float32{1, 2, 3, 4, 5}, 1, 1, 5)
		cache.Put(context, tensor, tensor)
505

506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
		// 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)")
		}
		if !cache.CanResume(0, 4) {
			t.Errorf("CanResume(0, 4) = false, want true (latest position)")
		}
522

523
524
525
526
527
528
529
530
		// shift window by adding position 5
		err = cache.StartForward(context, input.Batch{
			Positions: []int32{5},
			Sequences: []int{0},
		}, false)
		if err != nil {
			t.Fatalf("StartForward failed: %v", err)
		}
531

532
533
534
		cache.SetLayer(0)
		tensor = context.FromFloats([]float32{6}, 1, 1, 1)
		cache.Put(context, tensor, tensor)
535

536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
		// 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)")
		}
	})
556
557
}

558
func TestCanResumeSWAMem(t *testing.T) {
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
	runPermutedVariants(t, func(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{
			Positions: []int32{0, 1, 2, 3, 4, 5, 6},
			Sequences: []int{0, 0, 0, 0, 0, 0, 0},
		}, false)
		if err != nil {
			t.Fatalf("StartForward failed: %v", err)
		}
577

578
579
580
581
582
583
584
585
586
587
588
589
		cache.SetLayer(0)
		tensor := context.FromFloats([]float32{1, 2, 3, 4, 5, 6, 7}, 1, 1, 7)
		cache.Put(context, tensor, tensor)

		// shift window by adding position 7
		err = cache.StartForward(context, input.Batch{
			Positions: []int32{7},
			Sequences: []int{0},
		}, false)
		if err != nil {
			t.Fatalf("StartForward failed: %v", err)
		}
590

591
592
593
		cache.SetLayer(0)
		tensor = context.FromFloats([]float32{8}, 1, 1, 1)
		cache.Put(context, tensor, tensor)
594

595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
		// 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)")
		}
	})
621
622
}

Michael Yang's avatar
Michael Yang committed
623
624
type testBackend struct {
	ml.Backend
625
	permutedV bool
Jesse Gross's avatar
Jesse Gross committed
626
627
628
629
630
631
}

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

Michael Yang's avatar
Michael Yang committed
632
633
634
635
func (b *testBackend) NewContextSize(int) ml.Context {
	return &testContext{}
}

636
637
638
639
func (b *testBackend) CacheConfig() ml.CacheConfig {
	return ml.CacheConfig{PermutedV: b.permutedV}
}

Michael Yang's avatar
Michael Yang committed
640
641
type testContext struct {
	ml.Context
642
643
}

644
func (c *testContext) Empty(dtype ml.DType, shape ...int) ml.Tensor {
Jesse Gross's avatar
Jesse Gross committed
645
646
647
648
649
650
651
652
653
654
655
656
	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}
}

657
658
659
660
func (c *testContext) Zeros(dtype ml.DType, shape ...int) ml.Tensor {
	return c.Empty(dtype, shape...)
}

Michael Yang's avatar
Michael Yang committed
661
func (c *testContext) FromFloats(s []float32, shape ...int) ml.Tensor {
662
	t := c.Empty(ml.DTypeF32, shape...).(*testTensor)
Jesse Gross's avatar
Jesse Gross committed
663
664
665

	copy(t.data, s)

666
	return t
Jesse Gross's avatar
Jesse Gross committed
667
668
}

Michael Yang's avatar
Michael Yang committed
669
func (c *testContext) FromInts(s []int32, shape ...int) ml.Tensor {
Jesse Gross's avatar
Jesse Gross committed
670
671
672
673
674
	f := make([]float32, len(s))
	for i := range f {
		f[i] = float32(s[i])
	}

Michael Yang's avatar
Michael Yang committed
675
	out := c.FromFloats(f, shape...)
Jesse Gross's avatar
Jesse Gross committed
676
677
	out.(*testTensor).dtype = ml.DTypeI32

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

Michael Yang's avatar
arange  
Michael Yang committed
681
682
683
684
685
686
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)
	}

Michael Yang's avatar
Michael Yang committed
687
	out := c.FromFloats(s, len(s))
Michael Yang's avatar
arange  
Michael Yang committed
688
689
690
691
	out.(*testTensor).dtype = dtype
	return out
}

Michael Yang's avatar
Michael Yang committed
692
693
694
func (c *testContext) Input() ml.Context    { return c }
func (c *testContext) Layer(int) ml.Context { return c }

Michael Yang's avatar
Michael Yang committed
695
func (c *testContext) Forward(...ml.Tensor) ml.Context { return c }
Jesse Gross's avatar
Jesse Gross committed
696
697
698

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

699
func (c *testContext) Reserve() {}
700

Michael Yang's avatar
Michael Yang committed
701
func (c *testContext) MaxGraphNodes() int {
Jesse Gross's avatar
Jesse Gross committed
702
703
704
705
706
707
	return 10
}

func (c *testContext) Close() {}

type testTensor struct {
Michael Yang's avatar
Michael Yang committed
708
709
	ml.Tensor

Jesse Gross's avatar
Jesse Gross committed
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
	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
}

743
744
745
746
747
748
749
750
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
751
func (t *testTensor) Add(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
752
	out := ctx.Empty(t.DType(), t.Shape()...).(*testTensor)
Jesse Gross's avatar
Jesse Gross committed
753
754
755
756
757
758
759
760

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

	return out
}

761
762
763
764
765
766
767
768
769
func (t *testTensor) Reshape(ctx ml.Context, shape ...int) ml.Tensor {
	return &testTensor{
		dtype:       t.dtype,
		elementSize: t.elementSize,
		data:        t.data,
		shape:       shape,
	}
}

Jesse Gross's avatar
Jesse Gross committed
770
771
772
773
774
775
776
777
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]}
778
779
	case 3:
		s = []int{shape[0], shape[2]}
Jesse Gross's avatar
Jesse Gross committed
780
781
782
783
784
785
786
787
	case 5:
		s = []int{shape[0], shape[2], shape[4]}
	default:
		panic("unsupported number of dimensions")
	}

	context := &testContext{}

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

	return view
}

794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
func (t *testTensor) Permute(ctx ml.Context, order ...int) ml.Tensor {
	if len(t.shape) > 4 || len(order) > 4 {
		panic("permute only supports up to 4 dimensions")
	}

	if len(order) != len(t.shape) && len(order) != 4 {
		panic("invalid number of dimensions for permute")
	}

	// ggml_permute expects 4 axes, so fill in any missing dimensions.
	orderFull := append(make([]int, 0, 4), order...)
	for len(orderFull) < 4 {
		orderFull = append(orderFull, len(orderFull))
	}

	seen := [4]bool{}

	shape4 := [4]int{1, 1, 1, 1}
	for i := 0; i < len(t.shape) && i < 4; i++ {
		shape4[i] = t.shape[i]
	}

	newShape4 := [4]int{1, 1, 1, 1}
	for axis := range 4 {
		dst := orderFull[axis]
		if dst < 0 || dst >= 4 {
			panic("invalid axis for permute")
		}
		if seen[dst] {
			panic("duplicate axis for permute")
		}
		seen[dst] = true
		newShape4[dst] = shape4[axis]
	}

	total := len(t.data)
	newData := make([]float32, total)

	if total > 0 {
		oldDims := shape4
		newDims := newShape4

		oldStride := [4]int{1, 1, 1, 1}
		newStride := [4]int{1, 1, 1, 1}
		for i := 1; i < 4; i++ {
			oldStride[i] = oldStride[i-1] * oldDims[i-1]
			newStride[i] = newStride[i-1] * newDims[i-1]
		}

		var coords [4]int
		var newCoords [4]int

		for idx := range total {
			remainder := idx
			for axis := range 4 {
				dim := oldDims[axis]
				if dim == 0 {
					coords[axis] = 0
					continue
				}
				coords[axis] = remainder % dim
				remainder /= dim
			}

			for axis := range 4 {
				newCoords[orderFull[axis]] = coords[axis]
			}

			newIndex := 0
			for axis := range 4 {
				if newDims[axis] == 0 {
					continue
				}
				newIndex += newCoords[axis] * newStride[axis]
			}

			newData[newIndex] = t.data[idx]
		}
	}

	numDims := 4
	for numDims > 1 && newShape4[numDims-1] <= 1 {
		numDims--
	}

	newShape := make([]int, numDims)
	copy(newShape, newShape4[:numDims])

	return &testTensor{
		dtype:       t.dtype,
		elementSize: t.elementSize,
		data:        newData,
		shape:       newShape,
	}
}

890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
func (t *testTensor) SetRows(ctx ml.Context, src ml.Tensor, idxs ml.Tensor) ml.Tensor {
	dst := t
	srcTensor := src.(*testTensor)
	idxTensor := idxs.(*testTensor)

	shapeTo4D := func(shape []int) [4]int {
		out := [4]int{1, 1, 1, 1}
		for i := 0; i < len(shape) && i < 4; i++ {
			out[i] = shape[i]
		}
		return out
	}

	computeStrides := func(shape [4]int) [4]int {
		out := [4]int{1, 1, 1, 1}
		for i := 1; i < 4; i++ {
			out[i] = out[i-1] * shape[i-1]
		}
		return out
	}

	dstShape4D := shapeTo4D(dst.shape)
	srcShape4D := shapeTo4D(srcTensor.shape)
	idxShape4D := shapeTo4D(idxTensor.shape)

	if dstShape4D[0] != srcShape4D[0] || dstShape4D[2] != srcShape4D[2] || dstShape4D[3] != srcShape4D[3] {
		panic("SetRows requires matching tensor shapes")
	}

	if srcShape4D[1] != idxShape4D[0] {
		panic("SetRows rows/index mismatch")
	}

	if srcShape4D[2]%idxShape4D[1] != 0 || srcShape4D[3]%idxShape4D[2] != 0 {
		panic("SetRows cannot broadcast indices")
	}

	if idxShape4D[3] != 1 {
		panic("SetRows expects 1D or 2D index tensors")
	}

	dstStride := computeStrides(dstShape4D)
	srcStride := computeStrides(srcShape4D)
	idxStride := computeStrides(idxShape4D)

	numColumns := srcShape4D[0]
	numRows := srcShape4D[1]

	for dim3Index := range dstShape4D[3] {
		for dim2Index := range dstShape4D[2] {
			idxDim2 := 0
			idxDim3 := 0
			if idxShape4D[1] > 0 {
				idxDim2 = dim2Index % idxShape4D[1]
			}
			if idxShape4D[2] > 0 {
				idxDim3 = dim3Index % idxShape4D[2]
			}

			idxBase := idxDim3*idxStride[2] + idxDim2*idxStride[1]
			srcBase := dim3Index*srcStride[3] + dim2Index*srcStride[2]
			dstBase := dim3Index*dstStride[3] + dim2Index*dstStride[2]

			for row := range numRows {
				idx := int(idxTensor.data[idxBase+row*idxStride[0]])
				if idx < 0 || idx >= dstShape4D[1] {
					panic("SetRows index out of range")
				}

				srcOffset := srcBase + row*srcStride[1]
				dstOffset := dstBase + idx*dstStride[1]

				copy(dst.data[dstOffset:dstOffset+numColumns], srcTensor.data[srcOffset:srcOffset+numColumns])
			}
		}
	}

	return dst
}

Jesse Gross's avatar
Jesse Gross committed
970
971
972
973
func (t *testTensor) Copy(ctx ml.Context, t2 ml.Tensor) ml.Tensor {
	copy(t2.(*testTensor).data, t.data)
	return nil
}