cache.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. package ollamarunner
  2. import (
  3. "errors"
  4. "fmt"
  5. "log/slog"
  6. "math"
  7. "time"
  8. "github.com/ollama/ollama/kvcache"
  9. "github.com/ollama/ollama/ml"
  10. "github.com/ollama/ollama/model"
  11. "github.com/ollama/ollama/model/input"
  12. )
  13. type InputCache struct {
  14. // context window size (per slot)
  15. numCtx int32
  16. // does the cache store data or do we need to always send the full input?
  17. // note that when enabled is false the underlying cache may either be nil
  18. // or a non-nil dummy that doesn't actually store anything
  19. enabled bool
  20. // individual KV caches
  21. slots []InputCacheSlot
  22. // optimize cache eviction for multiple users
  23. multiUserCache bool
  24. cache kvcache.Cache
  25. }
  26. func NewInputCache(model model.Model, kvCacheType string, kvSize int32, numSlots int, batchSize int, multiUserCache bool) (*InputCache, error) {
  27. numCtx := kvSize / int32(numSlots)
  28. if numCtx < 1 {
  29. return nil, fmt.Errorf("must have at least one kv cache entry per parallel sequence (kv: %v parallel: %v)", kvSize, numSlots)
  30. }
  31. slots := make([]InputCacheSlot, numSlots)
  32. for i := range slots {
  33. slots[i] = InputCacheSlot{Id: i}
  34. }
  35. cache := model.Config().Cache
  36. if cache != nil {
  37. cache.Init(model.Backend(), kvCacheTypeFromStr(kvCacheType), numSlots, int(numCtx), batchSize)
  38. }
  39. return &InputCache{
  40. numCtx: numCtx,
  41. enabled: cache != nil,
  42. slots: slots,
  43. multiUserCache: multiUserCache,
  44. cache: cache,
  45. }, nil
  46. }
  47. func kvCacheTypeFromStr(s string) ml.DType {
  48. switch s {
  49. case "q8_0":
  50. return ml.DTypeQ80
  51. case "q4_0":
  52. return ml.DTypeQ40
  53. default:
  54. return ml.DTypeF16
  55. }
  56. }
  57. func (c *InputCache) Close() {
  58. c.cache.Close()
  59. }
  60. // Locking: Operations on InputCacheSlot (including finding one
  61. // through LoadCacheSlot) require a lock to be be held that serializes
  62. // these operations with each other and processBatch
  63. type InputCacheSlot struct {
  64. // Index in the KV cache
  65. Id int
  66. // Inputs that are stored in the KV cache
  67. Inputs []input.Input
  68. // is this cache actively being processed as part of a sequence?
  69. InUse bool
  70. // last time this cache was used (as of start of processing)
  71. lastUsed time.Time
  72. }
  73. func (c *InputCache) LoadCacheSlot(prompt []input.Input) (*InputCacheSlot, []input.Input, error) {
  74. var slot *InputCacheSlot
  75. var numPast int32
  76. var err error
  77. // In single-user scenarios, the longest cache slot works fine for getting good input
  78. // cache hit rates and it keeps the footprint of the cache small, which improves throughput.
  79. // For multiple users, the "best" cache slot produces better input cache hit rates
  80. // at the cost of worse performance when we miss the input cache.
  81. if !c.multiUserCache {
  82. slot, numPast, err = c.findLongestCacheSlot(prompt)
  83. } else {
  84. slot, numPast, err = c.findBestCacheSlot(prompt)
  85. }
  86. if err != nil {
  87. return nil, nil, err
  88. }
  89. slot.InUse = true
  90. slot.lastUsed = time.Now()
  91. if numPast == int32(len(prompt)) {
  92. // Leave one input to sample so we can get a response
  93. numPast--
  94. }
  95. if c.cache != nil {
  96. err = c.cache.Remove(slot.Id, numPast, math.MaxInt32)
  97. if err != nil {
  98. // Some models don't support partial erasure
  99. err = c.cache.Remove(slot.Id, 0, math.MaxInt32)
  100. if err != nil {
  101. return nil, nil, err
  102. }
  103. numPast = 0
  104. }
  105. }
  106. slog.Debug("loading cache slot", "id", slot.Id, "cache", len(slot.Inputs), "prompt", len(prompt),
  107. "used", numPast, "remaining", int32(len(prompt))-numPast)
  108. prompt = prompt[numPast:]
  109. slot.Inputs = slot.Inputs[:numPast]
  110. return slot, prompt, nil
  111. }
  112. func (c *InputCache) findLongestCacheSlot(prompt []input.Input) (*InputCacheSlot, int32, error) {
  113. longest := int32(-1)
  114. var longestSlot *InputCacheSlot
  115. for i, s := range c.slots {
  116. if s.InUse {
  117. continue
  118. }
  119. count := countCommonPrefix(s.Inputs, prompt)
  120. if count > longest {
  121. longest = count
  122. longestSlot = &c.slots[i]
  123. }
  124. }
  125. if longestSlot == nil {
  126. return nil, 0, errors.New("no available cache slots")
  127. }
  128. return longestSlot, longest, nil
  129. }
  130. func (c *InputCache) findBestCacheSlot(prompt []input.Input) (*InputCacheSlot, int32, error) {
  131. oldest := time.Now()
  132. var oldestSlot *InputCacheSlot
  133. longest := int32(-1)
  134. var longestSlot *InputCacheSlot
  135. for i, s := range c.slots {
  136. count := countCommonPrefix(s.Inputs, prompt)
  137. if count > longest {
  138. longest = count
  139. longestSlot = &c.slots[i]
  140. }
  141. if s.lastUsed.Compare(oldest) < 0 && !s.InUse {
  142. oldest = s.lastUsed
  143. oldestSlot = &c.slots[i]
  144. }
  145. }
  146. if longest == int32(len(longestSlot.Inputs)) && !longestSlot.InUse {
  147. return longestSlot, longest, nil
  148. }
  149. if oldestSlot.InUse {
  150. return nil, 0, errors.New("no available cache slots")
  151. }
  152. if len(oldestSlot.Inputs) != 0 {
  153. slog.Debug("evicting cache slot", "id", oldestSlot.Id, "inputs", len(oldestSlot.Inputs),
  154. "used", oldestSlot.lastUsed)
  155. }
  156. if longest > 0 && longestSlot != oldestSlot {
  157. slog.Debug("forking cache slot", "src", longestSlot.Id, "dst", oldestSlot.Id, "inputs", longest, "total",
  158. len(longestSlot.Inputs))
  159. oldestSlot.Inputs = make([]input.Input, longest)
  160. copy(oldestSlot.Inputs, longestSlot.Inputs[:longest])
  161. if c.cache != nil {
  162. c.cache.CopyPrefix(longestSlot.Id, oldestSlot.Id, longest)
  163. }
  164. }
  165. return oldestSlot, longest, nil
  166. }
  167. func countCommonPrefix(a []input.Input, b []input.Input) int32 {
  168. var count int32
  169. for i := range a {
  170. if i >= len(b) {
  171. break
  172. }
  173. if a[i].Token != b[i].Token || a[i].MultimodalHash != b[i].MultimodalHash {
  174. break
  175. }
  176. count++
  177. }
  178. return count
  179. }
  180. func (c *InputCache) ShiftDiscard(inputLen int32, numKeep int32) int32 {
  181. targetFree := (c.numCtx - numKeep) / 2
  182. targetFree = max(targetFree, 1)
  183. currentFree := c.numCtx - inputLen
  184. discard := targetFree - currentFree
  185. if discard < 0 {
  186. discard = 0
  187. }
  188. return discard
  189. }
  190. // Frees up space in the KV cache by deleting the oldest half of history and shifting
  191. // the newest half into that space (saving numKeep inputs at the beginning).
  192. //
  193. // Assumes that at least 1 entry can be freed up by shifting (i.e. numKeep < numCtx)
  194. func (c *InputCache) ShiftCacheSlot(slot *InputCacheSlot, numKeep int32) error {
  195. if numKeep >= c.numCtx {
  196. return fmt.Errorf("unable to shift context - keep exceeds context (keep: %v context: %v)", numKeep, c.numCtx)
  197. }
  198. inputLen := int32(len(slot.Inputs))
  199. discard := c.ShiftDiscard(inputLen, numKeep)
  200. if discard <= 0 {
  201. return nil
  202. }
  203. slog.Debug("context limit hit - shifting", "id", slot.Id, "limit", c.numCtx, "input", len(slot.Inputs),
  204. "keep", numKeep, "discard", discard)
  205. // TODO (jessegross): KV cache removal can fail for certain types of models
  206. if c.cache != nil {
  207. err := c.cache.Remove(slot.Id, numKeep, numKeep+discard)
  208. if err != nil {
  209. return fmt.Errorf("unable to remove old kv cache entries (id: %v, keep: %v discard: %v): %w", slot.Id, numKeep, discard, err)
  210. }
  211. }
  212. for i := numKeep + discard; i < inputLen; i++ {
  213. slot.Inputs[i-discard] = slot.Inputs[i]
  214. }
  215. slot.Inputs = slot.Inputs[:inputLen-discard]
  216. return nil
  217. }