memory.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. layers := f.Tensors().GroupLayers()
  96. // add one layer worth of memory as a buffer
  97. if blk0, ok := layers["blk.0"]; ok {
  98. layerSize = blk0.Size()
  99. } else {
  100. slog.Warn("model missing blk.0 layer size")
  101. }
  102. var kvct string
  103. if envconfig.FlashAttention() &&
  104. discover.GetGPUInfo().FlashAttentionSupported() &&
  105. f.SupportsFlashAttention() {
  106. requested := strings.ToLower(envconfig.KvCacheType())
  107. if requested != "" && f.SupportsKVCacheType(requested) {
  108. kvct = requested
  109. }
  110. }
  111. kv, graphPartialOffload, graphFullOffload := f.GraphSize(uint64(opts.NumCtx), uint64(min(opts.NumCtx, opts.NumBatch)), kvct)
  112. // KV is proportional to the number of layers
  113. layerSize += kv / f.KV().BlockCount()
  114. if graphPartialOffload == 0 {
  115. graphPartialOffload = f.KV().GQA() * kv / 6
  116. }
  117. if graphFullOffload == 0 {
  118. graphFullOffload = graphPartialOffload
  119. }
  120. // on metal there's no partial offload overhead
  121. if gpus[0].Library == "metal" {
  122. graphPartialOffload = graphFullOffload
  123. } else if len(gpus) > 1 {
  124. // multigpu should always use the partial graph size
  125. graphFullOffload = graphPartialOffload
  126. }
  127. if layer, ok := layers["output_norm"]; ok {
  128. memoryLayerOutput += layer.Size()
  129. }
  130. if layer, ok := layers["output"]; ok {
  131. memoryLayerOutput += layer.Size()
  132. } else if layer, ok := layers["token_embd"]; ok {
  133. memoryLayerOutput += layer.Size()
  134. }
  135. // Output layer handled at the end if we have space
  136. gpuZeroOverhead := projectorWeights + projectorGraph
  137. // Reduce set of GPUs to only those that have sufficient space to fit overhead and at least one layer
  138. var layerCount int
  139. layerCounts := make([]int, len(gpus))
  140. gpuAllocations := make([]uint64, len(gpus))
  141. type gs struct {
  142. i int
  143. g *discover.GpuInfo
  144. }
  145. gpusWithSpace := []gs{}
  146. for i := range gpus {
  147. var gzo uint64
  148. if len(gpusWithSpace) == 0 {
  149. gzo = gpuZeroOverhead
  150. }
  151. // Only include GPUs that can fit the graph, gpu minimum, the layer buffer and at least more layer
  152. if gpus[i].FreeMemory < overhead+gzo+max(graphPartialOffload, graphFullOffload)+gpus[i].MinimumMemory+2*layerSize {
  153. slog.Debug("gpu has too little memory to allocate any layers",
  154. "id", gpus[i].ID,
  155. "library", gpus[i].Library,
  156. "variant", gpus[i].Variant,
  157. "compute", gpus[i].Compute,
  158. "driver", fmt.Sprintf("%d.%d", gpus[i].DriverMajor, gpus[i].DriverMinor),
  159. "name", gpus[i].Name,
  160. "total", format.HumanBytes2(gpus[i].TotalMemory),
  161. "available", format.HumanBytes2(gpus[i].FreeMemory),
  162. "minimum_memory", gpus[i].MinimumMemory,
  163. "layer_size", format.HumanBytes2(layerSize),
  164. "gpu_zer_overhead", format.HumanBytes2(gzo),
  165. "partial_offload", format.HumanBytes2(graphPartialOffload),
  166. "full_offload", format.HumanBytes2(graphFullOffload),
  167. )
  168. continue
  169. }
  170. gpusWithSpace = append(gpusWithSpace, gs{i, &gpus[i]})
  171. gpuAllocations[i] += gpus[i].MinimumMemory + layerSize // We hold off on graph until we know partial vs. full
  172. }
  173. var gpuZeroID int
  174. if len(gpusWithSpace) > 0 {
  175. gpuZeroID = gpusWithSpace[0].i
  176. gpuAllocations[gpuZeroID] += gpuZeroOverhead
  177. }
  178. // For all the layers, find where they can fit on the GPU(s)
  179. for i := range int(f.KV().BlockCount()) {
  180. // Some models have inconsistent layer sizes
  181. if blk, ok := layers[fmt.Sprintf("blk.%d", i)]; ok {
  182. layerSize = blk.Size()
  183. layerSize += kv / f.KV().BlockCount()
  184. }
  185. memoryWeights += layerSize
  186. if opts.NumGPU >= 0 && layerCount >= opts.NumGPU {
  187. // Stop allocating on GPU(s) once we hit the users target NumGPU
  188. continue
  189. }
  190. // distribute the layers across the GPU(s) that have space
  191. for j := len(gpusWithSpace); j > 0; j-- {
  192. g := gpusWithSpace[i%j]
  193. used := gpuAllocations[g.i] + max(graphPartialOffload, graphFullOffload)
  194. if g.g.FreeMemory > overhead+used+layerSize {
  195. gpuAllocations[g.i] += layerSize
  196. layerCounts[g.i]++
  197. layerCount++
  198. break
  199. } else {
  200. gpusWithSpace = append(gpusWithSpace[:i%j], gpusWithSpace[i%j+1:]...)
  201. }
  202. }
  203. }
  204. if layerCount >= int(f.KV().BlockCount()) {
  205. fullyLoaded = true
  206. } else {
  207. for i := layerCount; i < int(f.KV().BlockCount()); i++ {
  208. overflow += layerSize
  209. }
  210. }
  211. // Determine if we need to consider output then find where it fits
  212. if memoryLayerOutput > 0 && (opts.NumGPU < 0 || layerCount < opts.NumGPU) {
  213. for j := len(gpusWithSpace); j > 0; j-- {
  214. g := gpusWithSpace[layerCount%j]
  215. used := gpuAllocations[g.i] + max(graphPartialOffload, graphFullOffload)
  216. if g.g.FreeMemory > overhead+used+memoryLayerOutput {
  217. gpuAllocations[g.i] += memoryLayerOutput
  218. layerCounts[g.i]++
  219. layerCount++
  220. break
  221. }
  222. }
  223. if layerCount < int(f.KV().BlockCount())+1 {
  224. fullyLoaded = false
  225. overflow += memoryLayerOutput
  226. }
  227. }
  228. // Add the applicable (full or partial) graph allocations
  229. for i := range gpus {
  230. if layerCounts[i] <= 0 {
  231. continue
  232. }
  233. if fullyLoaded {
  234. gpuAllocations[i] += graphFullOffload
  235. } else {
  236. gpuAllocations[i] += graphPartialOffload
  237. }
  238. }
  239. if fullyLoaded {
  240. graphOffload = graphFullOffload
  241. } else {
  242. graphOffload = graphPartialOffload
  243. }
  244. // Summaries for the log
  245. var memoryRequiredPartial, memoryRequiredTotal uint64
  246. for i := range gpuAllocations {
  247. memoryRequiredPartial += gpuAllocations[i]
  248. }
  249. memoryRequiredTotal = memoryRequiredPartial + overflow
  250. tensorSplit := ""
  251. if len(gpus) > 1 {
  252. splits := make([]string, len(gpus))
  253. for i, count := range layerCounts {
  254. splits[i] = strconv.Itoa(count)
  255. }
  256. tensorSplit = strings.Join(splits, ",")
  257. }
  258. allocationsList := []string{}
  259. for _, a := range gpuAllocations {
  260. allocationsList = append(allocationsList, format.HumanBytes2(a))
  261. }
  262. estimate := MemoryEstimate{
  263. TotalSize: memoryRequiredTotal,
  264. Layers: 0,
  265. Graph: 0,
  266. VRAMSize: 0,
  267. GPUSizes: []uint64{},
  268. inferenceLibrary: gpus[0].Library,
  269. layersRequested: opts.NumGPU,
  270. layersModel: int(f.KV().BlockCount()) + 1,
  271. availableList: availableList,
  272. kv: kv,
  273. allocationsList: allocationsList,
  274. memoryWeights: memoryWeights,
  275. memoryLayerOutput: memoryLayerOutput,
  276. graphFullOffload: graphFullOffload,
  277. graphPartialOffload: graphPartialOffload,
  278. projectorWeights: projectorWeights,
  279. projectorGraph: projectorGraph,
  280. }
  281. if gpus[0].Library == "cpu" {
  282. return estimate
  283. }
  284. if layerCount == 0 {
  285. slog.Debug("insufficient VRAM to load any model layers")
  286. return estimate
  287. }
  288. estimate.Layers = layerCount
  289. estimate.Graph = graphOffload
  290. estimate.VRAMSize = memoryRequiredPartial
  291. estimate.TotalSize = memoryRequiredTotal
  292. estimate.TensorSplit = tensorSplit
  293. estimate.GPUSizes = gpuAllocations
  294. return estimate
  295. }
  296. func (m MemoryEstimate) LogValue() slog.Value {
  297. attrs := []slog.Attr{
  298. slog.String("library", m.inferenceLibrary),
  299. slog.Group(
  300. "layers",
  301. // requested number of layers to offload
  302. "requested", m.layersRequested,
  303. // The number of layers the model has (including output)
  304. "model", m.layersModel,
  305. // estimated number of layers that can be offloaded
  306. "offload", m.Layers,
  307. // multi-gpu split for tensors
  308. "split", m.TensorSplit,
  309. ),
  310. slog.Group(
  311. "memory",
  312. // memory available by GPU for offloading
  313. "available", m.availableList,
  314. "gpu_overhead", format.HumanBytes2(envconfig.GpuOverhead()),
  315. slog.Group(
  316. "required",
  317. // memory required for full offloading
  318. "full", format.HumanBytes2(m.TotalSize),
  319. // memory required to offload layers.estimate layers
  320. "partial", format.HumanBytes2(m.VRAMSize),
  321. // memory of KV cache
  322. "kv", format.HumanBytes2(m.kv),
  323. // Allocations across the GPUs
  324. "allocations", m.allocationsList,
  325. ),
  326. slog.Group(
  327. "weights",
  328. // memory of the weights
  329. "total", format.HumanBytes2(m.memoryWeights),
  330. // memory of repeating layers
  331. "repeating", format.HumanBytes2(m.memoryWeights-m.memoryLayerOutput),
  332. // memory of non-repeating layers
  333. "nonrepeating", format.HumanBytes2(m.memoryLayerOutput),
  334. ),
  335. slog.Group(
  336. "graph",
  337. // memory of graph when fully offloaded
  338. "full", format.HumanBytes2(m.graphFullOffload),
  339. // memory of graph when not fully offloaded
  340. "partial", format.HumanBytes2(m.graphPartialOffload),
  341. ),
  342. ),
  343. }
  344. if m.projectorWeights > 0 {
  345. attrs = append(attrs, slog.Group(
  346. "projector",
  347. "weights", format.HumanBytes2(m.projectorWeights),
  348. "graph", format.HumanBytes2(m.projectorGraph),
  349. ))
  350. }
  351. return slog.GroupValue(attrs...)
  352. }
  353. func projectorMemoryRequirements(filename string) (weights, graphSize uint64) {
  354. file, err := os.Open(filename)
  355. if err != nil {
  356. return 0, 0
  357. }
  358. defer file.Close()
  359. ggml, _, err := ggml.Decode(file, 0)
  360. if err != nil {
  361. return 0, 0
  362. }
  363. for _, layer := range ggml.Tensors().GroupLayers() {
  364. weights += layer.Size()
  365. }
  366. switch arch := ggml.KV().Architecture(); arch {
  367. case "mllama":
  368. kv := func(n string) uint64 {
  369. if v, ok := ggml.KV()[arch+".vision."+n].(uint32); ok {
  370. return uint64(v)
  371. }
  372. return 0
  373. }
  374. imageSize := kv("image_size")
  375. maxNumTiles := kv("max_num_tiles")
  376. embeddingLength := kv("embedding_length")
  377. headCount := kv("attention.head_count")
  378. numPatches := (imageSize / kv("patch_size")) * (imageSize / kv("patch_size"))
  379. if _, ok := ggml.Tensors().GroupLayers()["v"]["class_embd"]; ok {
  380. numPatches++
  381. }
  382. numPaddedPatches := numPatches + 8 - (numPatches%8)%8
  383. graphSize = 4 * (8 +
  384. imageSize*imageSize*kv("num_channels")*maxNumTiles +
  385. embeddingLength*numPatches*maxNumTiles +
  386. 9*embeddingLength*numPaddedPatches*maxNumTiles +
  387. numPaddedPatches*maxNumTiles*numPaddedPatches*maxNumTiles*headCount)
  388. }
  389. return weights, graphSize
  390. }