memory.go 10 KB

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