cache.go 6.8 KB

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