memory.go 10 KB

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