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

import (
	"log/slog"
5
6
	"strconv"
	"strings"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
7
8
9
10
11
12
13
14
15

	"github.com/ollama/ollama/api"
	"github.com/ollama/ollama/format"
	"github.com/ollama/ollama/gpu"
)

// This algorithm looks for a complete fit to determine if we need to unload other models
func PredictServerFit(allGpus gpu.GpuInfoList, ggml *GGML, adapters, projectors []string, opts api.Options) (bool, uint64) {
	// Split up the GPUs by type and try them
16
	var estimatedVRAM uint64
Daniel Hiltgen's avatar
Daniel Hiltgen committed
17
18
	for _, gpus := range allGpus.ByLibrary() {
		var layerCount int
19
20
		estimate := EstimateGPULayers(gpus, ggml, projectors, opts)
		layerCount, estimatedVRAM = estimate.Layers, estimate.VRAMSize
Daniel Hiltgen's avatar
Daniel Hiltgen committed
21
22
23
24
25
26
27
28
29
30
31
32
33
		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
}

34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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
52
53
54
55
56
57
58
59
60
61
62
63

	// 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
64
65
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
66
// 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
67
// The GPUs provided must all be the same Library
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
func EstimateGPULayers(gpus []gpu.GpuInfo, ggml *GGML, projectors []string, opts api.Options) MemoryEstimate {
	// 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
	var projectorSize uint64

	// Conditional output size on GPU 0
	var memoryLayerOutput uint64

Daniel Hiltgen's avatar
Daniel Hiltgen committed
84
85
	// The sizes of a layer
	var layerSize uint64
Daniel Hiltgen's avatar
Daniel Hiltgen committed
86

87
88
89
90
91
92
93
94
95
96
97
98
99
100
	// 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

	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
101
102

	for _, projector := range projectors {
103
		projectorSize += projectorMemoryRequirements(projector)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
104
105
106
107
108

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

Michael Yang's avatar
Michael Yang committed
109
	layers := ggml.Tensors().Layers()
Michael Yang's avatar
typo  
Michael Yang committed
110
111
	// add one layer worth of memory as a buffer
	if blk0, ok := layers["blk.0"]; ok {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
112
113
114
		layerSize = blk0.size()
	} else {
		slog.Warn("model missing blk.0 layer size")
Michael Yang's avatar
typo  
Michael Yang committed
115
	}
Michael Yang's avatar
Michael Yang committed
116

Daniel Hiltgen's avatar
Daniel Hiltgen committed
117
118
119
	// fp16 k,v = (1 (k) + 1 (v)) * sizeof(float16) * n_ctx * n_layer * n_embd / n_head * n_head_kv
	var kv uint64 = 2 * 2 * uint64(opts.NumCtx) * ggml.KV().BlockCount() * ggml.KV().EmbeddingLength() / ggml.KV().HeadCount() * ggml.KV().HeadCountKV()

Daniel Hiltgen's avatar
Daniel Hiltgen committed
120
121
122
	// KV is proportional to the number of layers
	layerSize += kv / ggml.KV().BlockCount()

123
	graphPartialOffload, graphFullOffload = ggml.GraphSize(uint64(opts.NumCtx), uint64(min(opts.NumCtx, opts.NumBatch)))
Daniel Hiltgen's avatar
Daniel Hiltgen committed
124
125
126
127
128
129
130
	if graphPartialOffload == 0 {
		graphPartialOffload = ggml.KV().GQA() * kv / 6
	}
	if graphFullOffload == 0 {
		graphFullOffload = graphPartialOffload
	}

131
132
133
	// on metal there's no partial offload overhead
	if gpus[0].Library == "metal" {
		graphPartialOffload = graphFullOffload
Daniel Hiltgen's avatar
Daniel Hiltgen committed
134
135
136
	} else if len(gpus) > 1 {
		// multigpu should always use the partial graph size
		graphFullOffload = graphPartialOffload
137
138
	}

139
140
141
142
143
144
145
	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()
Michael Yang's avatar
Michael Yang committed
146
147
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
148
	// Output layer handled at the end if we have space
149
150
151
	gpuZeroOverhead := projectorSize

	// 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
152
	var layerCount int
153
154
155
156
157
158
159
160
161
162
163
164
165
	layerCounts := make([]int, len(gpus))
	gpuAllocations := make([]uint64, len(gpus))
	type gs struct {
		i int
		g *gpu.GpuInfo
	}
	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
Daniel Hiltgen's avatar
Daniel Hiltgen committed
166
		if gpus[i].FreeMemory < gzo+max(graphPartialOffload, graphFullOffload)+gpus[i].MinimumMemory+2*layerSize {
167
168
169
170
			slog.Debug("gpu has too little memory to allocate any layers", "gpu", gpus[i])
			continue
		}
		gpusWithSpace = append(gpusWithSpace, gs{i, &gpus[i]})
Daniel Hiltgen's avatar
Daniel Hiltgen committed
171
		gpuAllocations[i] += gpus[i].MinimumMemory + layerSize // We hold off on graph until we know partial vs. full
172
173
174
175
176
177
178
179
	}

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

Daniel Hiltgen's avatar
Daniel Hiltgen committed
180
	// For all the layers, find where they can fit on the GPU(s)
Michael Yang's avatar
lint  
Michael Yang committed
181
	for i := range int(ggml.KV().BlockCount()) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
182
		memoryWeights += layerSize
Daniel Hiltgen's avatar
Daniel Hiltgen committed
183

184
185
186
187
188
189
190
191
192
		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)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
193
194
			if g.g.FreeMemory > used+layerSize {
				gpuAllocations[g.i] += layerSize
195
				layerCounts[g.i]++
Michael Yang's avatar
typo  
Michael Yang committed
196
				layerCount++
197
198
199
				break
			} else {
				gpusWithSpace = append(gpusWithSpace[:i%j], gpusWithSpace[i%j+1:]...)
Michael Yang's avatar
typo  
Michael Yang committed
200
			}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
201
		}
