causal.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. package kvcache
  2. import (
  3. "errors"
  4. "fmt"
  5. "log/slog"
  6. "math"
  7. "slices"
  8. "github.com/ollama/ollama/ml"
  9. "github.com/ollama/ollama/model/input"
  10. )
  11. type shiftFn func(ctx ml.Context, layer int, key, shift ml.Tensor) (ml.Tensor, error)
  12. // Causal cache stores K and V tensors according to their position in the
  13. // sequence. Returns the history and a mask for attending to past tokens
  14. //
  15. // The tensors are of shape embed dim, kv heads, batch size
  16. // The mask is of shape history size, batch size
  17. type Causal struct {
  18. DType ml.DType
  19. Capacity int32
  20. causal bool
  21. windowSize int32
  22. // config controls mostly backend-specific optimizations
  23. config *ml.CacheConfig
  24. // ** current forward pass **
  25. // the active layer for Get and Put
  26. curLayer int
  27. // starting location for data storage for this batch
  28. curLoc int
  29. // size of the current batch
  30. curBatchSize int
  31. // mask of the cache as used by this batch
  32. curMask ml.Tensor
  33. // locations in the cache that are needed for this batch
  34. curCellRange cellRange
  35. // curSequences is the sequences corresponding to this pass's entries in the cache
  36. curSequences []int
  37. // curPositions is the positions corresponding to this pass's entries in the cache
  38. curPositions []int32
  39. // ** cache metadata **
  40. // for each possible location in the cache, stores the position and set of sequences
  41. // that reference the data there
  42. cells []cacheCell
  43. // maps from sequence to the range of locations where it is stored in the cache
  44. cellRanges map[int]cellRange
  45. // ** cache data storage **
  46. shiftFn shiftFn
  47. backend ml.Backend
  48. ctxs map[int]ml.Context
  49. keys, values map[int]ml.Tensor
  50. }
  51. type cacheCell struct {
  52. pos int32
  53. sequences []int
  54. }
  55. type cellRange struct {
  56. min int
  57. max int
  58. }
  59. func NewCausalCache(shift shiftFn) *Causal {
  60. return &Causal{
  61. causal: true,
  62. windowSize: math.MaxInt32,
  63. shiftFn: shift,
  64. ctxs: make(map[int]ml.Context),
  65. keys: make(map[int]ml.Tensor),
  66. values: make(map[int]ml.Tensor),
  67. }
  68. }
  69. func NewSWACache(windowSize int32, shift shiftFn) *Causal {
  70. return &Causal{
  71. causal: true,
  72. windowSize: windowSize,
  73. shiftFn: shift,
  74. ctxs: make(map[int]ml.Context),
  75. keys: make(map[int]ml.Tensor),
  76. values: make(map[int]ml.Tensor),
  77. }
  78. }
  79. func (c *Causal) Init(backend ml.Backend, dtype ml.DType, capacity int32) {
  80. if c.config == nil {
  81. var config ml.CacheConfig
  82. if cc, ok := backend.(ml.BackendCacheConfig); ok {
  83. config = cc.CacheConfig()
  84. }
  85. c.config = &config
  86. }
  87. if c.config.CachePadding == 0 {
  88. c.config.CachePadding = 1
  89. }
  90. if c.config.MaskBatchPadding == 0 {
  91. c.config.MaskBatchPadding = 1
  92. }
  93. if c.config.MaskDType == ml.DTypeOther {
  94. c.config.MaskDType = ml.DTypeF32
  95. }
  96. c.DType = dtype
  97. c.Capacity = int32(roundUp(int(capacity), c.config.CachePadding))
  98. c.cells = make([]cacheCell, c.Capacity)
  99. c.cellRanges = make(map[int]cellRange)
  100. c.backend = backend
  101. }
  102. func (c *Causal) SetConfig(config ml.CacheConfig) {
  103. if c.config != nil {
  104. panic("config cannot be changed after being previously set, either by the model or backend")
  105. }
  106. c.config = &config
  107. }
  108. func (c *Causal) Close() {
  109. for _, ctx := range c.ctxs {
  110. ctx.Close()
  111. }
  112. }
  113. func (c *Causal) StartForward(ctx ml.Context, opts input.Options) error {
  114. c.curBatchSize = len(opts.Positions)
  115. c.curSequences = opts.Sequences
  116. c.curPositions = opts.Positions
  117. var err error
  118. c.curLoc, err = c.findStartLoc()
  119. if errors.Is(err, ErrKvCacheFull) {
  120. c.defrag()
  121. c.curLoc, err = c.findStartLoc()
  122. }
  123. if err != nil {
  124. return err
  125. }
  126. c.curCellRange = newRange()
  127. for i, pos := range opts.Positions {
  128. seq := opts.Sequences[i]
  129. c.cells[c.curLoc+i] = cacheCell{pos: pos, sequences: []int{seq}}
  130. seqRange, ok := c.cellRanges[seq]
  131. if !ok {
  132. seqRange = newRange()
  133. }
  134. if c.curLoc+i > seqRange.max {
  135. seqRange.max = c.curLoc + i
  136. }
  137. if seqRange.max > c.curCellRange.max {
  138. c.curCellRange.max = seqRange.max
  139. }
  140. if c.curLoc+i < seqRange.min {
  141. seqRange.min = c.curLoc + i
  142. }
  143. if seqRange.min < c.curCellRange.min {
  144. c.curCellRange.min = seqRange.min
  145. }
  146. c.cellRanges[seq] = seqRange
  147. }
  148. c.curMask, err = c.buildMask(ctx)
  149. return err
  150. }
  151. func newRange() cellRange {
  152. return cellRange{
  153. min: math.MaxInt,
  154. max: 0,
  155. }
  156. }
  157. // Find the first contiguous block of at least curBatchSize
  158. func (c *Causal) findStartLoc() (int, error) {
  159. var start, count int
  160. for i := range c.cells {
  161. if len(c.cells[i].sequences) == 0 {
  162. count++
  163. if count >= c.curBatchSize {
  164. return start, nil
  165. }
  166. } else {
  167. start = i + 1
  168. count = 0
  169. }
  170. }
  171. return 0, fmt.Errorf("%w (length: %v)", ErrKvCacheFull, c.Capacity)
  172. }
  173. func roundDown(length, pad int) int {
  174. return (length / pad) * pad
  175. }
  176. func roundUp(length, pad int) int {
  177. return ((length + pad - 1) / pad) * pad
  178. }
  179. // Builds a mask of history x batch indicating whether for each token in the batch the
  180. // token in the history should apply. This is based on both the sequence and causality (the
  181. // position of the history is not ahead of the token in the batch).
  182. func (c *Causal) buildMask(ctx ml.Context) (ml.Tensor, error) {
  183. // Align and pad the two dimensions as required by the backend
  184. batchSize := roundUp(c.curBatchSize, c.config.MaskBatchPadding)
  185. c.curCellRange.min = roundDown(c.curCellRange.min, c.config.CachePadding)
  186. c.curCellRange.max = roundUp(c.curCellRange.max+1, c.config.CachePadding) - 1
  187. length := c.curCellRange.max - c.curCellRange.min + 1
  188. mask := make([]float32, batchSize*length)
  189. for i := range c.curBatchSize {
  190. for j := c.curCellRange.min; j <= c.curCellRange.max; j++ {
  191. if !slices.Contains(c.cells[j].sequences, c.curSequences[i]) ||
  192. (c.causal && c.cells[j].pos > c.curPositions[i]) ||
  193. c.cells[j].pos < c.curPositions[i]-c.windowSize {
  194. mask[i*length+(j-c.curCellRange.min)] = float32(math.Inf(-1))
  195. }
  196. }
  197. }
  198. // Mask out any padding tokens we added. For padding that we added to the cache history, this
  199. // has already been masked out because the sequence doesn't match.
  200. for i := c.curBatchSize * length; i < len(mask); i++ {
  201. mask[i] = float32(math.Inf(-1))
  202. }
  203. maskTensor, err := ctx.Input().FromFloatSlice(mask, length, batchSize)
  204. if err != nil {
  205. return nil, err
  206. }
  207. if c.config.MaskDType != ml.DTypeF32 {
  208. out := ctx.Input().Empty(c.config.MaskDType, maskTensor.Shape()...)
  209. ctx.Forward(maskTensor.Copy(ctx, out))
  210. maskTensor = out
  211. }
  212. return maskTensor, nil
  213. }
  214. func (c *Causal) moveCells(ctx ml.Context, src, dst, len int) {
  215. for i, key := range c.keys {
  216. if key == nil {
  217. continue
  218. }
  219. kHeadDim := key.Dim(0)
  220. numKVHeads := key.Dim(1)
  221. rowSize := key.Stride(2)
  222. kSrcView := key.View(ctx, rowSize*src, kHeadDim*numKVHeads*len)
  223. kDstView := key.View(ctx, rowSize*dst, kHeadDim*numKVHeads*len)
  224. value := c.values[i]
  225. var vSrcView, vDstView ml.Tensor
  226. if c.config.PermutedV {
  227. vHeadDim := value.Dim(1)
  228. elemSize := value.Stride(0)
  229. vSrcView = value.View(ctx, elemSize*src, len, int(c.Capacity)*elemSize, vHeadDim*numKVHeads)
  230. vDstView = value.View(ctx, elemSize*dst, len, int(c.Capacity)*elemSize, vHeadDim*numKVHeads)
  231. } else {
  232. vHeadDim := value.Dim(0)
  233. rowSize := value.Stride(2)
  234. vSrcView = value.View(ctx, rowSize*src, vHeadDim*numKVHeads*len)
  235. vDstView = value.View(ctx, rowSize*dst, vHeadDim*numKVHeads*len)
  236. }
  237. ctx.Forward(
  238. kSrcView.Copy(ctx, kDstView),
  239. vSrcView.Copy(ctx, vDstView),
  240. )
  241. }
  242. }
  243. func (c *Causal) defrag() {
  244. slog.Debug("defragmenting kv cache")
  245. // Defrag strategy:
  246. // - Search for empty holes at the beginning of the cache,
  247. // filling them with active data starting at the end
  248. // - If there are contiguous elements that need to be moved,
  249. // combine them into a single operation by holding new moves
  250. // until we see that the next one is non-contiguous
  251. // - Fill up the context with the maximum number of operations it
  252. // can hold then compute that and continue with a new context
  253. //
  254. // We could try to optimize placement by grouping blocks from
  255. // the same sequences together but most likely the next forward
  256. // pass will disrupt this anyways, so the real world benefit
  257. // seems limited as this time.
  258. ctx := c.backend.NewContext()
  259. // For every move, 6 tensors are required per layer (2 views and a
  260. // copy for each of k and v).
  261. layers := 0
  262. for _, key := range c.keys {
  263. if key == nil {
  264. continue
  265. }
  266. layers++
  267. }
  268. maxMoves := ctx.MaxGraphNodes() / (6 * layers)
  269. moves := 0
  270. var pendingSrc, pendingDst, pendingLen int
  271. src := len(c.cells) - 1
  272. for dst := 0; dst < src; dst++ {
  273. if len(c.cells[dst].sequences) == 0 {
  274. for ; src > dst; src-- {
  275. if len(c.cells[src].sequences) != 0 {
  276. c.cells[dst] = c.cells[src]
  277. c.cells[src] = cacheCell{}
  278. if pendingLen > 0 {
  279. if src == pendingSrc-pendingLen && dst == pendingDst+pendingLen {
  280. pendingSrc = src
  281. pendingLen++
  282. break
  283. } else {
  284. c.moveCells(ctx, pendingSrc, pendingDst, pendingLen)
  285. moves++
  286. }
  287. }
  288. pendingSrc = src
  289. pendingDst = dst
  290. pendingLen = 1
  291. break
  292. }
  293. }
  294. }
  295. if moves >= maxMoves {
  296. ctx.Compute()
  297. ctx.Close()
  298. ctx = c.backend.NewContext()
  299. moves = 0
  300. }
  301. }
  302. if pendingLen > 0 {
  303. c.moveCells(ctx, pendingSrc, pendingDst, pendingLen)
  304. moves++
  305. }
  306. if moves > 0 {
  307. ctx.Compute()
  308. }
  309. ctx.Close()
  310. // Reset range metadata
  311. for seq := range c.cellRanges {
  312. seqRange := newRange()
  313. for i, cell := range c.cells {
  314. if slices.Contains(cell.sequences, seq) {
  315. if i < seqRange.min {
  316. seqRange.min = i
  317. }
  318. if i > seqRange.max {
  319. seqRange.max = i
  320. }
  321. }
  322. }
  323. c.cellRanges[seq] = seqRange
  324. }
  325. }
  326. func (c *Causal) SetLayer(layer int) {
  327. c.curLayer = layer
  328. }
  329. // SetCausal enables or disables causal mask generation for subsequent calls to Get.
  330. // This state carries over to future forward passes. The default value is true.
  331. //
  332. // ctx may be set to nil if this is called from outside of a forward pass, for
  333. // example, when initializing the cache.
  334. func (c *Causal) SetCausal(ctx ml.Context, causal bool) {
  335. if c.causal != causal {
  336. c.causal = causal
  337. if ctx != nil {
  338. var err error
  339. c.curMask, err = c.buildMask(ctx)
  340. if err != nil {
  341. // This error should never occur because we have previously built a mask with the same shape
  342. panic(fmt.Errorf("SetCausal: %w", err))
  343. }
  344. }
  345. }
  346. }
  347. func (c *Causal) Get(ctx ml.Context) (ml.Tensor, ml.Tensor, ml.Tensor) {
  348. key := c.keys[c.curLayer]
  349. value := c.values[c.curLayer]
  350. kHeadDim := key.Dim(0)
  351. numKVHeads := key.Dim(1)
  352. rowSize := key.Stride(2)
  353. cachedSize := c.curMask.Dim(0)
  354. key = key.View(ctx, rowSize*c.curCellRange.min,
  355. kHeadDim, key.Stride(1),
  356. numKVHeads, key.Stride(2),
  357. cachedSize,
  358. )
  359. if c.config.PermutedV {
  360. vHeadDim := value.Dim(1)
  361. elemSize := value.Stride(0)
  362. value = value.View(ctx, elemSize*c.curCellRange.min,
  363. cachedSize, value.Stride(1),
  364. vHeadDim, value.Stride(2),
  365. numKVHeads,
  366. )
  367. } else {
  368. vHeadDim := value.Dim(0)
  369. rowSize := value.Stride(2)
  370. value = value.View(ctx, rowSize*c.curCellRange.min,
  371. vHeadDim, value.Stride(1),
  372. numKVHeads, value.Stride(2),
  373. cachedSize,
  374. )
  375. }
  376. return key, value, c.curMask
  377. }
  378. func (c *Causal) Put(ctx ml.Context, key, value ml.Tensor) {
  379. kHeadDim := key.Dim(0)
  380. vHeadDim := value.Dim(0)
  381. numKVHeads := key.Dim(1)
  382. batchSize := key.Dim(2)
  383. if c.curBatchSize != batchSize {
  384. panic(fmt.Errorf("inconsistent batch sizes (layer: %v, batch size: %v layer batch size: %v)", c.curLayer, c.curBatchSize, batchSize))
  385. }
  386. if _, ok := c.ctxs[c.curLayer]; !ok {
  387. c.ctxs[c.curLayer] = c.backend.NewContextSize(2).Layer(c.curLayer)
  388. }
  389. if _, ok := c.keys[c.curLayer]; !ok {
  390. c.keys[c.curLayer] = c.ctxs[c.curLayer].Zeros(c.DType, kHeadDim, numKVHeads, int(c.Capacity))
  391. }
  392. if _, ok := c.values[c.curLayer]; !ok {
  393. if c.config.PermutedV {
  394. c.values[c.curLayer] = c.ctxs[c.curLayer].Zeros(c.DType, int(c.Capacity), vHeadDim, numKVHeads)
  395. } else {
  396. c.values[c.curLayer] = c.ctxs[c.curLayer].Zeros(c.DType, vHeadDim, numKVHeads, int(c.Capacity))
  397. }
  398. }
  399. rowSize := c.keys[c.curLayer].Stride(2)
  400. ctx.Forward(key.Copy(ctx, c.keys[c.curLayer].View(ctx, rowSize*c.curLoc, kHeadDim*numKVHeads*batchSize)))
  401. if c.config.PermutedV {
  402. elemSize := c.values[c.curLayer].Stride(0)
  403. value = value.Permute(ctx, 1, 2, 0, 3)
  404. ctx.Forward(value.Copy(ctx, c.values[c.curLayer].View(ctx, elemSize*c.curLoc, batchSize, int(c.Capacity)*elemSize, vHeadDim*numKVHeads)))
  405. } else {
  406. rowSize := c.values[c.curLayer].Stride(2)
  407. ctx.Forward(value.Copy(ctx, c.values[c.curLayer].View(ctx, rowSize*c.curLoc, vHeadDim*numKVHeads*batchSize)))
  408. }
  409. }
  410. func (c *Causal) CopyPrefix(srcSeq, dstSeq int, len int32) {
  411. seqRange := newRange()
  412. for i := range c.cells {
  413. // Remove the contents of dstSeq so that we only have the copied prefix, metadata will be reset at the end
  414. if slices.Contains(c.cells[i].sequences, dstSeq) {
  415. c.cells[i].sequences = slices.DeleteFunc(c.cells[i].sequences, func(s int) bool { return s == dstSeq })
  416. }
  417. if slices.Contains(c.cells[i].sequences, srcSeq) && c.cells[i].pos < len {
  418. c.cells[i].sequences = append(c.cells[i].sequences, dstSeq)
  419. if i < seqRange.min {
  420. seqRange.min = i
  421. }
  422. if i > seqRange.max {
  423. seqRange.max = i
  424. }
  425. }
  426. }
  427. c.cellRanges[dstSeq] = seqRange
  428. }
  429. func (c *Causal) shift(seq int, beginIndex, offset int32) error {
  430. if c.shiftFn == nil {
  431. return ErrNotSupported
  432. }
  433. ctx := c.backend.NewContext()
  434. defer ctx.Close()
  435. seqRange := c.cellRanges[seq]
  436. size := seqRange.max - seqRange.min + 1
  437. offsets := make([]int32, size)
  438. for i := range offsets {
  439. cell := c.cells[seqRange.min+i]
  440. if slices.Contains(cell.sequences, seq) && cell.pos >= beginIndex {
  441. offsets[i] = offset
  442. }
  443. }
  444. kShift, err := ctx.Input().FromIntSlice(offsets, len(offsets))
  445. if err != nil {
  446. return err
  447. }
  448. for i, key := range c.keys {
  449. if key == nil {
  450. continue
  451. }
  452. kHeadDim := key.Dim(0)
  453. numKVHeads := key.Dim(1)
  454. rowSize := key.Stride(2)
  455. key = key.View(ctx, rowSize*seqRange.min,
  456. kHeadDim, key.Stride(1),
  457. numKVHeads, key.Stride(2),
  458. size,
  459. )
  460. roped, err := c.shiftFn(ctx, i, key, kShift)
  461. if err != nil {
  462. return err
  463. }
  464. ctx.Forward(roped.Copy(ctx, key))
  465. }
  466. ctx.Compute()
  467. return nil
  468. }
  469. func (c *Causal) Remove(seq int, beginIndex, endIndex int32) error {
  470. var offset int32
  471. if endIndex != math.MaxInt32 {
  472. offset = beginIndex - endIndex
  473. }
  474. seqRange := newRange()
  475. for i := range c.cells {
  476. if slices.Contains(c.cells[i].sequences, seq) {
  477. if c.cells[i].pos >= beginIndex && c.cells[i].pos < endIndex {
  478. c.cells[i].sequences = slices.DeleteFunc(c.cells[i].sequences, func(s int) bool { return s == seq })
  479. } else {
  480. if c.cells[i].pos >= endIndex {
  481. if slices.ContainsFunc(c.cells[i].sequences, func(s int) bool { return s != seq }) {
  482. // TODO(jessegross): Need to be careful about data shared between sequences
  483. return errors.New("shifting on cells shared by multiple sequences not yet implemented")
  484. }
  485. c.cells[i].pos += offset
  486. }
  487. if i < seqRange.min {
  488. seqRange.min = i
  489. }
  490. if i > seqRange.max {
  491. seqRange.max = i
  492. }
  493. }
  494. }
  495. }
  496. if seqRange == newRange() {
  497. delete(c.cellRanges, seq)
  498. return nil
  499. }
  500. c.cellRanges[seq] = seqRange
  501. if endIndex != math.MaxInt32 {
  502. err := c.shift(seq, endIndex+offset, offset)
  503. if err != nil {
  504. return err
  505. }
  506. }
  507. return nil
  508. }