memory.go 12.6 KB
Newer Older
mashun1's avatar
v1  
mashun1 committed
1
2
3
4
5
package llm

import (
	"fmt"
	"log/slog"
xuxzh1's avatar
update  
xuxzh1 committed
6
	"os"
xuxzh1's avatar
init  
xuxzh1 committed
7
8
	"strconv"
	"strings"
mashun1's avatar
v1  
mashun1 committed
9
10

	"github.com/ollama/ollama/api"
xuxzh1's avatar
update  
xuxzh1 committed
11
12
	"github.com/ollama/ollama/discover"
	"github.com/ollama/ollama/envconfig"
mashun1's avatar
v1  
mashun1 committed
13
14
15
16
	"github.com/ollama/ollama/format"
)

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

xuxzh1's avatar
init  
xuxzh1 committed
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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

	// 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
xuxzh1's avatar
update  
xuxzh1 committed
67
68

	projectorWeights, projectorGraph uint64
xuxzh1's avatar
init  
xuxzh1 committed
69
70
}

mashun1's avatar
v1  
mashun1 committed
71
72
// Given a model and one or more GPU targets, predict how many layers and bytes we can load, and the total size
// The GPUs provided must all be the same Library
xuxzh1's avatar
update  
xuxzh1 committed
73
func EstimateGPULayers(gpus []discover.GpuInfo, ggml *GGML, projectors []string, opts api.Options) MemoryEstimate {
xuxzh1's avatar
init  
xuxzh1 committed
74
75
76
77
78
79
80
81
82
83
	// 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
xuxzh1's avatar
update  
xuxzh1 committed
84
85
	var projectorWeights uint64
	var projectorGraph uint64
xuxzh1's avatar
init  
xuxzh1 committed
86
87
88
89
90
91
92
93
94

	// Conditional output size on GPU 0
	var memoryLayerOutput uint64

	// The sizes of a layer
	var layerSize uint64

	// The sum of all the layer sizes (just for logging)
	var memoryWeights uint64
mashun1's avatar
v1  
mashun1 committed
95

xuxzh1's avatar
init  
xuxzh1 committed
96
97
	// True if all the layers are loaded
	var fullyLoaded bool
mashun1's avatar
v1  
mashun1 committed
98

xuxzh1's avatar
init  
xuxzh1 committed
99
100
101
	// Overflow that didn't fit into the GPU
	var overflow uint64

xuxzh1's avatar
update  
xuxzh1 committed
102
	overhead := envconfig.GpuOverhead()
xuxzh1's avatar
init  
xuxzh1 committed
103
104
105
106
107
	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)
mashun1's avatar
v1  
mashun1 committed
108
109

	for _, projector := range projectors {
xuxzh1's avatar
update  
xuxzh1 committed
110
111
112
		weight, graph := projectorMemoryRequirements(projector)
		projectorWeights += weight
		projectorGraph += graph
mashun1's avatar
v1  
mashun1 committed
113
114
115
116
117
118
119
120

		// multimodal models require at least 2048 context
		opts.NumCtx = max(opts.NumCtx, 2048)
	}

	layers := ggml.Tensors().Layers()
	// add one layer worth of memory as a buffer
	if blk0, ok := layers["blk.0"]; ok {
xuxzh1's avatar
init  
xuxzh1 committed
121
122
123
		layerSize = blk0.size()
	} else {
		slog.Warn("model missing blk.0 layer size")
mashun1's avatar
v1  
mashun1 committed
124
125
	}

xuxzh1's avatar
update  
xuxzh1 committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
	fa := envconfig.FlashAttention() &&
		discover.GetGPUInfo().FlashAttentionSupported() &&
		ggml.SupportsFlashAttention()

	var kvct string
	if fa {
		requested := strings.ToLower(envconfig.KvCacheType())
		if requested != "" && ggml.SupportsKVCacheType(requested) {
			kvct = requested
		}
	}

	kv, graphPartialOffload, graphFullOffload := ggml.GraphSize(uint64(opts.NumCtx), uint64(min(opts.NumCtx, opts.NumBatch)), kvct)

	// KV is proportional to the number of layers
	layerSize += kv / ggml.KV().BlockCount()

mashun1's avatar
v1  
mashun1 committed
143
144
145
146
147
148
149
150
151
152
	if graphPartialOffload == 0 {
		graphPartialOffload = ggml.KV().GQA() * kv / 6
	}
	if graphFullOffload == 0 {
		graphFullOffload = graphPartialOffload
	}

	// on metal there's no partial offload overhead
	if gpus[0].Library == "metal" {
		graphPartialOffload = graphFullOffload
xuxzh1's avatar
init  
xuxzh1 committed
153
154
155
	} else if len(gpus) > 1 {
		// multigpu should always use the partial graph size
		graphFullOffload = graphPartialOffload
mashun1's avatar
v1  
mashun1 committed
156
157
158
159
160
161
162
163
164
165
166
	}

	if layer, ok := layers["output_norm"]; ok {
		memoryLayerOutput += layer.size()
	}
	if layer, ok := layers["output"]; ok {
		memoryLayerOutput += layer.size()
	} else if layer, ok := layers["token_embd"]; ok {
		memoryLayerOutput += layer.size()
	}

