memory.go 12.8 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"
7
8
	"strconv"
	"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
17
)

// This algorithm looks for a complete fit to determine if we need to unload other models
Michael Yang's avatar
Michael Yang committed
18
func PredictServerFit(allGpus discover.GpuInfoList, f *ggml.GGML, adapters, projectors []string, opts api.Options) (bool, uint64) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
19
	// Split up the GPUs by type and try them
20
	var estimatedVRAM uint64
Daniel Hiltgen's avatar
Daniel Hiltgen committed
21
22
	for _, gpus := range allGpus.ByLibrary() {
		var layerCount int
Michael Yang's avatar
Michael Yang committed
23
		estimate := EstimateGPULayers(gpus, f, projectors, opts)
24
		layerCount, estimatedVRAM = estimate.Layers, estimate.VRAMSize
Daniel Hiltgen's avatar
Daniel Hiltgen committed
25
		if opts.NumGPU < 0 {
Michael Yang's avatar
Michael Yang committed
26
			if layerCount > 0 && layerCount >= int(f.KV().BlockCount()+1) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
27
28
29
30
31
32
33
34
35
36
37
				return true, estimatedVRAM
			}
		} else {
			if layerCount > 0 && layerCount >= opts.NumGPU {
				return true, estimatedVRAM
			}
		}
	}
	return false, estimatedVRAM
}

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
	TensorSplit string

	// For multi-GPU scenarios, this is the size in bytes per GPU
	GPUSizes []uint64
56
57
58
59
60
61
62
63
64
65
66
67

	// 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
68
69

	projectorWeights, projectorGraph uint64