202
203
204
205
206
	}
	if layerCount >= int(ggml.KV().BlockCount()) {
		fullyLoaded = true
	} else {
		for i := layerCount; i < int(ggml.KV().BlockCount()); i++ {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
207
			overflow += layerSize
208
209
		}
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
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
214
215
216
217
218
219
220
221
222
		for j := len(gpusWithSpace); j > 0; j-- {
			g := gpusWithSpace[layerCount%j]
			used := gpuAllocations[g.i] + max(graphPartialOffload, graphFullOffload)
			if g.g.FreeMemory > used+memoryLayerOutput {
				gpuAllocations[g.i] += memoryLayerOutput
				layerCounts[g.i]++
				layerCount++
				break
			}
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
223

224
225
226
227
		if layerCount < int(ggml.KV().BlockCount())+1 {
			fullyLoaded = false
			overflow += memoryLayerOutput
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
228
229
	}

230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
	// 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
245
246
	}

247
248
249
250
	// Summaries for the log
	var memoryRequiredPartial, memoryRequiredTotal uint64
	for i := range gpuAllocations {
		memoryRequiredPartial += gpuAllocations[i]
Daniel Hiltgen's avatar
Daniel Hiltgen committed
251
	}
252
	memoryRequiredTotal = memoryRequiredPartial + overflow
Daniel Hiltgen's avatar
Daniel Hiltgen committed
253

254
255
256
257
258
259
260
261
262
263
264
265
	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
266

267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
	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,
	}

	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() {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
303
	slog.Info(
304
		"offload to "+m.inferenceLibrary,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
305
306
		slog.Group(
			"layers",
Michael Yang's avatar
Michael Yang committed
307
			// requested number of layers to offload
308
			"requested", m.layersRequested,
309
			// The number of layers the model has (including output)
310
			"model", m.layersModel,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
311
			// estimated number of layers that can be offloaded
312
313
314
			"offload", m.Layers,
			// multi-gpu split for tensors
			"split", m.TensorSplit,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
315
316
317
		),
		slog.Group(
			"memory",
318
			// memory available by GPU for offloading
319
			"available", m.availableList,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
320
321
322
			slog.Group(
				"required",
				// memory required for full offloading
323
				"full", format.HumanBytes2(m.TotalSize),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
324
				// memory required to offload layers.estimate layers
325
				"partial", format.HumanBytes2(m.VRAMSize),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
326
				// memory of KV cache
327
				"kv", format.HumanBytes2(m.kv),
328
				// Allocations across the GPUs
329
				"allocations", m.allocationsList,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
330
331
332
333
			),
			slog.Group(
				"weights",
				// memory of the weights
334
				"total", format.HumanBytes2(m.memoryWeights),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
335
				// memory of repeating layers
336
				"repeating", format.HumanBytes2(m.memoryWeights-m.memoryLayerOutput),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
337
				// memory of non-repeating layers
338
				"nonrepeating", format.HumanBytes2(m.memoryLayerOutput),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
339
340
341
342
			),
			slog.Group(
				"graph",
				// memory of graph when fully offloaded
343
				"full", format.HumanBytes2(m.graphFullOffload),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
344
				// memory of graph when not fully offloaded
345
				"partial", format.HumanBytes2(m.graphPartialOffload),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
346
347
348
349
			),
		),
	)
}