"examples/community/pipeline_stable_diffusion_xl_ipex.py" did not exist on "30e5e81d58eb9c3979c07e6626bae89c1df8c0e1"
causal.go 19.7 KB
Newer Older
Jesse Gross's avatar
Jesse Gross committed
1
2
3
4
5
6
7
8
9
10
package kvcache

import (
	"errors"
	"fmt"
	"log/slog"
	"math"
	"slices"

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

type shiftFn func(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error)

// Causal cache stores K and V tensors according to their position in the
// sequence. Returns the history and a mask for attending to past tokens
//
// The tensors are of shape embed dim, kv heads, batch size
// The mask is of shape history size, batch size
type Causal struct {
22
23
24
25
26
27
28
29
30
31
	DType ml.DType

	// swaWindowSize is the number of tokens that will be included in the mask
	// during attention operations. swaMemorySize is the number of tokens that
	// will be retained in memory for partial prefix caching. Set to math.MaxInt32
	// for unlimited or if sliding window attention is not being used.
	swaWindowSize int32
	swaMemorySize int32

	chunkSize int32
Jesse Gross's avatar
Jesse Gross committed
32

33
34
	opts CausalOptions

35
36
37
	// maxBatch is the largest batch that we might receive
	maxBatch int

38
39
40
	// config controls mostly backend-specific optimizations
	config *ml.CacheConfig

Jesse Gross's avatar
Jesse Gross committed
41
42
	// ** current forward pass **

43
44
45
46
47
	// curReserve indicates that this forward pass is only for
	// memory reservation and we should not update our metadata
	// based on it.
	curReserve bool

Jesse Gross's avatar
Jesse Gross committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
	// the active layer for Get and Put
	curLayer int

	// starting location for data storage for this batch
	curLoc int

	// size of the current batch
	curBatchSize int

	// mask of the cache as used by this batch
	curMask ml.Tensor

	// locations in the cache that are needed for this batch
	curCellRange cellRange

63
64
65
66
67
68
	// curSequences is the sequences corresponding to this pass's entries in the cache
	curSequences []int

	// curPositions is the positions corresponding to this pass's entries in the cache
	curPositions []int32

Jesse Gross's avatar
Jesse Gross committed
69
70
71
72
73
74
75
76
77
78
79
80
81
	// ** cache metadata **

	// for each possible location in the cache, stores the position and set of sequences
	// that reference the data there
	cells []cacheCell

	// maps from sequence to the range of locations where it is stored in the cache
	cellRanges map[int]cellRange

	// ** cache data storage **

	shiftFn      shiftFn
	backend      ml.Backend
82
83
	ctxs         map[int]ml.Context
	keys, values map[int]ml.Tensor
Jesse Gross's avatar
Jesse Gross committed
84
85
86
87
88
89
90
91
92
93
94
95
96
}

type cacheCell struct {
	pos       int32
	sequences []int
}

type cellRange struct {
	min int
	max int
}

func NewCausalCache(shift shiftFn) *Causal {
97
	return &Causal{
98
99
100
101
		shiftFn: shift,
		ctxs:    make(map[int]ml.Context),
		keys:    make(map[int]ml.Tensor),
		values:  make(map[int]ml.Tensor),
102
	}
Jesse Gross's avatar
Jesse Gross committed
103
104
105
}

func NewSWACache(windowSize int32, shift shiftFn) *Causal {
106
	return &Causal{
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
		swaWindowSize: windowSize,
		shiftFn:       shift,
		ctxs:          make(map[int]ml.Context),
		keys:          make(map[int]ml.Tensor),
		values:        make(map[int]ml.Tensor),
	}
}

func NewSWAMemCache(windowSize int32, memorySize int32, shift shiftFn) *Causal {
	return &Causal{
		swaWindowSize: windowSize,
		swaMemorySize: memorySize,
		shiftFn:       shift,
		ctxs:          make(map[int]ml.Context),
		keys:          make(map[int]ml.Tensor),
		values:        make(map[int]ml.Tensor),
123
	}
Jesse Gross's avatar
Jesse Gross committed
124
125
}

Michael Yang's avatar
Michael Yang committed
126
127
func NewChunkedAttentionCache(chunkSize int32, shift shiftFn) *Causal {
	return &Causal{
128
129
130
131
132
		chunkSize: chunkSize,
		shiftFn:   shift,
		ctxs:      make(map[int]ml.Context),
		keys:      make(map[int]ml.Tensor),
		values:    make(map[int]ml.Tensor),
Michael Yang's avatar
Michael Yang committed
133
134
135
	}
}

136
func (c *Causal) Init(backend ml.Backend, dtype ml.DType, maxSequences, capacity, maxBatch int) {
137
138
139
140
141
142
143
144
145
146
147
148
	if c.config == nil {
		var config ml.CacheConfig
		if cc, ok := backend.(ml.BackendCacheConfig); ok {
			config = cc.CacheConfig()
		}
		c.config = &config
	}

	if c.config.CachePadding == 0 {
		c.config.CachePadding = 1
	}

149
150
151
152
153
154
155
156
	if c.config.MaskBatchPadding == 0 {
		c.config.MaskBatchPadding = 1
	}

	if c.config.MaskDType == ml.DTypeOther {
		c.config.MaskDType = ml.DTypeF32
	}

157
158
159
160
161
162
163
164
165
166
167
168
169
170
	if c.swaWindowSize == 0 {
		c.swaWindowSize = math.MaxInt32
	}
	if c.swaMemorySize == 0 {
		c.swaMemorySize = c.swaWindowSize
	}
	if int(c.swaMemorySize) > capacity {
		c.swaMemorySize = math.MaxInt32
	}

	if c.swaMemorySize < c.swaWindowSize {
		panic(fmt.Errorf("sliding window memory (%v) must be at least as large as the window (%v)", c.swaMemorySize, c.swaWindowSize))
	}

171
	var cacheSize int
172
	if c.swaMemorySize == math.MaxInt32 {
173
174
		cacheSize = maxSequences * capacity
	} else {
175
		cacheSize = (maxSequences * int(c.swaMemorySize)) + maxBatch
176
	}
177
178
179
	cacheSize = roundUp(cacheSize, c.config.CachePadding)
	c.cells = make([]cacheCell, cacheSize)

Jesse Gross's avatar
Jesse Gross committed
180
181
182
	c.DType = dtype
	c.cellRanges = make(map[int]cellRange)
	c.backend = backend
183
	c.maxBatch = maxBatch
Jesse Gross's avatar
Jesse Gross committed
184
185
}

186
187
188
189
190
191
192
193
func (c *Causal) SetConfig(config ml.CacheConfig) {
	if c.config != nil {
		panic("config cannot be changed after being previously set, either by the model or backend")
	}

	c.config = &config
}

Jesse Gross's avatar
Jesse Gross committed
194
func (c *Causal) Close() {
195
196
197
	for _, ctx := range c.ctxs {
		ctx.Close()
	}
Jesse Gross's avatar
Jesse Gross committed
198
199
}

200
func (c *Causal) StartForward(ctx ml.Context, batch input.Batch, reserve bool) error {
201
	c.curReserve = reserve
Jesse Gross's avatar
Jesse Gross committed
202
203
204
	c.curBatchSize = len(batch.Positions)
	c.curSequences = batch.Sequences
	c.curPositions = batch.Positions
205
	c.opts.Except = nil
Jesse Gross's avatar
Jesse Gross committed
206

207
	if !c.curReserve {
208
		c.updateSlidingWindow()
209

210
		var err error
Jesse Gross's avatar
Jesse Gross committed
211
		c.curLoc, err = c.findStartLoc()
212
213
214
		if errors.Is(err, ErrKvCacheFull) {
			c.defrag()
			c.curLoc, err = c.findStartLoc()
Jesse Gross's avatar
Jesse Gross committed
215
		}
216
		if err != nil {
217
			slog.Warn("unable to find a kv cache slot", "cache", c)
218
			return err
Jesse Gross's avatar
Jesse Gross committed
219
220
		}

221
222
223
224
225
226
227
228
229
230
		for i, pos := range batch.Positions {
			seq := batch.Sequences[i]

			c.cells[c.curLoc+i] = cacheCell{pos: pos, sequences: []int{seq}}

			seqRange, ok := c.cellRanges[seq]
			if !ok {
				seqRange = newRange()
			}

231
232
233
234
235
			seqRange.min = min(seqRange.min, c.curLoc+i)
			c.curCellRange.min = min(c.curCellRange.min, c.curLoc+i)

			seqRange.max = max(seqRange.max, c.curLoc+i)
			c.curCellRange.max = max(c.curCellRange.max, c.curLoc+i)
236
237

			c.cellRanges[seq] = seqRange
Jesse Gross's avatar
Jesse Gross committed
238
		}
239
240
241
242
243
244
	} else {
		// If we are reserving memory, don't update any of the cache metadata but set the size
		// to the worst case.
		c.curLoc = 0
		c.curCellRange.min = 0
		c.curCellRange.max = len(c.cells) - 1
Jesse Gross's avatar
Jesse Gross committed
245
246
	}

247
	c.curMask = c.buildMask(ctx)
Jesse Gross's avatar
Jesse Gross committed
248

249
	return nil
Jesse Gross's avatar
Jesse Gross committed
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
}

func newRange() cellRange {
	return cellRange{
		min: math.MaxInt,
		max: 0,
	}
}

// Find the first contiguous block of at least curBatchSize
func (c *Causal) findStartLoc() (int, error) {
	var start, count int
	for i := range c.cells {
		if len(c.cells[i].sequences) == 0 {
			count++
			if count >= c.curBatchSize {
				return start, nil
			}
		} else {
			start = i + 1
			count = 0
		}
	}

274
	return 0, fmt.Errorf("%w (cache: %v batch: %v)", ErrKvCacheFull, len(c.cells), c.curBatchSize)
Jesse Gross's avatar
Jesse Gross committed
275
276
}

277
func (c *Causal) updateSlidingWindow() {
278
279
280
281
282
283
284
285
286
287
	c.curCellRange = newRange()

	if c.swaMemorySize == math.MaxInt32 {
		for _, seq := range c.curSequences {
			if seqRange, ok := c.cellRanges[seq]; ok {
				c.curCellRange.min = min(c.curCellRange.min, seqRange.min)
				c.curCellRange.max = max(c.curCellRange.max, seqRange.max)
			}
		}

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
		return
	}

	// create a map of unique sequences to the lowest position in that sequence
	lowestPos := make(map[int]int32)
	for i := range c.curPositions {
		seq := c.curSequences[i]

		pos, ok := lowestPos[seq]
		if !ok {
			pos = c.curPositions[i]
		} else if c.curPositions[i] < pos {
			pos = c.curPositions[i]
		}

		lowestPos[seq] = pos
	}

	// delete any entries that are beyond the window of the oldest position in the sequence
	for seq, pos := range lowestPos {
		oldRange, ok := c.cellRanges[seq]
		if !ok {
			continue
		}

		newRange := newRange()

		for i := oldRange.min; i <= oldRange.max; i++ {
			if slices.Contains(c.cells[i].sequences, seq) {
317
				if c.cells[i].pos < pos-c.swaMemorySize {
318
319
320
321
322
					c.cells[i].sequences = slices.DeleteFunc(c.cells[i].sequences, func(s int) bool { return s == seq })
				} else {
					newRange.min = min(newRange.min, i)
					newRange.max = max(newRange.max, i)
				}
323
324
325
326
				if c.cells[i].pos >= pos-c.swaWindowSize {
					c.curCellRange.min = min(c.curCellRange.min, i)
					c.curCellRange.max = max(c.curCellRange.max, i)
				}
327
328
329
330
331
332
333
			}
		}

		c.cellRanges[seq] = newRange
	}
}

334
335
336
337
338
339
340
341
func roundDown(length, pad int) int {
	return (length / pad) * pad
}

func roundUp(length, pad int) int {
	return ((length + pad - 1) / pad) * pad
}

Jesse Gross's avatar
Jesse Gross committed
342
343
344
// Builds a mask of history x batch indicating whether for each token in the batch the
// token in the history should apply. This is based on both the sequence and causality (the
// position of the history is not ahead of the token in the batch).
345
func (c *Causal) buildMask(ctx ml.Context) ml.Tensor {
346
347
348
	// Align and pad the two dimensions as required by the backend
	batchSize := roundUp(c.curBatchSize, c.config.MaskBatchPadding)

349
350
351
352
	c.curCellRange.min = roundDown(c.curCellRange.min, c.config.CachePadding)
	c.curCellRange.max = roundUp(c.curCellRange.max+1, c.config.CachePadding) - 1

	length := c.curCellRange.max - c.curCellRange.min + 1
353
354
355
356
357

	if c.curReserve {
		return ctx.Input().Empty(c.config.MaskDType, length, batchSize)
	}

358
	mask := make([]float32, batchSize*length)
Jesse Gross's avatar
Jesse Gross committed
359
360

	for i := range c.curBatchSize {
361
		enabled := !slices.Contains(c.opts.Except, i)
Jesse Gross's avatar
Jesse Gross committed
362
		for j := c.curCellRange.min; j <= c.curCellRange.max; j++ {
363
			if !slices.Contains(c.cells[j].sequences, c.curSequences[i]) ||
364
				(enabled && c.cells[j].pos > c.curPositions[i]) ||
Michael Yang's avatar
Michael Yang committed
365
				c.chunkSize > 0 && c.cells[j].pos < c.curPositions[i]-c.curPositions[i]%c.chunkSize ||
366
				c.cells[j].pos < c.curPositions[i]-c.swaWindowSize {
367
				mask[i*length+(j-c.curCellRange.min)] = float32(math.Inf(-1))
Jesse Gross's avatar
Jesse Gross committed
368
369
370
371
			}
		}
	}

372
373
374
375
376
377
	// Mask out any padding tokens we added. For padding that we added to the cache history, this
	// has already been masked out because the sequence doesn't match.
	for i := c.curBatchSize * length; i < len(mask); i++ {
		mask[i] = float32(math.Inf(-1))
	}

378
	maskTensor := ctx.Input().FromFloatSlice(mask, length, batchSize)
379
380

	if c.config.MaskDType != ml.DTypeF32 {
381
		out := ctx.Input().Empty(c.config.MaskDType, maskTensor.Shape()...)
382
383
384
385
		ctx.Forward(maskTensor.Copy(ctx, out))
		maskTensor = out
	}

386
	return maskTensor
Jesse Gross's avatar
Jesse Gross committed
387
388
}

389
func (c *Causal) moveCells(ctx ml.Context, src, dst, length int) {
390
391
	for i, key := range c.keys {
		if key == nil {
Jesse Gross's avatar
Jesse Gross committed
392
393
394
			continue
		}

395
396
397
398
		kHeadDim := key.Dim(0)
		numKVHeads := key.Dim(1)
		rowSize := key.Stride(2)

399
400
		kSrcView := key.View(ctx, rowSize*src, kHeadDim*numKVHeads*length)
		kDstView := key.View(ctx, rowSize*dst, kHeadDim*numKVHeads*length)
401
402
403
404
405
406
407

		value := c.values[i]
		var vSrcView, vDstView ml.Tensor
		if c.config.PermutedV {
			vHeadDim := value.Dim(1)
			elemSize := value.Stride(0)

408
409
			vSrcView = value.View(ctx, elemSize*src, length, len(c.cells)*elemSize, vHeadDim*numKVHeads)
			vDstView = value.View(ctx, elemSize*dst, length, len(c.cells)*elemSize, vHeadDim*numKVHeads)
410
411
412
		} else {
			vHeadDim := value.Dim(0)
			rowSize := value.Stride(2)
Jesse Gross's avatar
Jesse Gross committed
413

414
415
			vSrcView = value.View(ctx, rowSize*src, vHeadDim*numKVHeads*length)
			vDstView = value.View(ctx, rowSize*dst, vHeadDim*numKVHeads*length)
416
417
418
419
420
421
		}

		ctx.Forward(
			kSrcView.Copy(ctx, kDstView),
			vSrcView.Copy(ctx, vDstView),
		)
Jesse Gross's avatar
Jesse Gross committed
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
	}
}

func (c *Causal) defrag() {
	slog.Debug("defragmenting kv cache")

	// Defrag strategy:
	// - Search for empty holes at the beginning of the cache,
	//   filling them with active data starting at the end
	// - If there are contiguous elements that need to be moved,
	//   combine them into a single operation by holding new moves
	//   until we see that the next one is non-contiguous
	// - Fill up the context with the maximum number of operations it
	//   can hold then compute that and continue with a new context
	//
	// We could try to optimize placement by grouping blocks from
	// the same sequences together but most likely the next forward
	// pass will disrupt this anyways, so the real world benefit
	// seems limited as this time.

	ctx := c.backend.NewContext()

	// For every move, 6 tensors are required per layer (2 views and a
445
446
	// copy for each of k and v). We also need to refer to the original
	// k and v cache tensors - once per layer, not per move.
Jesse Gross's avatar
Jesse Gross committed
447
448
449
450
451
452
453
454
	layers := 0
	for _, key := range c.keys {
		if key == nil {
			continue
		}
		layers++
	}

455
	maxMoves := (ctx.MaxGraphNodes() - 2*layers) / (6 * layers)
Jesse Gross's avatar
Jesse Gross committed
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
	moves := 0

	var pendingSrc, pendingDst, pendingLen int
	src := len(c.cells) - 1

	for dst := 0; dst < src; dst++ {
		if len(c.cells[dst].sequences) == 0 {
			for ; src > dst; src-- {
				if len(c.cells[src].sequences) != 0 {
					c.cells[dst] = c.cells[src]
					c.cells[src] = cacheCell{}

					if pendingLen > 0 {
						if src == pendingSrc-pendingLen && dst == pendingDst+pendingLen {
							pendingSrc = src
							pendingLen++
							break
						} else {
474
							c.moveCells(ctx, pendingSrc, pendingDst, pendingLen)
Jesse Gross's avatar
Jesse Gross committed
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
							moves++
						}
					}

					pendingSrc = src
					pendingDst = dst
					pendingLen = 1

					break
				}
			}
		}

		if moves >= maxMoves {
			ctx.Compute()
			ctx.Close()
			ctx = c.backend.NewContext()

			moves = 0
		}
	}

	if pendingLen > 0 {
498
		c.moveCells(ctx, pendingSrc, pendingDst, pendingLen)
Jesse Gross's avatar
Jesse Gross committed
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
		moves++
	}

	if moves > 0 {
		ctx.Compute()
	}
	ctx.Close()

	// Reset range metadata
	for seq := range c.cellRanges {
		seqRange := newRange()

		for i, cell := range c.cells {
			if slices.Contains(cell.sequences, seq) {
				if i < seqRange.min {
					seqRange.min = i
				}
				if i > seqRange.max {
					seqRange.max = i
				}
			}
		}

		c.cellRanges[seq] = seqRange
	}
524
525

	c.updateSlidingWindow()
Jesse Gross's avatar
Jesse Gross committed
526
527
528
529
530
531
}

func (c *Causal) SetLayer(layer int) {
	c.curLayer = layer
}

532
type CausalOptions struct {
533
534
	// Enabled controls whether the causal mask is generated for a particular index in a batch
	Except []int
535
536
}

537
538
// SetCausal disables causal mask generation for a particular range of indicies in
// the current batch for subsequent calls to Get. The state resets for the next forward pass.
539
540
541
func (c *Causal) SetCausal(ctx ml.Context, opts CausalOptions) {
	if !slices.Equal(c.opts.Except, opts.Except) {
		c.opts = opts
542
		if ctx != nil {
543
			c.curMask = c.buildMask(ctx)
544
545
546
547
		}
	}
}

Jesse Gross's avatar
Jesse Gross committed
548
549
550
551
func (c *Causal) Get(ctx ml.Context) (ml.Tensor, ml.Tensor, ml.Tensor) {
	key := c.keys[c.curLayer]
	value := c.values[c.curLayer]

552
553
554
555
	kHeadDim := key.Dim(0)
	numKVHeads := key.Dim(1)
	rowSize := key.Stride(2)
	cachedSize := c.curMask.Dim(0)
Jesse Gross's avatar
Jesse Gross committed
556

557
558
559
560
	key = key.View(ctx, rowSize*c.curCellRange.min,
		kHeadDim, key.Stride(1),
		numKVHeads, key.Stride(2),
		cachedSize,
Jesse Gross's avatar
Jesse Gross committed
561
562
	)

563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
	if c.config.PermutedV {
		vHeadDim := value.Dim(1)
		elemSize := value.Stride(0)

		value = value.View(ctx, elemSize*c.curCellRange.min,
			cachedSize, value.Stride(1),
			vHeadDim, value.Stride(2),
			numKVHeads,
		)
	} else {
		vHeadDim := value.Dim(0)
		rowSize := value.Stride(2)

		value = value.View(ctx, rowSize*c.curCellRange.min,
			vHeadDim, value.Stride(1),
			numKVHeads, value.Stride(2),
			cachedSize,
		)
	}

Jesse Gross's avatar
Jesse Gross committed
583
584
585
586
	return key, value, c.curMask
}

func (c *Causal) Put(ctx ml.Context, key, value ml.Tensor) {
587
588
589
590
591
592
593
	kHeadDim := key.Dim(0)
	vHeadDim := value.Dim(0)
	numKVHeads := key.Dim(1)
	batchSize := key.Dim(2)

	if c.curBatchSize != batchSize {
		panic(fmt.Errorf("inconsistent batch sizes (layer: %v, batch size: %v layer batch size: %v)", c.curLayer, c.curBatchSize, batchSize))
Jesse Gross's avatar
Jesse Gross committed
594
595
	}

596
	if _, ok := c.ctxs[c.curLayer]; !ok {
597
		c.ctxs[c.curLayer] = c.backend.NewContextSize(2).Layer(c.curLayer)
598
599
600
	}

	if _, ok := c.keys[c.curLayer]; !ok {
601
		c.keys[c.curLayer] = c.ctxs[c.curLayer].Zeros(c.DType, kHeadDim, numKVHeads, len(c.cells))
602
	}
603

604
	if _, ok := c.values[c.curLayer]; !ok {
605
		if c.config.PermutedV {
606
			c.values[c.curLayer] = c.ctxs[c.curLayer].Zeros(c.DType, len(c.cells), vHeadDim, numKVHeads)
607
		} else {
608
			c.values[c.curLayer] = c.ctxs[c.curLayer].Zeros(c.DType, vHeadDim, numKVHeads, len(c.cells))
609
		}
Jesse Gross's avatar
Jesse Gross committed
610
611
	}

612
613
614
615
616
617
618
	rowSize := c.keys[c.curLayer].Stride(2)
	ctx.Forward(key.Copy(ctx, c.keys[c.curLayer].View(ctx, rowSize*c.curLoc, kHeadDim*numKVHeads*batchSize)))

	if c.config.PermutedV {
		elemSize := c.values[c.curLayer].Stride(0)

		value = value.Permute(ctx, 1, 2, 0, 3)
619
		ctx.Forward(value.Copy(ctx, c.values[c.curLayer].View(ctx, elemSize*c.curLoc, batchSize, len(c.cells)*elemSize, vHeadDim*numKVHeads)))
620
621
622
623
624
	} else {
		rowSize := c.values[c.curLayer].Stride(2)

		ctx.Forward(value.Copy(ctx, c.values[c.curLayer].View(ctx, rowSize*c.curLoc, vHeadDim*numKVHeads*batchSize)))
	}
Jesse Gross's avatar
Jesse Gross committed
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
}

func (c *Causal) CopyPrefix(srcSeq, dstSeq int, len int32) {
	seqRange := newRange()

	for i := range c.cells {
		// Remove the contents of dstSeq so that we only have the copied prefix, metadata will be reset at the end
		if slices.Contains(c.cells[i].sequences, dstSeq) {
			c.cells[i].sequences = slices.DeleteFunc(c.cells[i].sequences, func(s int) bool { return s == dstSeq })
		}

		if slices.Contains(c.cells[i].sequences, srcSeq) && c.cells[i].pos < len {
			c.cells[i].sequences = append(c.cells[i].sequences, dstSeq)
			if i < seqRange.min {
				seqRange.min = i
			}
			if i > seqRange.max {
				seqRange.max = i
			}
		}
	}

	c.cellRanges[dstSeq] = seqRange
}

650
func (c *Causal) CanResume(seq int, pos int32) bool {
651
	if c.swaMemorySize == math.MaxInt32 {
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
		return true
	}

	seqRange, ok := c.cellRanges[seq]
	if !ok {
		return false
	}

	// for sliding window, check that the window of the new sequence is contained in
	// the window of what we are storing
	var last int32 = -1
	for i := seqRange.min; i <= seqRange.max; i++ {
		if slices.Contains(c.cells[i].sequences, seq) {
			last = max(last, c.cells[i].pos)
		}
	}

	if last == -1 {
		return false
	}

673
674
	lastWindowStart := max(0, last-c.swaMemorySize)
	posWindowStart := max(0, pos-c.swaWindowSize)
675
676
677
678

	return posWindowStart >= lastWindowStart
}

Jesse Gross's avatar
Jesse Gross committed
679
680
681
682
683
684
685
func (c *Causal) shift(seq int, beginIndex, offset int32) error {
	if c.shiftFn == nil {
		return ErrNotSupported
	}

	seqRange := c.cellRanges[seq]

686
687
688
	for start := seqRange.min; start <= seqRange.max; start += c.maxBatch {
		size := min(seqRange.max-start+1, c.maxBatch)
		offsets := make([]int32, size)
689
690
691
692

		var batchFirst, batchLast int

		batchFirst = -1
693
694
695
696
697
		for i := range offsets {
			cell := c.cells[start+i]

			if slices.Contains(cell.sequences, seq) && cell.pos >= beginIndex {
				offsets[i] = offset
698
699
700
701
				if batchFirst < 0 {
					batchFirst = i
				}
				batchLast = i
702
			}
Jesse Gross's avatar
Jesse Gross committed
703
704
		}

705
706
707
708
709
710
711
		if batchFirst < 0 {
			continue
		}

		offsets = offsets[batchFirst : batchLast+1]

		ctx := c.backend.NewContext()
712
		kShift := ctx.Input().FromIntSlice(offsets, len(offsets))
Jesse Gross's avatar
Jesse Gross committed
713

714
715
716
717
		for i, key := range c.keys {
			if key == nil {
				continue
			}
Jesse Gross's avatar
Jesse Gross committed
718

719
720
721
			kHeadDim := key.Dim(0)
			numKVHeads := key.Dim(1)
			rowSize := key.Stride(2)
722

723
			key = key.View(ctx, rowSize*(start+batchFirst),
724
725
				kHeadDim, key.Stride(1),
				numKVHeads, key.Stride(2),
726
				len(offsets),
727
			)
Jesse Gross's avatar
Jesse Gross committed
728

729
730
731
732
733
734
735
			roped, err := c.shiftFn(ctx, i, key, kShift)
			if err != nil {
				ctx.Close()
				return err
			}

			ctx.Forward(roped.Copy(ctx, key))
Jesse Gross's avatar
Jesse Gross committed
736
737
		}

738
739
		ctx.Compute()
		ctx.Close()
Jesse Gross's avatar
Jesse Gross committed
740
741
742
743
744
745
	}

	return nil
}

func (c *Causal) Remove(seq int, beginIndex, endIndex int32) error {
746
747
748
749
750
751
	// TODO(jessegross): We should check to see if removing the middle of the sequence will
	// cause the sliding window to encompass tokens that we no longer have. If so, then we
	// should return an error, which will trigger the runner to evaluate the full history and
	// rebuild the window. However, if we have multimodal inputs in our history, this reuse
	// results in use after free, so we don't do it for now.

Jesse Gross's avatar
Jesse Gross committed
752
753
754
755
756
757
758
759
760
761
762
763
764
765
	var offset int32
	if endIndex != math.MaxInt32 {
		offset = beginIndex - endIndex
	}

	seqRange := newRange()

	for i := range c.cells {
		if slices.Contains(c.cells[i].sequences, seq) {
			if c.cells[i].pos >= beginIndex && c.cells[i].pos < endIndex {
				c.cells[i].sequences = slices.DeleteFunc(c.cells[i].sequences, func(s int) bool { return s == seq })
			} else {
				if c.cells[i].pos >= endIndex {
					if slices.ContainsFunc(c.cells[i].sequences, func(s int) bool { return s != seq }) {
766
						return errors.New("shifting cells shared by multiple sequences not supported")
Jesse Gross's avatar
Jesse Gross committed
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
					}

					c.cells[i].pos += offset
				}
				if i < seqRange.min {
					seqRange.min = i
				}
				if i > seqRange.max {
					seqRange.max = i
				}
			}
		}
	}

	if seqRange == newRange() {
		delete(c.cellRanges, seq)
		return nil
	}

	c.cellRanges[seq] = seqRange

	if endIndex != math.MaxInt32 {
		err := c.shift(seq, endIndex+offset, offset)
		if err != nil {
			return err
		}
	}

	return nil
}