memory.go 5.6 KB

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