memory.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. package llm
  2. import (
  3. "log/slog"
  4. "strconv"
  5. "strings"
  6. "github.com/ollama/ollama/api"
  7. "github.com/ollama/ollama/format"
  8. "github.com/ollama/ollama/gpu"
  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. // Split up the GPUs by type and try them
  13. var estimatedVRAM uint64
  14. for _, gpus := range allGpus.ByLibrary() {
  15. var layerCount int
  16. estimate := EstimateGPULayers(gpus, ggml, projectors, opts)
  17. layerCount, estimatedVRAM = estimate.Layers, estimate.VRAMSize
  18. if opts.NumGPU < 0 {
  19. if layerCount > 0 && layerCount >= int(ggml.KV().BlockCount()+1) {
  20. return true, estimatedVRAM
  21. }
  22. } else {
  23. if layerCount > 0 && layerCount >= opts.NumGPU {
  24. return true, estimatedVRAM
  25. }
  26. }
  27. }
  28. return false, estimatedVRAM
  29. }
  30. type MemoryEstimate struct {
  31. // How many layers we predict we can load
  32. Layers int
  33. // The size of the graph which occupies the main GPU
  34. Graph uint64
  35. // How much VRAM will be allocated given the number of layers we predict
  36. VRAMSize uint64
  37. // The total size of the model if loaded into VRAM. If all layers are loaded, VRAMSize == TotalSize
  38. TotalSize uint64
  39. // For multi-GPU scenarios, this provides the tensor split parameter
  40. TensorSplit string
  41. // For multi-GPU scenarios, this is the size in bytes per GPU
  42. GPUSizes []uint64
  43. }
  44. // Given a model and one or more GPU targets, predict how many layers and bytes we can load, and the total size
  45. // The GPUs provided must all be the same Library
  46. func EstimateGPULayers(gpus []gpu.GpuInfo, ggml *GGML, projectors []string, opts api.Options) MemoryEstimate {
  47. // Graph size for a partial offload, applies to all GPUs
  48. var graphPartialOffload uint64
  49. // Graph size when all layers are offloaded, applies to all GPUs
  50. var graphFullOffload uint64
  51. // Final graph offload once we know full or partial
  52. var graphOffload uint64
  53. // Projectors loaded into GPU0 only
  54. var projectorSize uint64
  55. // Conditional output size on GPU 0
  56. var memoryLayerOutput uint64
  57. // The sizes of a layer
  58. var layerSize uint64
  59. // The sum of all the layer sizes (just for logging)
  60. var memoryWeights uint64
  61. // True if all the layers are loaded
  62. var fullyLoaded bool
  63. // Overflow that didn't fit into the GPU
  64. var overflow uint64
  65. availableList := make([]string, len(gpus))
  66. for i, gpu := range gpus {
  67. availableList[i] = format.HumanBytes2(gpu.FreeMemory)
  68. }
  69. slog.Debug("evaluating", "library", gpus[0].Library, "gpu_count", len(gpus), "available", availableList)
  70. for _, projector := range projectors {
  71. projectorSize += projectorMemoryRequirements(projector)
  72. // multimodal models require at least 2048 context
  73. opts.NumCtx = max(opts.NumCtx, 2048)
  74. }
  75. layers := ggml.Tensors().Layers()
  76. // add one layer worth of memory as a buffer
  77. if blk0, ok := layers["blk.0"]; ok {
  78. layerSize = blk0.size()
  79. } else {
  80. slog.Warn("model missing blk.0 layer size")
  81. }
  82. // fp16 k,v = (1 (k) + 1 (v)) * sizeof(float16) * n_ctx * n_layer * n_embd / n_head * n_head_kv
  83. var kv uint64 = 2 * 2 * uint64(opts.NumCtx) * ggml.KV().BlockCount() * ggml.KV().EmbeddingLength() / ggml.KV().HeadCount() * ggml.KV().HeadCountKV()
  84. // KV is proportional to the number of layers
  85. layerSize += kv / ggml.KV().BlockCount()
  86. graphPartialOffload, graphFullOffload = ggml.GraphSize(uint64(opts.NumCtx), uint64(min(opts.NumCtx, opts.NumBatch)))
  87. if graphPartialOffload == 0 {
  88. graphPartialOffload = ggml.KV().GQA() * kv / 6
  89. }
  90. if graphFullOffload == 0 {
  91. graphFullOffload = graphPartialOffload
  92. }
  93. // on metal there's no partial offload overhead
  94. if gpus[0].Library == "metal" {
  95. graphPartialOffload = graphFullOffload
  96. } else if len(gpus) > 1 {
  97. // multigpu should always use the partial graph size
  98. graphFullOffload = graphPartialOffload
  99. }
  100. if layer, ok := layers["output_norm"]; ok {
  101. memoryLayerOutput += layer.size()
  102. }
  103. if layer, ok := layers["output"]; ok {
  104. memoryLayerOutput += layer.size()
  105. } else if layer, ok := layers["token_embd"]; ok {
  106. memoryLayerOutput += layer.size()
  107. }
  108. // Output layer handled at the end if we have space
  109. gpuZeroOverhead := projectorSize
  110. // Reduce set of GPUs to only those that have sufficient space to fit overhead and at least one layer
  111. var layerCount int
  112. layerCounts := make([]int, len(gpus))
  113. gpuAllocations := make([]uint64, len(gpus))
  114. type gs struct {
  115. i int
  116. g *gpu.GpuInfo
  117. }
  118. gpusWithSpace := []gs{}
  119. for i := range gpus {
  120. var gzo uint64
  121. if len(gpusWithSpace) == 0 {
  122. gzo = gpuZeroOverhead
  123. }
  124. // Only include GPUs that can fit the graph, gpu minimum, the layer buffer and at least more layer
  125. if gpus[i].FreeMemory < gzo+max(graphPartialOffload, graphFullOffload)+gpus[i].MinimumMemory+2*layerSize {
  126. slog.Debug("gpu has too little memory to allocate any layers", "gpu", gpus[i])
  127. continue
  128. }
  129. gpusWithSpace = append(gpusWithSpace, gs{i, &gpus[i]})
  130. gpuAllocations[i] += gpus[i].MinimumMemory + layerSize // We hold off on graph until we know partial vs. full
  131. }
  132. var gpuZeroID int
  133. if len(gpusWithSpace) > 0 {
  134. gpuZeroID = gpusWithSpace[0].i
  135. gpuAllocations[gpuZeroID] += gpuZeroOverhead
  136. }
  137. // For all the layers, find where they can fit on the GPU(s)
  138. for i := range int(ggml.KV().BlockCount()) {
  139. memoryWeights += layerSize
  140. if opts.NumGPU >= 0 && layerCount >= opts.NumGPU {
  141. // Stop allocating on GPU(s) once we hit the users target NumGPU
  142. continue
  143. }
  144. // distribute the layers across the GPU(s) that have space
  145. for j := len(gpusWithSpace); j > 0; j-- {
  146. g := gpusWithSpace[i%j]
  147. used := gpuAllocations[g.i] + max(graphPartialOffload, graphFullOffload)
  148. if g.g.FreeMemory > used+layerSize {
  149. gpuAllocations[g.i] += layerSize
  150. layerCounts[g.i]++
  151. layerCount++
  152. break
  153. } else {
  154. gpusWithSpace = append(gpusWithSpace[:i%j], gpusWithSpace[i%j+1:]...)
  155. }
  156. }
  157. }
  158. if layerCount >= int(ggml.KV().BlockCount()) {
  159. fullyLoaded = true
  160. } else {
  161. for i := layerCount; i < int(ggml.KV().BlockCount()); i++ {
  162. overflow += layerSize
  163. }
  164. }
  165. // Determine if we need to consider output then find where it fits
  166. if memoryLayerOutput > 0 && (opts.NumGPU < 0 || layerCount < opts.NumGPU) {
  167. for j := len(gpusWithSpace); j > 0; j-- {
  168. g := gpusWithSpace[layerCount%j]
  169. used := gpuAllocations[g.i] + max(graphPartialOffload, graphFullOffload)
  170. if g.g.FreeMemory > used+memoryLayerOutput {
  171. gpuAllocations[g.i] += memoryLayerOutput
  172. layerCounts[g.i]++
  173. layerCount++
  174. break
  175. }
  176. }
  177. if layerCount < int(ggml.KV().BlockCount())+1 {
  178. fullyLoaded = false
  179. overflow += memoryLayerOutput
  180. }
  181. }
  182. // Add the applicable (full or partial) graph allocations
  183. for i := range gpus {
  184. if layerCounts[i] <= 0 {
  185. continue
  186. }
  187. if fullyLoaded {
  188. gpuAllocations[i] += graphFullOffload
  189. } else {
  190. gpuAllocations[i] += graphPartialOffload
  191. }
  192. }
  193. if fullyLoaded {
  194. graphOffload = graphFullOffload
  195. } else {
  196. graphOffload = graphPartialOffload
  197. }
  198. // Summaries for the log
  199. var memoryRequiredPartial, memoryRequiredTotal uint64
  200. for i := range gpuAllocations {
  201. memoryRequiredPartial += gpuAllocations[i]
  202. }
  203. memoryRequiredTotal = memoryRequiredPartial + overflow
  204. tensorSplit := ""
  205. if len(gpus) > 1 {
  206. splits := make([]string, len(gpus))
  207. for i, count := range layerCounts {
  208. splits[i] = strconv.Itoa(count)
  209. }
  210. tensorSplit = strings.Join(splits, ",")
  211. }
  212. allocationsList := []string{}
  213. for _, a := range gpuAllocations {
  214. allocationsList = append(allocationsList, format.HumanBytes2(a))
  215. }
  216. slog.Info(
  217. "offload to gpu",
  218. slog.Group(
  219. "layers",
  220. // requested number of layers to offload
  221. "requested", opts.NumGPU,
  222. // The number of layers the model has (including output)
  223. "model", int(ggml.KV().BlockCount())+1,
  224. // estimated number of layers that can be offloaded
  225. "offload", layerCount,
  226. // multi-gpu split for tesnors
  227. "split", tensorSplit,
  228. ),
  229. slog.Group(
  230. "memory",
  231. // memory available by GPU for offloading
  232. "available", availableList,
  233. slog.Group(
  234. "required",
  235. // memory required for full offloading
  236. "full", format.HumanBytes2(memoryRequiredTotal),
  237. // memory required to offload layers.estimate layers
  238. "partial", format.HumanBytes2(memoryRequiredPartial),
  239. // memory of KV cache
  240. "kv", format.HumanBytes2(kv),
  241. // Allocations across the GPUs
  242. "allocations", allocationsList,
  243. ),
  244. slog.Group(
  245. "weights",
  246. // memory of the weights
  247. "total", format.HumanBytes2(memoryWeights),
  248. // memory of repeating layers
  249. "repeating", format.HumanBytes2(memoryWeights-memoryLayerOutput),
  250. // memory of non-repeating layers
  251. "nonrepeating", format.HumanBytes2(memoryLayerOutput),
  252. ),
  253. slog.Group(
  254. "graph",
  255. // memory of graph when fully offloaded
  256. "full", format.HumanBytes2(graphFullOffload),
  257. // memory of graph when not fully offloaded
  258. "partial", format.HumanBytes2(graphPartialOffload),
  259. ),
  260. ),
  261. )
  262. if gpus[0].Library == "cpu" {
  263. return MemoryEstimate{
  264. Layers: 0,
  265. Graph: 0,
  266. VRAMSize: 0,
  267. TotalSize: memoryRequiredTotal,
  268. GPUSizes: []uint64{},
  269. }
  270. }
  271. if layerCount == 0 {
  272. slog.Debug("insufficient VRAM to load any model layers")
  273. return MemoryEstimate{
  274. Layers: 0,
  275. Graph: 0,
  276. VRAMSize: 0,
  277. TotalSize: memoryRequiredTotal,
  278. GPUSizes: []uint64{},
  279. }
  280. }
  281. return MemoryEstimate{
  282. Layers: layerCount,
  283. Graph: graphOffload,
  284. VRAMSize: memoryRequiredPartial,
  285. TotalSize: memoryRequiredTotal,
  286. TensorSplit: tensorSplit,
  287. GPUSizes: gpuAllocations,
  288. }
  289. }