memory.go 13 KB

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