memory.go 14.9 KB
Newer Older
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1
2
3
package llm

import (
4
	"fmt"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
5
	"log/slog"
6
	"os"
Jesse Gross's avatar
Jesse Gross committed
7
	"sort"
8
	"strings"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
9
10

	"github.com/ollama/ollama/api"
11
	"github.com/ollama/ollama/discover"
12
	"github.com/ollama/ollama/envconfig"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
13
	"github.com/ollama/ollama/format"
Michael Yang's avatar
Michael Yang committed
14
	"github.com/ollama/ollama/fs/ggml"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
15
16
)

Jesse Gross's avatar
Jesse Gross committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// pickBestFullFitByLibrary will try to find the optimal placement of the model in the available GPUs where the model fully fits
// The list of GPUs returned will always be the same brand (library)
// If the model can not be fit fully within the available GPU(s) nil is returned
func pickBestFullFitByLibrary(f *ggml.GGML, modelPath string, projectors []string, adapters []string, opts api.Options, gpus discover.GpuInfoList, numParallel int) discover.GpuInfoList {
	for _, gl := range gpus.ByLibrary() {
		sgl := append(make(discover.GpuInfoList, 0, len(gl)), gl...)

		// TODO - potentially sort by performance capability, existing models loaded, etc.
		// TODO - Eliminate any GPUs that already have envconfig.MaxRunners loaded on them
		// Note: at present, this will favor most current available VRAM descending and ignoring faster GPU speed in mixed setups
		sort.Sort(sort.Reverse(discover.ByFreeMemory(sgl)))

		if !envconfig.SchedSpread() {
			// Try to pack into as few GPUs as possible, starting from 1 GPU
			for numGPUs := 1; numGPUs <= len(sgl); numGPUs++ {
				gpuSubset := sgl[:numGPUs]
33
				ok, estimatedVRAM := predictServerFit(gpuSubset, f, adapters, projectors, opts, numParallel)
Jesse Gross's avatar
Jesse Gross committed
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

				if ok {
					slog.Info("new model will fit in available VRAM across minimum required GPUs, loading",
						"model", modelPath,
						"library", sgl[0].Library,
						"parallel", numParallel,
						"required", format.HumanBytes2(estimatedVRAM),
						"gpus", numGPUs)
					return gpuSubset
				}
			}
		} else {
			// TODO future refinements
			// - if multiple Libraries, see if any single GPU in any Library will fit
			// - try subsets of GPUs instead of just falling back to 1 or all in a family

			// Now try all the GPUS (OLLAMA_SCHED_SPREAD is set)
51
			if ok, estimatedVRAM := predictServerFit(sgl, f, adapters, projectors, opts, numParallel); ok {
Jesse Gross's avatar
Jesse Gross committed
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
				slog.Info("new model will fit in available VRAM, loading",
					"model", modelPath,
					"library", sgl[0].Library,
					"parallel", numParallel,
					"required", format.HumanBytes2(estimatedVRAM),
					"gpus", len(sgl))
				return sgl
			}
		}
	}
	return nil
}

// If multiple Libraries are detected, pick the Library which loads the most layers for the model
func pickBestPartialFitByLibrary(f *ggml.GGML, projectors []string, adapters []string, opts api.Options, gpus discover.GpuInfoList, numParallel int) discover.GpuInfoList {
	byLibrary := gpus.ByLibrary()
	if len(byLibrary) <= 1 {
		return gpus
	}
	var bestEstimate uint64
	var bestFit int
	for i, gl := range byLibrary {
74
		_, estimatedVRAM := predictServerFit(gl, f, adapters, projectors, opts, numParallel)
Jesse Gross's avatar
Jesse Gross committed
75
76
77
78
79
80
81
82
		if estimatedVRAM > bestEstimate {
			bestEstimate = estimatedVRAM
			bestFit = i
		}
	}
	return byLibrary[bestFit]
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
83
// This algorithm looks for a complete fit to determine if we need to unload other models
84
func predictServerFit(allGpus discover.GpuInfoList, f *ggml.GGML, adapters, projectors []string, opts api.Options, numParallel int) (bool, uint64) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
85
	// Split up the GPUs by type and try them
86
	var estimatedVRAM uint64
Daniel Hiltgen's avatar
Daniel Hiltgen committed
87
88
	for _, gpus := range allGpus.ByLibrary() {
		var layerCount int
Jesse Gross's avatar
Jesse Gross committed
89
		estimate := estimateGPULayers(gpus, f, projectors, opts, numParallel)
90
		layerCount, estimatedVRAM = estimate.Layers, estimate.VRAMSize
Daniel Hiltgen's avatar
Daniel Hiltgen committed
91
		if opts.NumGPU < 0 {
Michael Yang's avatar
Michael Yang committed
92
			if layerCount > 0 && layerCount >= int(f.KV().BlockCount()+1) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
93
94
95
96
97
98
99
				return true, estimatedVRAM
			}
		} else {
			if layerCount > 0 && layerCount >= opts.NumGPU {
				return true, estimatedVRAM
			}
		}
100
101
102
103

		if len(gpus) == 1 && gpus[0].Library == "cpu" && estimate.TotalSize <= gpus[0].FreeMemory {
			return true, estimatedVRAM
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
104
105
106
107
	}
	return false, estimatedVRAM
}

