encoder.go 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. package kvcache
  2. import (
  3. "fmt"
  4. "github.com/ollama/ollama/ml"
  5. )
  6. // Encoder cache stores K and V tensors that are position independent
  7. //
  8. // The tensors can be of any shape and will be returned as they were stored
  9. // The mask is currently always nil
  10. //
  11. // Not currently safe for multiple sequences
  12. type EncoderCache struct {
  13. // config controls mostly backend-specific optimizations
  14. config *ml.CacheConfig
  15. // ** current forward pass **
  16. // the active layer for Get and Put
  17. curLayer int
  18. // if something is stored during this pass, this
  19. // will be the position (but there is no guarantee
  20. // anything will be stored)
  21. curPos int32
  22. // ** cache metadata **
  23. // was something stored in the cache?
  24. encoderCached bool
  25. // position of the cached data
  26. encoderPos int32
  27. // ** cache data storage **
  28. backend ml.Backend
  29. ctxs map[int]ml.Context
  30. keys, values map[int]ml.Tensor
  31. }
  32. func NewEncoderCache() *EncoderCache {
  33. return &EncoderCache{
  34. ctxs: make(map[int]ml.Context),
  35. keys: make(map[int]ml.Tensor),
  36. values: make(map[int]ml.Tensor),
  37. }
  38. }
  39. func (c *EncoderCache) Init(backend ml.Backend, dtype ml.DType, capacity int32) {
  40. if c.config == nil {
  41. var config ml.CacheConfig
  42. if cc, ok := backend.(ml.BackendCacheConfig); ok {
  43. config = cc.CacheConfig()
  44. }
  45. c.config = &config
  46. }
  47. if c.config.CachePadding != 0 && c.config.CachePadding != 1 {
  48. panic(fmt.Errorf("encoder cache is unable to enforce requested CachePadding (%v)", c.config.CachePadding))
  49. }
  50. c.backend = backend
  51. }
  52. func (c *EncoderCache) SetConfig(config ml.CacheConfig) {
  53. if c.config != nil {
  54. panic("config cannot be changed after being previously set, either by the model or backend")
  55. }
  56. c.config = &config
  57. }
  58. func (c *EncoderCache) Close() {
  59. for _, ctx := range c.ctxs {
  60. ctx.Close()
  61. }
  62. }
  63. func (c *EncoderCache) StartForward(ctx ml.Context, positions []int32, seqs []int) error {
  64. // The image is always in the first position
  65. c.curPos = positions[0]
  66. return nil
  67. }
  68. func (c *EncoderCache) SetLayer(layer int) {
  69. c.curLayer = layer
  70. }
  71. func (c *EncoderCache) EncoderCached() bool {
  72. return c.encoderCached
  73. }
  74. func (c *EncoderCache) Get(ctx ml.Context) (ml.Tensor, ml.Tensor, ml.Tensor) {
  75. return c.keys[c.curLayer], c.values[c.curLayer], nil
  76. }
  77. func (c *EncoderCache) Put(ctx ml.Context, key, value ml.Tensor) {
  78. c.encoderPos = c.curPos
  79. c.encoderCached = true
  80. if c.config.PermutedV {
  81. value = value.Permute(ctx, 1, 2, 0, 3)
  82. }
  83. if _, ok := c.ctxs[c.curLayer]; !ok {
  84. c.ctxs[c.curLayer] = c.backend.NewContextSize(2).Layer(c.curLayer)
  85. }
  86. if _, ok := c.keys[c.curLayer]; !ok {
  87. c.keys[c.curLayer] = c.ctxs[c.curLayer].Empty(key.DType(), key.Shape()...)
  88. }
  89. if _, ok := c.values[c.curLayer]; !ok {
  90. c.values[c.curLayer] = c.ctxs[c.curLayer].Empty(value.DType(), value.Shape()...)
  91. }
  92. ctx.Forward(
  93. key.Copy(ctx, c.keys[c.curLayer]),
  94. value.Copy(ctx, c.values[c.curLayer]),
  95. )
  96. }
  97. func (c *EncoderCache) CopyPrefix(srcSeq, dstSeq int, len int32) {
  98. panic("encoder cache does not support multiple sequences")
  99. }
  100. func (c *EncoderCache) Remove(seq int, beginIndex, endIndex int32) error {
  101. if c.encoderPos >= beginIndex && c.encoderPos < endIndex {
  102. c.encoderCached = false
  103. }
  104. return nil
  105. }