xuxzh1's avatar
init  
xuxzh1 committed
167
	// Output layer handled at the end if we have space
xuxzh1's avatar
update  
xuxzh1 committed
168
	gpuZeroOverhead := projectorWeights + projectorGraph
mashun1's avatar
v1  
mashun1 committed
169

xuxzh1's avatar
init  
xuxzh1 committed
170
	// Reduce set of GPUs to only those that have sufficient space to fit overhead and at least one layer
mashun1's avatar
v1  
mashun1 committed
171
	var layerCount int
xuxzh1's avatar
init  
xuxzh1 committed
172
173
174
175
	layerCounts := make([]int, len(gpus))
	gpuAllocations := make([]uint64, len(gpus))
	type gs struct {
		i int
xuxzh1's avatar
update  
xuxzh1 committed
176
		g *discover.GpuInfo
xuxzh1's avatar
init  
xuxzh1 committed
177
178
179
180
181
182
183
184
	}
	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
xuxzh1's avatar
update  
xuxzh1 committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
		if (gpus[i].FreeMemory - overhead) < gzo+max(graphPartialOffload, graphFullOffload)+gpus[i].MinimumMemory+2*layerSize {
			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),
			)
xuxzh1's avatar
init  
xuxzh1 committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
			continue
		}
		gpusWithSpace = append(gpusWithSpace, gs{i, &gpus[i]})
		gpuAllocations[i] += gpus[i].MinimumMemory + layerSize // We hold off on graph until we know partial vs. full
	}

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

	// For all the layers, find where they can fit on the GPU(s)
	for i := range int(ggml.KV().BlockCount()) {
		// Some models have inconsistent layer sizes
mashun1's avatar
v1  
mashun1 committed
216
		if blk, ok := layers[fmt.Sprintf("blk.%d", i)]; ok {
xuxzh1's avatar
init  
xuxzh1 committed
217
218
219
220
			layerSize = blk.size()
			layerSize += kv / ggml.KV().BlockCount()
		}
		memoryWeights += layerSize
mashun1's avatar
v1  
mashun1 committed
221

xuxzh1's avatar
init  
xuxzh1 committed
222
223
224
225
		if opts.NumGPU >= 0 && layerCount >= opts.NumGPU {
			// Stop allocating on GPU(s) once we hit the users target NumGPU
			continue
		}
mashun1's avatar
v1  
mashun1 committed
226

xuxzh1's avatar
init  
xuxzh1 committed
227
228
229
230
		// 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)
xuxzh1's avatar
update  
xuxzh1 committed
231
			if (g.g.FreeMemory - overhead) > used+layerSize {
xuxzh1's avatar
init  
xuxzh1 committed
232
233
				gpuAllocations[g.i] += layerSize
				layerCounts[g.i]++
mashun1's avatar
v1  
mashun1 committed
234
				layerCount++
xuxzh1's avatar
init  
xuxzh1 committed
235
236
237
				break
			} else {
				gpusWithSpace = append(gpusWithSpace[:i%j], gpusWithSpace[i%j+1:]...)
mashun1's avatar
v1  
mashun1 committed
238
239
240
			}
		}
	}
xuxzh1's avatar
init  
xuxzh1 committed
241
242
243
244
245
246
247
248
249
250
251
252
253
	if layerCount >= int(ggml.KV().BlockCount()) {
		fullyLoaded = true
	} else {
		for i := layerCount; i < int(ggml.KV().BlockCount()); i++ {
			overflow += layerSize
		}
	}

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

xuxzh1's avatar
init  
xuxzh1 committed
262
263
264
265
		if layerCount < int(ggml.KV().BlockCount())+1 {
			fullyLoaded = false
			overflow += memoryLayerOutput
		}
mashun1's avatar
v1  
mashun1 committed
266
267
	}

xuxzh1's avatar
init  
xuxzh1 committed
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
	// 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
mashun1's avatar
v1  
mashun1 committed
283
284
	}

xuxzh1's avatar
init  
xuxzh1 committed
285
286
287
288
289
290
	// Summaries for the log
	var memoryRequiredPartial, memoryRequiredTotal uint64
	for i := range gpuAllocations {
		memoryRequiredPartial += gpuAllocations[i]
	}
	memoryRequiredTotal = memoryRequiredPartial + overflow
mashun1's avatar
v1  
mashun1 committed
291