108
109
110
111
112
113
114
115
116
117
118
119
120
121
type MemoryEstimate struct {
	// How many layers we predict we can load
	Layers int

	// The size of the graph which occupies the main GPU
	Graph uint64

	// How much VRAM will be allocated given the number of layers we predict
	VRAMSize uint64

	// The total size of the model if loaded into VRAM.  If all layers are loaded, VRAMSize == TotalSize
	TotalSize uint64

	// For multi-GPU scenarios, this provides the tensor split parameter
Jesse Gross's avatar
Jesse Gross committed
122
	TensorSplit []int
123
124
125

	// For multi-GPU scenarios, this is the size in bytes per GPU
	GPUSizes []uint64
126
127
128
129
130
131
132
133
134
135
136
137

	// internal fields for logging purposes
	inferenceLibrary    string
	layersRequested     int
	layersModel         int
	availableList       []string
	kv                  uint64
	allocationsList     []string
	memoryWeights       uint64
	memoryLayerOutput   uint64
	graphFullOffload    uint64
	graphPartialOffload uint64
138
139

	projectorWeights, projectorGraph uint64
140
141
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
142
// Given a model and one or more GPU targets, predict how many layers and bytes we can load, and the total size
Daniel Hiltgen's avatar
Daniel Hiltgen committed
143
// The GPUs provided must all be the same Library
Jesse Gross's avatar
Jesse Gross committed
144
func estimateGPULayers(gpus []discover.GpuInfo, f *ggml.GGML, projectors []string, opts api.Options, numParallel int) MemoryEstimate {
145
146
147
148
149
150
151
152
153
154
	// Graph size for a partial offload, applies to all GPUs
	var graphPartialOffload uint64

	// Graph size when all layers are offloaded, applies to all GPUs
	var graphFullOffload uint64

	// Final graph offload once we know full or partial
	var graphOffload uint64

	// Projectors loaded into GPU0 only
155
156
157
158
159
	var llamaEngineProjectorWeights uint64

	// Projectors loaded with output layer
	var ollamaEngineProjectorWeights uint64
	var ollamaEngineProjectorGraph uint64
160
161
162
163

	// Conditional output size on GPU 0
	var memoryLayerOutput uint64

Daniel Hiltgen's avatar
Daniel Hiltgen committed
164
165
	// The sizes of a layer
	var layerSize uint64
Daniel Hiltgen's avatar
Daniel Hiltgen committed
166

167
168
169
170
171
172
173
174
175
	// The sum of all the layer sizes (just for logging)
	var memoryWeights uint64

	// True if all the layers are loaded
	var fullyLoaded bool

	// Overflow that didn't fit into the GPU
	var overflow uint64

176
	overhead := envconfig.GpuOverhead()
177
178
179
180
181
	availableList := make([]string, len(gpus))
	for i, gpu := range gpus {
		availableList[i] = format.HumanBytes2(gpu.FreeMemory)
	}
	slog.Debug("evaluating", "library", gpus[0].Library, "gpu_count", len(gpus), "available", availableList)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
182
183

	for _, projector := range projectors {
184
		llamaEngineProjectorWeights += projectorMemoryRequirements(projector)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
185
	}
186
187
	if llamaEngineProjectorWeights == 0 {
		ollamaEngineProjectorWeights, ollamaEngineProjectorGraph = f.VisionGraphSize()
188
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
189

Michael Yang's avatar
Michael Yang committed
190
	layers := f.Tensors().GroupLayers()
Michael Yang's avatar
typo  
Michael Yang committed
191
192
	// add one layer worth of memory as a buffer
	if blk0, ok := layers["blk.0"]; ok {
Michael Yang's avatar
Michael Yang committed
193
		layerSize = blk0.Size()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
194
195
	} else {
		slog.Warn("model missing blk.0 layer size")
Michael Yang's avatar
typo  
Michael Yang committed
196
	}
Michael Yang's avatar
Michael Yang committed
197

198
	var kvct string
Michael Yang's avatar
Michael Yang committed
199
200
201
	if envconfig.FlashAttention() &&
		discover.GetGPUInfo().FlashAttentionSupported() &&
		f.SupportsFlashAttention() {
202
		requested := strings.ToLower(envconfig.KvCacheType())
Michael Yang's avatar
Michael Yang committed
203
		if requested != "" && f.SupportsKVCacheType(requested) {
204
205
206
207
			kvct = requested
		}
	}

208
	kv, graphPartialOffload, graphFullOffload := f.GraphSize(uint64(opts.NumCtx), uint64(min(opts.NumCtx, opts.NumBatch)), numParallel, kvct)
209

210
211
212
213
214
215
216
217
	if len(kv) > 0 {
		layerSize += kv[0]
	}

	var kvTotal uint64
	for _, kvLayer := range kv {
		kvTotal += kvLayer
	}
218

Daniel Hiltgen's avatar
Daniel Hiltgen committed
219
	if graphPartialOffload == 0 {
220
221
222
223
224
225
		headsKV := f.KV().HeadCountKVMin()
		if headsKV == 0 {
			headsKV = 1
		}
		gqa := f.KV().HeadCountMax() / headsKV
		graphPartialOffload = gqa * kvTotal / 6
Daniel Hiltgen's avatar
Daniel Hiltgen committed
226
227
228
229
230
	}
	if graphFullOffload == 0 {
		graphFullOffload = graphPartialOffload
	}

231
232
233
	// on metal there's no partial offload overhead
	if gpus[0].Library == "metal" {
		graphPartialOffload = graphFullOffload
Daniel Hiltgen's avatar
Daniel Hiltgen committed
234
235
236
	} else if len(gpus) > 1 {
		// multigpu should always use the partial graph size
		graphFullOffload = graphPartialOffload
237
238
	}

239
	// Output layer handled at the end if we have space
240
	if layer, ok := layers["output_norm"]; ok {
Michael Yang's avatar
Michael Yang committed
241
		memoryLayerOutput += layer.Size()
242
243
	}
	if layer, ok := layers["output"]; ok {
Michael Yang's avatar
Michael Yang committed
244
		memoryLayerOutput += layer.Size()
245
	} else if layer, ok := layers["token_embd"]; ok {
Michael Yang's avatar
Michael Yang committed
246
		memoryLayerOutput += layer.Size()
Michael Yang's avatar
Michael Yang committed
247
248
	}

249
	gpuZeroOverhead := llamaEngineProjectorWeights
250
251

	// Reduce set of GPUs to only those that have sufficient space to fit overhead and at least one layer
Michael Yang's avatar
Michael Yang committed
252
	var layerCount int
Jesse Gross's avatar
Jesse Gross committed
253
	tensorSplit := make([]int, len(gpus))
254
255
256
	gpuAllocations := make([]uint64, len(gpus))
	type gs struct {
		i int
257
		g *discover.GpuInfo
258
259
260
261
262
263
264
265
	}
	gpusWithSpace := []gs{}
	for i := range gpus {
		var gzo uint64
		if len(gpusWithSpace) == 0 {
			gzo = gpuZeroOverhead
		}
		// Only include GPUs that can fit the graph, gpu minimum, the layer buffer and at least more layer
266
		if gpus[i].FreeMemory < overhead+gzo+max(graphPartialOffload, graphFullOffload)+gpus[i].MinimumMemory+2*layerSize {
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
			slog.Debug("gpu has too little memory to allocate any layers",
				"id", gpus[i].ID,
				"library", gpus[i].Library,
				"variant", gpus[i].Variant,
				"compute", gpus[i].Compute,
				"driver", fmt.Sprintf("%d.%d", gpus[i].DriverMajor, gpus[i].DriverMinor),
				"name", gpus[i].Name,
				"total", format.HumanBytes2(gpus[i].TotalMemory),
				"available", format.HumanBytes2(gpus[i].FreeMemory),
				"minimum_memory", gpus[i].MinimumMemory,
				"layer_size", format.HumanBytes2(layerSize),
				"gpu_zer_overhead", format.HumanBytes2(gzo),
				"partial_offload", format.HumanBytes2(graphPartialOffload),
				"full_offload", format.HumanBytes2(graphFullOffload),
			)
282
283
284
			continue
		}
		gpusWithSpace = append(gpusWithSpace, gs{i, &gpus[i]})
Daniel Hiltgen's avatar
Daniel Hiltgen committed
285
		gpuAllocations[i] += gpus[i].MinimumMemory + layerSize // We hold off on graph until we know partial vs. full
286
287
288
289
290
291
	}

	var gpuZeroID int
	if len(gpusWithSpace) > 0 {
		gpuZeroID = gpusWithSpace[0].i
		gpuAllocations[gpuZeroID] += gpuZeroOverhead
292
293
	} else {
		overflow += gpuZeroOverhead
294
295
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
296
	// For all the layers, find where they can fit on the GPU(s)
297
	for i := int(f.KV().BlockCount()) - 1; i >= 0; i-- {
298
299
		// Some models have inconsistent layer sizes
		if blk, ok := layers[fmt.Sprintf("blk.%d", i)]; ok {
Michael Yang's avatar
Michael Yang committed
300
			layerSize = blk.Size()
301
			layerSize += kv[i]
Michael Yang's avatar
Michael Yang committed
302
			memoryWeights += blk.Size()
303
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
304

305
306
		if opts.NumGPU >= 0 && layerCount >= opts.NumGPU {
			// Stop allocating on GPU(s) once we hit the users target NumGPU
307
			overflow += layerSize
308
309
310
311
312
313
314
			continue
		}

		// distribute the layers across the GPU(s) that have space
		for j := len(gpusWithSpace); j > 0; j-- {
			g := gpusWithSpace[i%j]
			used := gpuAllocations[g.i] + max(graphPartialOffload, graphFullOffload)
315
			if g.g.FreeMemory > overhead+used+layerSize {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
316
				gpuAllocations[g.i] += layerSize
Jesse Gross's avatar
Jesse Gross committed
317
				tensorSplit[g.i]++
Michael Yang's avatar
typo  
Michael Yang committed
318
				layerCount++
319
320
321
				break
			} else {
				gpusWithSpace = append(gpusWithSpace[:i%j], gpusWithSpace[i%j+1:]...)
Michael Yang's avatar
typo  
Michael Yang committed
322
			}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
323
		}
324
325
326
327

		if len(gpusWithSpace) == 0 {
			overflow += layerSize
		}
328
	}
Michael Yang's avatar
Michael Yang committed
329
	if layerCount >= int(f.KV().BlockCount()) {
330
331
		fullyLoaded = true
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
332
333

	// Determine if we need to consider output then find where it fits
334
335
	memoryLastLayer := memoryLayerOutput + ollamaEngineProjectorWeights + ollamaEngineProjectorGraph
	if memoryLastLayer > 0 {
336
337
338
339
		if opts.NumGPU < 0 || layerCount < opts.NumGPU {
			for j := len(gpusWithSpace); j > 0; j-- {
				g := gpusWithSpace[layerCount%j]
				used := gpuAllocations[g.i] + max(graphPartialOffload, graphFullOffload)
340
341
				if g.g.FreeMemory > overhead+used+memoryLastLayer {
					gpuAllocations[g.i] += memoryLastLayer
Jesse Gross's avatar
Jesse Gross committed
342
					tensorSplit[g.i]++
343
344
345
					layerCount++
					break
				}
346
347
			}
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
348

Michael Yang's avatar
Michael Yang committed
349
		if layerCount < int(f.KV().BlockCount())+1 {
350
			fullyLoaded = false
351
			overflow += memoryLastLayer
352
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
353
354
	}

355
356
	// Add the applicable (full or partial) graph allocations
	for i := range gpus {
Jesse Gross's avatar
Jesse Gross committed
357
		if tensorSplit[i] <= 0 {
358
359
360
361
362
363
364
365
366
367
368
369
			continue
		}
		if fullyLoaded {
			gpuAllocations[i] += graphFullOffload
		} else {
			gpuAllocations[i] += graphPartialOffload
		}
	}
	if fullyLoaded {
		graphOffload = graphFullOffload
	} else {
		graphOffload = graphPartialOffload
Daniel Hiltgen's avatar
Daniel Hiltgen committed
370
371
	}

372
373
374
375
	// Summaries for the log
	var memoryRequiredPartial, memoryRequiredTotal uint64
	for i := range gpuAllocations {
		memoryRequiredPartial += gpuAllocations[i]
Daniel Hiltgen's avatar
Daniel Hiltgen committed
376
	}
377
	memoryRequiredTotal = memoryRequiredPartial + overflow
Daniel Hiltgen's avatar
Daniel Hiltgen committed
378

379
380
381
382
	allocationsList := []string{}
	for _, a := range gpuAllocations {
		allocationsList = append(allocationsList, format.HumanBytes2(a))
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
383

384
385
386
387
388
389
390
391
392
	estimate := MemoryEstimate{
		TotalSize: memoryRequiredTotal,
		Layers:    0,
		Graph:     0,
		VRAMSize:  0,
		GPUSizes:  []uint64{},

		inferenceLibrary:    gpus[0].Library,
		layersRequested:     opts.NumGPU,
Michael Yang's avatar
Michael Yang committed
393
		layersModel:         int(f.KV().BlockCount()) + 1,
394
		availableList:       availableList,
395
		kv:                  kvTotal,
396
397
398
399
400
		allocationsList:     allocationsList,
		memoryWeights:       memoryWeights,
		memoryLayerOutput:   memoryLayerOutput,
		graphFullOffload:    graphFullOffload,
		graphPartialOffload: graphPartialOffload,
401
402
		projectorWeights:    llamaEngineProjectorWeights + ollamaEngineProjectorWeights,
		projectorGraph:      ollamaEngineProjectorGraph,
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
	}

	if gpus[0].Library == "cpu" {
		return estimate
	}
	if layerCount == 0 {
		slog.Debug("insufficient VRAM to load any model layers")
		return estimate
	}
	estimate.Layers = layerCount
	estimate.Graph = graphOffload
	estimate.VRAMSize = memoryRequiredPartial
	estimate.TotalSize = memoryRequiredTotal
	estimate.TensorSplit = tensorSplit
	estimate.GPUSizes = gpuAllocations
	return estimate
}

Michael Yang's avatar
Michael Yang committed
421
422
423
func (m MemoryEstimate) LogValue() slog.Value {
	attrs := []slog.Attr{
		slog.String("library", m.inferenceLibrary),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
424
425
		slog.Group(
			"layers",
Michael Yang's avatar
Michael Yang committed
426
			// requested number of layers to offload
427
			"requested", m.layersRequested,
428
			// The number of layers the model has (including output)
429
			"model", m.layersModel,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
430
			// estimated number of layers that can be offloaded
431
432
433
			"offload", m.Layers,
			// multi-gpu split for tensors
			"split", m.TensorSplit,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
434
435
436
		),
		slog.Group(
			"memory",
437
			// memory available by GPU for offloading
438
			"available", m.availableList,
Michael Yang's avatar
Michael Yang committed
439
			"gpu_overhead", format.HumanBytes2(envconfig.GpuOverhead()),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
440
441
442
			slog.Group(
				"required",
				// memory required for full offloading
443
				"full", format.HumanBytes2(m.TotalSize),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
444
				// memory required to offload layers.estimate layers
445
				"partial", format.HumanBytes2(m.VRAMSize),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
446
				// memory of KV cache
447
				"kv", format.HumanBytes2(m.kv),
448
				// Allocations across the GPUs
449
				"allocations", m.allocationsList,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
450
451
452
453
			),
			slog.Group(
				"weights",
				// memory of the weights
454
				"total", format.HumanBytes2(m.memoryWeights+m.memoryLayerOutput),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
455
				// memory of repeating layers
Michael Yang's avatar
Michael Yang committed
456
				"repeating", format.HumanBytes2(m.memoryWeights),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
457
				// memory of non-repeating layers
458
				"nonrepeating", format.HumanBytes2(m.memoryLayerOutput),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
459
460
461
462
			),
			slog.Group(
				"graph",
				// memory of graph when fully offloaded
463
				"full", format.HumanBytes2(m.graphFullOffload),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
464
				// memory of graph when not fully offloaded
465
				"partial", format.HumanBytes2(m.graphPartialOffload),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
466
467
			),
		),
Michael Yang's avatar
Michael Yang committed
468
469
470
471
472
473
474
475
476
477
478
	}

	if m.projectorWeights > 0 {
		attrs = append(attrs, slog.Group(
			"projector",
			"weights", format.HumanBytes2(m.projectorWeights),
			"graph", format.HumanBytes2(m.projectorGraph),
		))
	}

	return slog.GroupValue(attrs...)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
479
}
480

481
func projectorMemoryRequirements(filename string) (weights uint64) {
482
483
	file, err := os.Open(filename)
	if err != nil {
484
		return 0
485
486
487
	}
	defer file.Close()

488
	ggml, err := ggml.Decode(file, 1024)
489
	if err != nil {
490
		return 0
491
492
	}

Michael Yang's avatar
Michael Yang committed
493
494
	for _, layer := range ggml.Tensors().GroupLayers() {
		weights += layer.Size()
495
496
	}

497
	return weights
498
}