causal.go 13 KB

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