70
71
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
72
// 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
73
// The GPUs provided must all be the same Library
Michael Yang's avatar
Michael Yang committed
74
func EstimateGPULayers(gpus []discover.GpuInfo, f *ggml.GGML, projectors []string, opts api.Options) MemoryEstimate {
75
76
77
78
79
80
81
82
83
84
	// 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
85
86
	var projectorWeights uint64
	var projectorGraph uint64
87
88
89
90

	// Conditional output size on GPU 0
	var memoryLayerOutput uint64

Daniel Hiltgen's avatar
Daniel Hiltgen committed
91
92
	// The sizes of a layer
	var layerSize uint64
Daniel Hiltgen's avatar
Daniel Hiltgen committed
93

94
95
96
97
98
99
100
101
102
	// 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

103
	overhead := envconfig.GpuOverhead()
104
105
106
107
108
	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
109
110

	for _, projector := range projectors {
111
112
113
		weight, graph := projectorMemoryRequirements(projector)
		projectorWeights += weight
		projectorGraph += graph
Daniel Hiltgen's avatar
Daniel Hiltgen committed
114
115
116
117

		// multimodal models require at least 2048 context
		opts.NumCtx = max(opts.NumCtx, 2048)
	}
118
119
120
	if projectorWeights == 0 && projectorGraph == 0 {
		projectorWeights, projectorGraph = f.VisionGraphSize()
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
121

Michael Yang's avatar
Michael Yang committed
122
	layers := f.Tensors().GroupLayers()
Michael Yang's avatar
typo  
Michael Yang committed
123
124
	// add one layer worth of memory as a buffer
	if blk0, ok := layers["blk.0"]; ok {
Michael Yang's avatar
Michael Yang committed
125
		layerSize = blk0.Size()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
126
127
	} else {
		slog.Warn("model missing blk.0 layer size")
Michael Yang's avatar
typo  
Michael Yang committed
128
	}
Michael Yang's avatar
Michael Yang committed
129

130
	var kvct string
Michael Yang's avatar
Michael Yang committed
131
132
133
	if envconfig.FlashAttention() &&
		discover.GetGPUInfo().FlashAttentionSupported() &&
		f.SupportsFlashAttention() {
134
		requested := strings.ToLower(envconfig.KvCacheType())
Michael Yang's avatar
Michael Yang committed
135
		if requested != "" && f.SupportsKVCacheType(requested) {
136
137
138
139
			kvct = requested
		}
	}

Michael Yang's avatar
Michael Yang committed
140
	kv, graphPartialOffload, graphFullOffload := f.GraphSize(uint64(opts.NumCtx), uint64(min(opts.NumCtx, opts.NumBatch)), kvct)
141
142

	// KV is proportional to the number of layers
Michael Yang's avatar
Michael Yang committed
143
	layerSize += kv / f.KV().BlockCount()
144

Daniel Hiltgen's avatar
Daniel Hiltgen committed
145
	if graphPartialOffload == 0 {
Michael Yang's avatar
Michael Yang committed
146
		graphPartialOffload = f.KV().GQA() * kv / 6
Daniel Hiltgen's avatar
Daniel Hiltgen committed
147
148
149
150
151
	}
	if graphFullOffload == 0 {
		graphFullOffload = graphPartialOffload
	}

152
153
154
	// on metal there's no partial offload overhead
	if gpus[0].Library == "metal" {
		graphPartialOffload = graphFullOffload
Daniel Hiltgen's avatar
Daniel Hiltgen committed
155
156
157
	} else if len(gpus) > 1 {
		// multigpu should always use the partial graph size
		graphFullOffload = graphPartialOffload
158
159
	}

160
	if layer, ok := layers["output_norm"]; ok {
Michael Yang's avatar
Michael Yang committed
161
		memoryLayerOutput += layer.Size()
162
163
	}
	if layer, ok := layers["output"]; ok {
Michael Yang's avatar
Michael Yang committed
164
		memoryLayerOutput += layer.Size()
165
	} else if layer, ok := layers["token_embd"]; ok {
Michael Yang's avatar
Michael Yang committed
166
		memoryLayerOutput += layer.Size()
Michael Yang's avatar
Michael Yang committed
167
168
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
169
	// Output layer handled at the end if we have space
170
	gpuZeroOverhead := projectorWeights + projectorGraph
171
172

	// 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
173
	var layerCount int
174
175
176
177
	layerCounts := make([]int, len(gpus))
	gpuAllocations := make([]uint64, len(gpus))
	type gs struct {
		i int
178
		g *discover.GpuInfo
179
180
181
182
183
184
185
186
	}
	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
187
		if gpus[i].FreeMemory < overhead+gzo+max(graphPartialOffload, graphFullOffload)+gpus[i].MinimumMemory+2*layerSize {
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
			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),
			)
203
204
205
			continue
		}
		gpusWithSpace = append(gpusWithSpace, gs{i, &gpus[i]})
Daniel Hiltgen's avatar
Daniel Hiltgen committed
206
		gpuAllocations[i] += gpus[i].MinimumMemory + layerSize // We hold off on graph until we know partial vs. full
207
208
209
210
211
212
213
214
	}

	var gpuZeroID int
	if len(gpusWithSpace) > 0 {
		gpuZeroID = gpusWithSpace[0].i
		gpuAllocations[gpuZeroID] += gpuZeroOverhead
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
215
	// For all the layers, find where they can fit on the GPU(s)
Michael Yang's avatar
Michael Yang committed
216
	for i := range int(f.KV().BlockCount()) {
217
218
		// Some models have inconsistent layer sizes
		if blk, ok := layers[fmt.Sprintf("blk.%d", i)]; ok {
Michael Yang's avatar
Michael Yang committed
219
220
			layerSize = blk.Size()
			layerSize += kv / f.KV().BlockCount()
Michael Yang's avatar
Michael Yang committed
221
			memoryWeights += blk.Size()
222
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
223

224
225
226
227
228
229
230
231
232
		if opts.NumGPU >= 0 && layerCount >= opts.NumGPU {
			// Stop allocating on GPU(s) once we hit the users target NumGPU
			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)
233
			if g.g.FreeMemory > overhead+used+layerSize {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
234
				gpuAllocations[g.i] += layerSize
235
				layerCounts[g.i]++
Michael Yang's avatar
typo  
Michael Yang committed
236
				layerCount++
237
238
239
				break
			} else {
				gpusWithSpace = append(gpusWithSpace[:i%j], gpusWithSpace[i%j+1:]...)
Michael Yang's avatar
typo  
Michael Yang committed
240
			}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
241
		}
242
	}
Michael Yang's avatar
Michael Yang committed
243
	if layerCount >= int(f.KV().BlockCount()) {
244
245
		fullyLoaded = true
	} else {
Michael Yang's avatar
Michael Yang committed
246
		for i := layerCount; i < int(f.KV().BlockCount()); i++ {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
247
			overflow += layerSize
248
249
		}
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
250
251

	// Determine if we need to consider output then find where it fits
252
	if memoryLayerOutput > 0 && (opts.NumGPU < 0 || layerCount < opts.NumGPU) {
253
254
255
		for j := len(gpusWithSpace); j > 0; j-- {
			g := gpusWithSpace[layerCount%j]
			used := gpuAllocations[g.i] + max(graphPartialOffload, graphFullOffload)
256
			if g.g.FreeMemory > overhead+used+memoryLayerOutput {
257
258
259
260
261
262
				gpuAllocations[g.i] += memoryLayerOutput
				layerCounts[g.i]++
				layerCount++
				break
			}
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
263

Michael Yang's avatar
Michael Yang committed
264
		if layerCount < int(f.KV().BlockCount())+1 {
265
266
267
			fullyLoaded = false
			overflow += memoryLayerOutput
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
268
269
	}

270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
	// Add the applicable (full or partial) graph allocations
	for i := range gpus {
		if layerCounts[i] <= 0 {
			continue
		}
		if fullyLoaded {
			gpuAllocations[i] += graphFullOffload
		} else {
			gpuAllocations[i] += graphPartialOffload
		}
	}
	if fullyLoaded {
		graphOffload = graphFullOffload
	} else {
		graphOffload = graphPartialOffload
Daniel Hiltgen's avatar
Daniel Hiltgen committed
285
286
	}

287
288
289
290
	// Summaries for the log
	var memoryRequiredPartial, memoryRequiredTotal uint64
	for i := range gpuAllocations {
		memoryRequiredPartial += gpuAllocations[i]
Daniel Hiltgen's avatar
Daniel Hiltgen committed
291
	}
292
	memoryRequiredTotal = memoryRequiredPartial + overflow
Daniel Hiltgen's avatar
Daniel Hiltgen committed
293

294
295
296
297
298
299
300
301
302
303
304
305
	tensorSplit := ""
	if len(gpus) > 1 {
		splits := make([]string, len(gpus))
		for i, count := range layerCounts {
			splits[i] = strconv.Itoa(count)
		}
		tensorSplit = strings.Join(splits, ",")
	}
	allocationsList := []string{}
	for _, a := range gpuAllocations {
		allocationsList = append(allocationsList, format.HumanBytes2(a))
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
306

307
308
309
310
311
312
313
314
315
	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
316
		layersModel:         int(f.KV().BlockCount()) + 1,
317
318
319
320
321
322
323
		availableList:       availableList,
		kv:                  kv,
		allocationsList:     allocationsList,
		memoryWeights:       memoryWeights,
		memoryLayerOutput:   memoryLayerOutput,
		graphFullOffload:    graphFullOffload,
		graphPartialOffload: graphPartialOffload,
324
325
		projectorWeights:    projectorWeights,
		projectorGraph:      projectorGraph,
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
	}

	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
344
345
346
func (m MemoryEstimate) LogValue() slog.Value {
	attrs := []slog.Attr{
		slog.String("library", m.inferenceLibrary),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
347
348
		slog.Group(
			"layers",
Michael Yang's avatar
Michael Yang committed
349
			// requested number of layers to offload
350
			"requested", m.layersRequested,
351
			// The number of layers the model has (including output)
352
			"model", m.layersModel,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
353
			// estimated number of layers that can be offloaded
354
355
356
			"offload", m.Layers,
			// multi-gpu split for tensors
			"split", m.TensorSplit,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
357
358
359
		),
		slog.Group(
			"memory",
360
			// memory available by GPU for offloading
361
			"available", m.availableList,
Michael Yang's avatar
Michael Yang committed
362
			"gpu_overhead", format.HumanBytes2(envconfig.GpuOverhead()),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
363
364
365
			slog.Group(
				"required",
				// memory required for full offloading
366
				"full", format.HumanBytes2(m.TotalSize),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
367
				// memory required to offload layers.estimate layers
368
				"partial", format.HumanBytes2(m.VRAMSize),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
369
				// memory of KV cache
370
				"kv", format.HumanBytes2(m.kv),
371
				// Allocations across the GPUs
372
				"allocations", m.allocationsList,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
373
374
375
376
			),
			slog.Group(
				"weights",
				// memory of the weights
377
				"total", format.HumanBytes2(m.memoryWeights+m.memoryLayerOutput),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
378
				// memory of repeating layers
Michael Yang's avatar
Michael Yang committed
379
				"repeating", format.HumanBytes2(m.memoryWeights),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
380
				// memory of non-repeating layers
381
				"nonrepeating", format.HumanBytes2(m.memoryLayerOutput),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
382
383
384
385
			),
			slog.Group(
				"graph",
				// memory of graph when fully offloaded
386
				"full", format.HumanBytes2(m.graphFullOffload),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
387
				// memory of graph when not fully offloaded
388
				"partial", format.HumanBytes2(m.graphPartialOffload),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
389
390
			),
		),
Michael Yang's avatar
Michael Yang committed
391
392
393
394
395
396
397
398
399
400
401
	}

	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
402
}
403
404
405
406
407
408
409
410

func projectorMemoryRequirements(filename string) (weights, graphSize uint64) {
	file, err := os.Open(filename)
	if err != nil {
		return 0, 0
	}
	defer file.Close()

Michael Yang's avatar
Michael Yang committed
411
	ggml, _, err := ggml.Decode(file, 0)
412
413
414
415
	if err != nil {
		return 0, 0
	}

Michael Yang's avatar
Michael Yang committed
416
417
	for _, layer := range ggml.Tensors().GroupLayers() {
		weights += layer.Size()
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
	}

	switch arch := ggml.KV().Architecture(); arch {
	case "mllama":
		kv := func(n string) uint64 {
			if v, ok := ggml.KV()[arch+".vision."+n].(uint32); ok {
				return uint64(v)
			}

			return 0
		}

		imageSize := kv("image_size")

		maxNumTiles := kv("max_num_tiles")
		embeddingLength := kv("embedding_length")
		headCount := kv("attention.head_count")

		numPatches := (imageSize / kv("patch_size")) * (imageSize / kv("patch_size"))
Michael Yang's avatar
Michael Yang committed
437
		if _, ok := ggml.Tensors().GroupLayers()["v"]["class_embd"]; ok {
438
439
440
441
442
443
444
445
446
447
448
449
450
451
			numPatches++
		}

		numPaddedPatches := numPatches + 8 - (numPatches%8)%8

		graphSize = 4 * (8 +
			imageSize*imageSize*kv("num_channels")*maxNumTiles +
			embeddingLength*numPatches*maxNumTiles +
			9*embeddingLength*numPaddedPatches*maxNumTiles +
			numPaddedPatches*maxNumTiles*numPaddedPatches*maxNumTiles*headCount)
	}

	return weights, graphSize
}