memory.go 13 KB

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