memory.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. package llm
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "os"
  6. "strconv"
  7. "strings"
  8. "github.com/ollama/ollama/api"
  9. "github.com/ollama/ollama/format"
  10. "github.com/ollama/ollama/gpu"
  11. )
  12. // This algorithm looks for a complete fit to determine if we need to unload other models
  13. func PredictServerFit(allGpus gpu.GpuInfoList, ggml *GGML, adapters, projectors []string, opts api.Options) (bool, uint64) {
  14. var estimatedVRAM uint64
  15. if opts.NumCtx > int(ggml.KV().ContextLength()) {
  16. slog.Warn("requested context length is greater than model max context length", "requested", opts.NumCtx, "model", ggml.KV().ContextLength())
  17. opts.NumCtx = int(ggml.KV().ContextLength())
  18. }
  19. if opts.NumCtx < 4 {
  20. opts.NumCtx = 4
  21. }
  22. // Split up the GPUs by type and try them
  23. for _, gpus := range allGpus.ByLibrary() {
  24. var layerCount int
  25. layerCount, estimatedVRAM = EstimateGPULayers(gpus, ggml, projectors, opts)
  26. if opts.NumGPU < 0 {
  27. if layerCount > 0 && layerCount >= int(ggml.KV().BlockCount()+1) {
  28. return true, estimatedVRAM
  29. }
  30. } else {
  31. if layerCount > 0 && layerCount >= opts.NumGPU {
  32. return true, estimatedVRAM
  33. }
  34. }
  35. }
  36. return false, estimatedVRAM
  37. }
  38. // Given a model and one or more GPU targets, predict how many layers and bytes we can load
  39. // The GPUs provided must all be the same Library
  40. func EstimateGPULayers(gpus []gpu.GpuInfo, ggml *GGML, projectors []string, opts api.Options) (int, uint64) {
  41. if gpus[0].Library == "cpu" {
  42. return 0, 0
  43. }
  44. var memoryAvailable uint64
  45. for _, info := range gpus {
  46. memoryAvailable += info.FreeMemory
  47. }
  48. userLimit := os.Getenv("OLLAMA_MAX_VRAM")
  49. if userLimit != "" {
  50. avail, err := strconv.ParseUint(userLimit, 10, 64)
  51. if err != nil {
  52. slog.Error("invalid setting, ignoring", "OLLAMA_MAX_VRAM", userLimit, "error", err)
  53. } else {
  54. slog.Info("user override memory limit", "OLLAMA_MAX_VRAM", avail, "actual", memoryAvailable)
  55. memoryAvailable = avail
  56. }
  57. }
  58. slog.Debug("evaluating", "library", gpus[0].Library, "gpu_count", len(gpus), "available", format.HumanBytes2(memoryAvailable))
  59. // TODO - this is probably wrong, first GPU vs secondaries will have different overheads
  60. memoryMinimum := gpus[0].MinimumMemory
  61. for _, projector := range projectors {
  62. memoryMinimum += projectorMemoryRequirements(projector)
  63. // multimodal models require at least 2048 context
  64. opts.NumCtx = max(opts.NumCtx, 2048)
  65. }
  66. // fp16 k,v = (1 (k) + 1 (v)) * sizeof(float16) * n_ctx * n_layer * n_embd / n_head * n_head_kv
  67. var kv uint64 = 2 * 2 * uint64(opts.NumCtx) * ggml.KV().BlockCount() * ggml.KV().EmbeddingLength() / ggml.KV().HeadCount() * ggml.KV().HeadCountKV()
  68. graphPartialOffload, graphFullOffload := ggml.GraphSize(uint64(opts.NumCtx), uint64(min(opts.NumCtx, opts.NumBatch)))
  69. if graphPartialOffload == 0 {
  70. graphPartialOffload = ggml.KV().GQA() * kv / 6
  71. }
  72. if graphFullOffload == 0 {
  73. graphFullOffload = graphPartialOffload
  74. }
  75. graphFullOffload *= uint64(len(gpus))
  76. graphPartialOffload *= uint64(len(gpus))
  77. // memoryRequiredTotal represents the memory required for full GPU offloading (all layers)
  78. memoryRequiredTotal := memoryMinimum + graphFullOffload
  79. // memoryRequiredPartial represents the memory required for partial GPU offloading (n > 0, n < layers)
  80. memoryRequiredPartial := memoryMinimum + graphPartialOffload
  81. if memoryRequiredPartial > memoryAvailable {
  82. slog.Debug("insufficient VRAM to load any model layers")
  83. return 0, 0
  84. }
  85. var layerCount int
  86. layers := ggml.Tensors().Layers()
  87. for i := 0; i < int(ggml.KV().BlockCount()); i++ {
  88. memoryLayer := layers[fmt.Sprintf("blk.%d", i)].size()
  89. // KV is proportional to the number of layers
  90. memoryLayer += kv / ggml.KV().BlockCount()
  91. memoryRequiredTotal += memoryLayer
  92. if memoryAvailable > memoryRequiredPartial+memoryLayer {
  93. memoryRequiredPartial += memoryLayer
  94. layerCount++
  95. }
  96. }
  97. var memoryLayerOutput uint64
  98. for k, v := range layers {
  99. if !strings.HasPrefix(k, "blk.") {
  100. memoryLayerOutput += v.size()
  101. }
  102. }
  103. memoryRequiredTotal += memoryLayerOutput
  104. if memoryAvailable > memoryRequiredTotal {
  105. layerCount = int(ggml.KV().BlockCount()) + 1
  106. memoryRequiredPartial = memoryRequiredTotal
  107. }
  108. memoryWeights := memoryRequiredTotal - memoryMinimum - graphFullOffload - kv
  109. slog.Info(
  110. "offload to gpu",
  111. slog.Group(
  112. "layers",
  113. // actual number of layers offloaded
  114. "real", opts.NumGPU,
  115. // estimated number of layers that can be offloaded
  116. "estimate", layerCount,
  117. ),
  118. slog.Group(
  119. "memory",
  120. // memory available for offloading
  121. "available", format.HumanBytes2(memoryAvailable),
  122. slog.Group(
  123. "required",
  124. // memory required for full offloading
  125. "full", format.HumanBytes2(memoryRequiredTotal),
  126. // memory required to offload layers.estimate layers
  127. "partial", format.HumanBytes2(memoryRequiredPartial),
  128. // memory of KV cache
  129. "kv", format.HumanBytes2(kv),
  130. ),
  131. slog.Group(
  132. "weights",
  133. // memory of the weights
  134. "total", format.HumanBytes2(memoryWeights),
  135. // memory of repeating layers
  136. "repeating", format.HumanBytes2(memoryWeights-memoryLayerOutput),
  137. // memory of non-repeating layers
  138. "nonrepeating", format.HumanBytes2(memoryLayerOutput),
  139. ),
  140. slog.Group(
  141. "graph",
  142. // memory of graph when fully offloaded
  143. "full", format.HumanBytes2(graphFullOffload),
  144. // memory of graph when not fully offloaded
  145. "partial", format.HumanBytes2(graphPartialOffload),
  146. ),
  147. ),
  148. )
  149. return layerCount, uint64(memoryRequiredPartial)
  150. }