causal.go 14 KB

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