xuxzh1's avatar
init  
xuxzh1 committed
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
	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))
	}

	estimate := MemoryEstimate{
		TotalSize: memoryRequiredTotal,
		Layers:    0,
		Graph:     0,
		VRAMSize:  0,
		GPUSizes:  []uint64{},

		inferenceLibrary:    gpus[0].Library,
		layersRequested:     opts.NumGPU,
		layersModel:         int(ggml.KV().BlockCount()) + 1,
		availableList:       availableList,
		kv:                  kv,
		allocationsList:     allocationsList,
		memoryWeights:       memoryWeights,
		memoryLayerOutput:   memoryLayerOutput,
		graphFullOffload:    graphFullOffload,
		graphPartialOffload: graphPartialOffload,
xuxzh1's avatar
update  
xuxzh1 committed
322
323
		projectorWeights:    projectorWeights,
		projectorGraph:      projectorGraph,
xuxzh1's avatar
init  
xuxzh1 committed
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
	}

	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
}

func (m MemoryEstimate) log() {
xuxzh1's avatar
update  
xuxzh1 committed
343
344
345
346
347
348
349
350
351
352
353
354
355
356
	overhead := envconfig.GpuOverhead()

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

	log.Info(
xuxzh1's avatar
init  
xuxzh1 committed
357
		"offload to "+m.inferenceLibrary,
mashun1's avatar
v1  
mashun1 committed
358
359
360
		slog.Group(
			"layers",
			// requested number of layers to offload
xuxzh1's avatar
init  
xuxzh1 committed
361
362
363
			"requested", m.layersRequested,
			// The number of layers the model has (including output)
			"model", m.layersModel,
mashun1's avatar
v1  
mashun1 committed
364
			// estimated number of layers that can be offloaded
xuxzh1's avatar
init  
xuxzh1 committed
365
366
367
			"offload", m.Layers,
			// multi-gpu split for tensors
			"split", m.TensorSplit,
mashun1's avatar
v1  
mashun1 committed
368
369
370
		),
		slog.Group(
			"memory",
xuxzh1's avatar
init  
xuxzh1 committed
371
372
			// memory available by GPU for offloading
			"available", m.availableList,
xuxzh1's avatar
update  
xuxzh1 committed
373
			"gpu_overhead", format.HumanBytes2(overhead),
mashun1's avatar
v1  
mashun1 committed
374
375
376
			slog.Group(
				"required",
				// memory required for full offloading
xuxzh1's avatar
init  
xuxzh1 committed
377
				"full", format.HumanBytes2(m.TotalSize),
mashun1's avatar
v1  
mashun1 committed
378
				// memory required to offload layers.estimate layers
xuxzh1's avatar
init  
xuxzh1 committed
379
				"partial", format.HumanBytes2(m.VRAMSize),
mashun1's avatar
v1  
mashun1 committed
380
				// memory of KV cache
xuxzh1's avatar
init  
xuxzh1 committed
381
382
383
				"kv", format.HumanBytes2(m.kv),
				// Allocations across the GPUs
				"allocations", m.allocationsList,
mashun1's avatar
v1  
mashun1 committed
384
385
386
387
			),
			slog.Group(
				"weights",
				// memory of the weights
xuxzh1's avatar
init  
xuxzh1 committed
388
				"total", format.HumanBytes2(m.memoryWeights),
mashun1's avatar
v1  
mashun1 committed
389
				// memory of repeating layers
xuxzh1's avatar
init  
xuxzh1 committed
390
				"repeating", format.HumanBytes2(m.memoryWeights-m.memoryLayerOutput),
mashun1's avatar
v1  
mashun1 committed
391
				// memory of non-repeating layers
xuxzh1's avatar
init  
xuxzh1 committed
392
				"nonrepeating", format.HumanBytes2(m.memoryLayerOutput),
mashun1's avatar
v1  
mashun1 committed
393
394
395
396
			),
			slog.Group(
				"graph",
				// memory of graph when fully offloaded
xuxzh1's avatar
init  
xuxzh1 committed
397
				"full", format.HumanBytes2(m.graphFullOffload),
mashun1's avatar
v1  
mashun1 committed
398
				// memory of graph when not fully offloaded
xuxzh1's avatar
init  
xuxzh1 committed
399
				"partial", format.HumanBytes2(m.graphPartialOffload),
mashun1's avatar
v1  
mashun1 committed
400
401
402
403
			),
		),
	)
}
xuxzh1's avatar
update  
xuxzh1 committed
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452

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

	ggml, _, err := DecodeGGML(file, 0)
	if err != nil {
		return 0, 0
	}

	for _, layer := range ggml.Tensors().Layers() {
		weights += layer.size()
	}

	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"))
		if _, ok := ggml.Tensors().Layers()["v"]["class_embd"]; ok {
			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
}