server.go 52.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package llm

import (
	"bufio"
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"log/slog"
	"math/rand"
	"net"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
20
	"slices"
Jesse Gross's avatar
Jesse Gross committed
21
	"sort"
22
23
	"strconv"
	"strings"
24
	"sync"
25
26
	"time"

Daniel Hiltgen's avatar
Daniel Hiltgen committed
27
28
	"golang.org/x/sync/semaphore"

29
	"github.com/ollama/ollama/api"
30
	"github.com/ollama/ollama/discover"
31
	"github.com/ollama/ollama/envconfig"
32
	"github.com/ollama/ollama/format"
Michael Yang's avatar
Michael Yang committed
33
	"github.com/ollama/ollama/fs/ggml"
34
	"github.com/ollama/ollama/llama"
35
	"github.com/ollama/ollama/logutil"
Jesse Gross's avatar
Jesse Gross committed
36
	"github.com/ollama/ollama/ml"
37
	"github.com/ollama/ollama/model"
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 filteredEnv []string

func (e filteredEnv) LogValue() slog.Value {
	var attrs []slog.Attr
	for _, env := range e {
		if key, value, ok := strings.Cut(env, "="); ok {
			switch {
			case strings.HasPrefix(key, "OLLAMA_"),
				strings.HasPrefix(key, "CUDA_"),
				strings.HasPrefix(key, "ROCR_"),
				strings.HasPrefix(key, "ROCM_"),
				strings.HasPrefix(key, "HIP_"),
				strings.HasPrefix(key, "GPU_"),
				strings.HasPrefix(key, "HSA_"),
				strings.HasPrefix(key, "GGML_"),
				slices.Contains([]string{
					"PATH",
					"LD_LIBRARY_PATH",
					"DYLD_LIBRARY_PATH",
				}, key):
				attrs = append(attrs, slog.String(key, value))
			}
		}
	}
	return slog.GroupValue(attrs...)
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
67
type LlamaServer interface {
Jesse Gross's avatar
Jesse Gross committed
68
69
	ModelPath() string
	Load(ctx context.Context, gpus discover.GpuInfoList, requireFull bool) error
Daniel Hiltgen's avatar
Daniel Hiltgen committed
70
71
72
	Ping(ctx context.Context) error
	WaitUntilRunning(ctx context.Context) error
	Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error
73
	Embedding(ctx context.Context, input string) ([]float32, error)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
74
75
76
	Tokenize(ctx context.Context, content string) ([]int, error)
	Detokenize(ctx context.Context, tokens []int) (string, error)
	Close() error
Jesse Gross's avatar
Jesse Gross committed
77
78
79
	VRAMSize() uint64 // Total VRAM across all GPUs
	TotalSize() uint64
	VRAMByGPU(gpuID string) uint64
80
	Pid() int
Daniel Hiltgen's avatar
Daniel Hiltgen committed
81
82
}

Jesse Gross's avatar
Jesse Gross committed
83
// llmServer is an instance of a runner hosting a single model
Daniel Hiltgen's avatar
Daniel Hiltgen committed
84
type llmServer struct {
85
86
87
88
89
90
	port        int
	cmd         *exec.Cmd
	done        chan error // Channel to signal when the process exits
	status      *StatusWriter
	options     api.Options
	numParallel int
91
	modelPath   string
92

Jesse Gross's avatar
Jesse Gross committed
93
94
	loadRequest LoadRequest // Parameters used to initialize the runner

95
96
97
	// llamaModel is an instance of the cgo llama.cpp model definition
	// nil if this server is running the new engine
	llamaModel     *llama.Model
Jesse Gross's avatar
Jesse Gross committed
98
	llamaModelLock *sync.Mutex
99
100
101
102

	// textProcessor handles text encoding/decoding for the model in the Ollama engine
	// nil if this server is running the llama.cpp based engine
	textProcessor model.TextProcessor
Daniel Hiltgen's avatar
Daniel Hiltgen committed
103

Jesse Gross's avatar
Jesse Gross committed
104
105
	totalLayers  uint64
	loadStart    time.Time // Record how long it took the model to load
106
	loadProgress float32
Daniel Hiltgen's avatar
Daniel Hiltgen committed
107
108

	sem *semaphore.Weighted
109
110
}

Jesse Gross's avatar
Jesse Gross committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
type llamaServer struct {
	llmServer

	ggml     *ggml.GGML
	gpus     discover.GpuInfoList // The set of GPUs covered by the memory estimate
	estimate MemoryEstimate
}

type ollamaServer struct {
	llmServer

	mem *ml.BackendMemory
}

125
126
127
128
129
// LoadModel will load a model from disk. The model must be in the GGML format.
//
// It collects array values for arrays with a size less than or equal to
// maxArraySize. If maxArraySize is 0, the default value of 1024 is used. If
// the maxArraySize is negative, all arrays are collected.
Michael Yang's avatar
Michael Yang committed
130
func LoadModel(model string, maxArraySize int) (*ggml.GGML, error) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
131
132
133
134
	if _, err := os.Stat(model); err != nil {
		return nil, err
	}

135
136
137
138
139
140
	f, err := os.Open(model)
	if err != nil {
		return nil, err
	}
	defer f.Close()

141
	ggml, err := ggml.Decode(f, maxArraySize)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
142
143
	return ggml, err
}
144

Daniel Hiltgen's avatar
Daniel Hiltgen committed
145
// NewLlamaServer will run a server for the given GPUs
146
func NewLlamaServer(gpus discover.GpuInfoList, modelPath string, f *ggml.GGML, adapters, projectors []string, opts api.Options, numParallel int) (LlamaServer, error) {
Jesse Gross's avatar
Jesse Gross committed
147
148
149
150
151
152
153
154
155
	var llamaModel *llama.Model
	var textProcessor model.TextProcessor
	var err error
	if envconfig.NewEngine() || f.KV().OllamaEngineRequired() {
		textProcessor, err = model.NewTextProcessor(modelPath)
		if err != nil {
			// To prepare for opt-out mode, instead of treating this as an error, we fallback to the old runner
			slog.Debug("model not yet supported by Ollama engine, switching to compatibility mode", "model", modelPath, "error", err)
		}
156
	}
Jesse Gross's avatar
Jesse Gross committed
157
158
159
160
161
	if textProcessor == nil {
		llamaModel, err = llama.LoadModelFromFile(modelPath, llama.ModelParams{VocabOnly: true})
		if err != nil {
			return nil, err
		}
162
163
	}

Jesse Gross's avatar
Jesse Gross committed
164
165
166
	newEstimates := textProcessor != nil && envconfig.NewMemoryEstimates()
	if newEstimates {
		slog.Info("enabling new memory estimates")
167
168
	}

Jesse Gross's avatar
Jesse Gross committed
169
170
171
172
173
	// Verify the requested context size is <= the model training size
	trainCtx := f.KV().ContextLength()
	if opts.NumCtx > int(trainCtx) && trainCtx > 0 {
		slog.Warn("requested context size too large for model", "num_ctx", opts.NumCtx, "n_ctx_train", trainCtx)
		opts.NumCtx = int(trainCtx)
174
175
	}

Jesse Gross's avatar
Jesse Gross committed
176
	loadRequest := LoadRequest{LoraPath: adapters, KvSize: opts.NumCtx * numParallel, BatchSize: opts.NumBatch, Parallel: numParallel, MultiUserCache: envconfig.MultiUserCache()}
177

Jesse Gross's avatar
Jesse Gross committed
178
179
180
181
182
	defaultThreads := discover.GetSystemInfo().GetOptimalThreadCount()
	if opts.NumThread > 0 {
		loadRequest.NumThreads = opts.NumThread
	} else if defaultThreads > 0 {
		loadRequest.NumThreads = defaultThreads
183
	}
Michael Yang's avatar
Michael Yang committed
184

Jesse Gross's avatar
Jesse Gross committed
185
	// TODO - NUMA support currently doesn't work properly
186
187

	if opts.MainGPU > 0 {
Jesse Gross's avatar
Jesse Gross committed
188
		loadRequest.MainGPU = opts.MainGPU
189
190
	}

Jesse Gross's avatar
Jesse Gross committed
191
192
	if len(projectors) > 0 && llamaModel != nil {
		loadRequest.ProjectorPath = projectors[0]
193
194
	}

Jesse Gross's avatar
Jesse Gross committed
195
196
	// This will disable flash attention unless all GPUs on the system support it, even if we end up selecting a subset
	// that can handle it.
197
	fa := envconfig.FlashAttention()
198
199
200
201
202
	if f.FlashAttention() {
		slog.Info("model wants flash attention")
		fa = true
	}

203
204
205
206
	if fa && !gpus.FlashAttentionSupported() {
		slog.Warn("flash attention enabled but not supported by gpu")
		fa = false
	}
Sam's avatar
Sam committed
207

Michael Yang's avatar
Michael Yang committed
208
	if fa && !f.SupportsFlashAttention() {
209
210
211
212
		slog.Warn("flash attention enabled but not supported by model")
		fa = false
	}

213
	kvct := strings.ToLower(envconfig.KvCacheType())
214
215
216

	if fa {
		slog.Info("enabling flash attention")
Jesse Gross's avatar
Jesse Gross committed
217
		loadRequest.FlashAttention = true
218
219
220

		// Flash Attention also supports kv cache quantization
		// Enable if the requested and kv cache type is supported by the model
Michael Yang's avatar
Michael Yang committed
221
		if kvct != "" && f.SupportsKVCacheType(kvct) {
Jesse Gross's avatar
Jesse Gross committed
222
			loadRequest.KvCacheType = kvct
223
224
		} else {
			slog.Warn("kv cache type not supported by model", "type", kvct)
Sam's avatar
Sam committed
225
		}
226
227
228
	} else if kvct != "" && kvct != "f16" {
		slog.Warn("quantized kv cache requested but flash attention disabled", "type", kvct)
	}
229

Jesse Gross's avatar
Jesse Gross committed
230
	availableLibs := make(map[string]string)
231
232
	if entries, err := os.ReadDir(discover.LibOllamaPath); err == nil {
		for _, entry := range entries {
Jesse Gross's avatar
Jesse Gross committed
233
			availableLibs[entry.Name()] = filepath.Join(discover.LibOllamaPath, entry.Name())
Michael Yang's avatar
Michael Yang committed
234
235
236
		}
	}

Jesse Gross's avatar
Jesse Gross committed
237
238
239
240
241
	var gpuLibs []string
	for _, gpu := range gpus {
		gpuLibs = append(gpuLibs, gpu.RunnerName())
	}

Michael Yang's avatar
Michael Yang committed
242
	requested := envconfig.LLMLibrary()
Jesse Gross's avatar
Jesse Gross committed
243
	if availableLibs[requested] != "" {
Michael Yang's avatar
Michael Yang committed
244
		slog.Info("using requested gpu library", "requested", requested)
Jesse Gross's avatar
Jesse Gross committed
245
		gpuLibs = []string{requested}
Michael Yang's avatar
Michael Yang committed
246
247
248
	}

	var compatible []string
Jesse Gross's avatar
Jesse Gross committed
249
250
251
252
253
254
255
256
257
258
259
260
261
	for _, gpuLib := range gpuLibs {
		var matchingLibs []string
		for k := range availableLibs {
			// exact match first
			if k == gpuLib {
				matchingLibs = append([]string{k}, matchingLibs...)
				continue
			}

			// then match the family (e.g. 'cuda')
			if strings.Split(k, "_")[0] == strings.Split(gpuLib, "_")[0] {
				matchingLibs = append(matchingLibs, k)
			}
262
		}
263

Jesse Gross's avatar
Jesse Gross committed
264
265
		if len(matchingLibs) > 0 {
			compatible = append(compatible, matchingLibs[0])
Daniel Hiltgen's avatar
Daniel Hiltgen committed
266
		}
Michael Yang's avatar
Michael Yang committed
267
	}
Jesse Gross's avatar
Jesse Gross committed
268

269
270
271
272
273
274
275
276
277
	exe, err := os.Executable()
	if err != nil {
		return nil, fmt.Errorf("unable to lookup executable path: %w", err)
	}

	if eval, err := filepath.EvalSymlinks(exe); err == nil {
		exe = eval
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
278
	// iterate through compatible GPU libraries such as 'cuda_v12', 'rocm', etc.
Michael Yang's avatar
Michael Yang committed
279
280
281
	// adding each library's respective path to the LD_LIBRARY_PATH, until finally running
	// without any LD_LIBRARY_PATH flags
	for {
282
283
284
285
286
287
288
289
290
		port := 0
		if a, err := net.ResolveTCPAddr("tcp", "localhost:0"); err == nil {
			var l *net.TCPListener
			if l, err = net.ListenTCP("tcp", a); err == nil {
				port = l.Addr().(*net.TCPAddr).Port
				l.Close()
			}
		}
		if port == 0 {
291
			slog.Debug("ResolveTCPAddr failed, using random port")
292
293
			port = rand.Intn(65535-49152) + 49152 // get a random port in the ephemeral range
		}
Jesse Gross's avatar
Jesse Gross committed
294
		params := []string{"runner"}
295
296
297
		if textProcessor != nil {
			// New engine
			// TODO - if we have failure to load scenarios, add logic to retry with the old runner
Jesse Gross's avatar
Jesse Gross committed
298
			params = append(params, "--ollama-engine")
Jesse Gross's avatar
Jesse Gross committed
299
		}
Jesse Gross's avatar
Jesse Gross committed
300
301
		params = append(params, "--model", modelPath)
		params = append(params, "--port", strconv.Itoa(port))
302

303
304
305
		var pathEnv string
		switch runtime.GOOS {
		case "windows":
306
			pathEnv = "PATH"
307
308
309
310
		case "darwin":
			pathEnv = "DYLD_LIBRARY_PATH"
		default:
			pathEnv = "LD_LIBRARY_PATH"
311
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
312

313
314
315
		// Note: we always put our dependency paths first
		// since these are the exact version we compiled/linked against
		libraryPaths := []string{discover.LibOllamaPath}
316
		if libraryPath, ok := os.LookupEnv(pathEnv); ok {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
317
			libraryPaths = append(libraryPaths, filepath.SplitList(libraryPath)...)
318
319
		}

320
		ggmlPaths := []string{discover.LibOllamaPath}
Jesse Gross's avatar
Jesse Gross committed
321
322
		for _, c := range compatible {
			if libpath, ok := availableLibs[c]; ok {
Michael Yang's avatar
Michael Yang committed
323
				slog.Debug("adding gpu library", "path", libpath)
324
				libraryPaths = append([]string{libpath}, libraryPaths...)
325
				ggmlPaths = append(ggmlPaths, libpath)
Michael Yang's avatar
Michael Yang committed
326
327
328
			}
		}

Jesse Gross's avatar
Jesse Gross committed
329
330
331
332
333
		for _, gpu := range gpus {
			if gpu.DependencyPath != nil {
				slog.Debug("adding gpu dependency paths", "paths", gpu.DependencyPath)
				libraryPaths = append(gpu.DependencyPath, libraryPaths...)
			}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
334
335
		}

Michael Yang's avatar
Michael Yang committed
336
337
338
		// finally, add the root library path
		libraryPaths = append(libraryPaths, discover.LibOllamaPath)

Jesse Gross's avatar
Jesse Gross committed
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
		s := llmServer{
			port:           port,
			cmd:            exec.Command(exe, params...),
			status:         NewStatusWriter(os.Stderr),
			options:        opts,
			modelPath:      modelPath,
			loadRequest:    loadRequest,
			llamaModel:     llamaModel,
			llamaModelLock: &sync.Mutex{},
			textProcessor:  textProcessor,
			numParallel:    numParallel,
			sem:            semaphore.NewWeighted(int64(numParallel)),
			totalLayers:    f.KV().BlockCount() + 1,
			loadStart:      time.Now(),
			done:           make(chan error, 1),
354
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
355

356
		s.cmd.Env = os.Environ()
357
358
		s.cmd.Stdout = os.Stdout
		s.cmd.Stderr = s.status
359
		s.cmd.SysProcAttr = LlamaServerSysProcAttr
360

361
362
		s.cmd.Env = append(s.cmd.Env, "OLLAMA_LIBRARY_PATH="+strings.Join(ggmlPaths, string(filepath.ListSeparator)))

363
		envWorkarounds := []string{}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
364
365
366
		for _, gpu := range gpus {
			envWorkarounds = append(envWorkarounds, gpu.EnvWorkarounds...)
		}
367
368
		// Always filter down the set of GPUs in case there are any unsupported devices that might crash
		envWorkarounds = append(envWorkarounds, gpus.GetVisibleDevicesEnv()...)
369
370
		pathEnvVal := strings.Join(libraryPaths, string(filepath.ListSeparator))

Jesse Gross's avatar
Jesse Gross committed
371
		// Update or add the path variable with our adjusted version
372
		pathNeeded := true
373
		envWorkaroundDone := make([]bool, len(envWorkarounds))
374
375
376
377
378
		for i := range s.cmd.Env {
			cmp := strings.SplitN(s.cmd.Env[i], "=", 2)
			if strings.EqualFold(cmp[0], pathEnv) {
				s.cmd.Env[i] = pathEnv + "=" + pathEnvVal
				pathNeeded = false
Daniel Hiltgen's avatar
Daniel Hiltgen committed
379
			} else if len(envWorkarounds) != 0 {
380
381
382
383
384
				for j, kv := range envWorkarounds {
					tmp := strings.SplitN(kv, "=", 2)
					if strings.EqualFold(cmp[0], tmp[0]) {
						s.cmd.Env[i] = kv
						envWorkaroundDone[j] = true
Daniel Hiltgen's avatar
Daniel Hiltgen committed
385
386
					}
				}
387
			}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
388
		}
389
390
		if pathNeeded {
			s.cmd.Env = append(s.cmd.Env, pathEnv+"="+pathEnvVal)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
391
		}
392
393
394
395
396
		for i, done := range envWorkaroundDone {
			if !done {
				s.cmd.Env = append(s.cmd.Env, envWorkarounds[i])
			}
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
397

Jesse Gross's avatar
Jesse Gross committed
398
		slog.Info("starting runner", "cmd", s.cmd)
399
		slog.Debug("subprocess", "", filteredEnv(s.cmd.Env))
400
401

		if err = s.cmd.Start(); err != nil {
Michael Yang's avatar
Michael Yang committed
402
			var msg string
403
404
405
			if s.status != nil && s.status.LastErrMsg != "" {
				msg = s.status.LastErrMsg
			}
Michael Yang's avatar
Michael Yang committed
406
407
			err := fmt.Errorf("error starting runner: %v %s", err, msg)
			if len(compatible) == 0 {
408
409
410
				if llamaModel != nil {
					llama.FreeModel(llamaModel)
				}
Michael Yang's avatar
Michael Yang committed
411
412
413
414
415
				return nil, err
			}

			slog.Warn("unable to start runner with compatible gpu", "error", err, "compatible", compatible)
			compatible = compatible[1:]
416
417
418
			continue
		}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
419
420
		// reap subprocess when it exits
		go func() {
421
422
423
			err := s.cmd.Wait()
			// Favor a more detailed message over the process exit status
			if err != nil && s.status != nil && s.status.LastErrMsg != "" {
Michael Yang's avatar
Michael Yang committed
424
				slog.Error("llama runner terminated", "error", err)
425
426
427
				if strings.Contains(s.status.LastErrMsg, "unknown model") {
					s.status.LastErrMsg = "this model is not supported by your version of Ollama. You may need to upgrade"
				}
Michael Yang's avatar
lint  
Michael Yang committed
428
				s.done <- errors.New(s.status.LastErrMsg)
429
430
431
			} else {
				s.done <- err
			}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
432
433
		}()

Jesse Gross's avatar
Jesse Gross committed
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
		if newEstimates {
			return &ollamaServer{llmServer: s}, nil
		} else {
			return &llamaServer{llmServer: s, ggml: f}, nil
		}
	}
}

func (s *llmServer) ModelPath() string {
	return s.modelPath
}

type LoadOperation int

// The order of these constants are significant because we iterate over the operations. They
// should be in order of increasingly loading the model.
const (
	LoadOperationFit    LoadOperation = iota // Return memory requirements but do not allocate
	LoadOperationAlloc                       // Allocate memory but do not load the weights
	LoadOperationCommit                      // Load weights - further changes cannot be made after this
	LoadOperationClose                       // Close model and free memory
)

func (o LoadOperation) String() string {
	switch o {
	case LoadOperationFit:
		return "fit"
	case LoadOperationAlloc:
		return "alloc"
	case LoadOperationCommit:
		return "commit"
	case LoadOperationClose:
		return "close"
	default:
		return "unknown"
	}
}

type LoadRequest struct {
	Operation LoadOperation

	LoraPath       []string
	Parallel       int
	BatchSize      int
	FlashAttention bool
	KvSize         int
	KvCacheType    string
	NumThreads     int
	GPULayers      ml.GPULayersList
	MultiUserCache bool

	// Legacy fields - not used with the Ollama engine
	ProjectorPath string
	MainGPU       int
	UseMmap       bool
}

type LoadResponse struct {
	Success bool
	Memory  ml.BackendMemory
}

var ErrLoadRequiredFull = errors.New("unable to load full model on GPU")

func (s *llamaServer) Load(ctx context.Context, gpus discover.GpuInfoList, requireFull bool) error {
	systemInfo := discover.GetSystemInfo()
	systemTotalMemory := systemInfo.System.TotalMemory
	systemFreeMemory := systemInfo.System.FreeMemory
	systemSwapFreeMemory := systemInfo.System.FreeSwap
	slog.Info("system memory", "total", format.HumanBytes2(systemTotalMemory), "free", format.HumanBytes2(systemFreeMemory), "free_swap", format.HumanBytes2(systemSwapFreeMemory))

	g := pickBestFullFitByLibrary(s.ggml, s.modelPath, []string{s.loadRequest.ProjectorPath}, s.loadRequest.LoraPath, s.options, gpus, s.numParallel)
	if g == nil {
		if !requireFull {
			g = pickBestPartialFitByLibrary(s.ggml, []string{s.loadRequest.ProjectorPath}, s.loadRequest.LoraPath, s.options, gpus, s.numParallel)
		} else {
510
			slog.Info("model requires more memory than is currently available, evicting a model to make space", "estimate", s.estimate)
Jesse Gross's avatar
Jesse Gross committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
			return ErrLoadRequiredFull
		}
	}

	gpus = g
	s.estimate = estimateGPULayers(gpus, s.ggml, []string{s.loadRequest.ProjectorPath}, s.options, s.numParallel)

	if len(gpus) > 1 || gpus[0].Library != "cpu" {
		switch {
		case gpus[0].Library == "metal" && s.estimate.VRAMSize > systemInfo.System.TotalMemory:
			// disable partial offloading when model is greater than total system memory as this
			// can lead to locking up the system
			s.options.NumGPU = 0
		case gpus[0].Library != "metal" && s.estimate.Layers == 0:
			// Don't bother loading into the GPU if no layers can fit
			gpus = discover.GetCPUInfo()
		case s.options.NumGPU < 0 && s.estimate.Layers > 0 && gpus[0].Library != "cpu":
			s.options.NumGPU = s.estimate.Layers
		}
	}

	// On linux and windows, over-allocating CPU memory will almost always result in an error
	// Darwin has fully dynamic swap so has no direct concept of free swap space
	if runtime.GOOS != "darwin" {
		systemMemoryRequired := s.estimate.TotalSize - s.estimate.VRAMSize
		available := systemInfo.System.FreeMemory + systemInfo.System.FreeSwap
		if systemMemoryRequired > available {
			slog.Warn("model request too large for system", "requested", format.HumanBytes2(systemMemoryRequired), "available", format.HumanBytes2(available), "total", format.HumanBytes2(systemInfo.System.TotalMemory), "free", format.HumanBytes2(systemInfo.System.FreeMemory), "swap", format.HumanBytes2(systemInfo.System.FreeSwap))
			return fmt.Errorf("model requires more system memory (%s) than is available (%s)", format.HumanBytes2(systemMemoryRequired), format.HumanBytes2(available))
		}
	}

	slog.Info("offload", "", s.estimate)

	s.gpus = gpus
	s.loadRequest.GPULayers = createGPULayers(s.estimate, s.ggml, gpus, s.options.NumGPU)

	// Mmap is only supported on the llama engine
	if s.textProcessor == nil {
		s.loadRequest.UseMmap = true

		// mmap has issues with partial offloading on metal
		for _, g := range gpus {
			if g.Library == "metal" &&
				uint64(s.options.NumGPU) > 0 &&
				uint64(s.options.NumGPU) < s.ggml.KV().BlockCount()+1 {
				s.options.UseMMap = new(bool)
				*s.options.UseMMap = false
			}
		}

		// Windows CUDA should not use mmap for best performance
		// Linux  with a model larger than free space, mmap leads to thrashing
		// For CPU loads we want the memory to be allocated, not FS cache
		if (runtime.GOOS == "windows" && gpus[0].Library == "cuda" && s.options.UseMMap == nil) ||
			(runtime.GOOS == "linux" && systemInfo.System.FreeMemory < s.estimate.TotalSize && s.options.UseMMap == nil) ||
			(gpus[0].Library == "cpu" && s.options.UseMMap == nil) ||
			(s.options.UseMMap != nil && !*s.options.UseMMap) {
			s.loadRequest.UseMmap = false
		}
	}

	if err := s.waitUntilRunnerLaunched(ctx); err != nil {
		return err
	}

	resp, err := s.initModel(ctx, s.loadRequest, LoadOperationCommit)
	if err != nil {
		return err
	}

	// On the Ollama engine, we can print out a summary of the memory allocations.
	// We don't have this for the llama engine but it does something similar itself.
	if s.textProcessor != nil {
		resp.Memory.Log(slog.LevelInfo)
	}

	if !resp.Success {
		slog.Warn("failed to allocate memory for model", "memory", resp.Memory)
		return errors.New("failed to allocate memory for model")
	}

	// The llama engine does its memory allocations together with model loading, so we
	// need to wait until it is done to ensure that we have accurate memory data before
	// loading the next model
	if s.textProcessor == nil {
		return s.WaitUntilRunning(ctx)
	} else {
		return nil
	}
}

// createGPULayers maps from the tensor splits assigned by the memory estimates to explicit assignment
// of particular layers onto GPUs
func createGPULayers(estimate MemoryEstimate, ggml *ggml.GGML, gpus discover.GpuInfoList, numGPU int) ml.GPULayersList {
	if numGPU <= 0 {
		return nil
608
	}
Jesse Gross's avatar
Jesse Gross committed
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665

	gpuLayers := make(ml.GPULayersList, len(gpus))
	for i := range gpuLayers {
		gpuLayers[i].ID = gpus[i].ID
	}

	var sum float32
	splits := make([]float32, len(estimate.TensorSplit))
	// cumulative sum of all splits
	for i := range splits {
		sum += float32(estimate.TensorSplit[i])
		splits[i] = sum
	}

	if sum <= 0 {
		return nil
	}

	// normalize splits
	for i := range splits {
		splits[i] /= sum
	}

	blocks := int(ggml.KV().BlockCount())
	gpuRangeStart := max(0, blocks-numGPU)
	gpuRangeStop := min(gpuRangeStart+numGPU, blocks+1)
	for i := range blocks + 1 {
		if i < gpuRangeStart || i >= gpuRangeStop {
			continue
		}

		index := slices.IndexFunc(splits, func(f float32) bool { return float32(i-gpuRangeStart)/float32(gpuRangeStop-gpuRangeStart) < f })
		if index < 0 || index >= len(gpus) {
			continue
		}

		gpuLayers[index].Layers = append(gpuLayers[index].Layers, i)
	}

	return gpuLayers
}

// Load finds the optimal layout of layers to offload on GPUs based on no initial information about the size of the model
// It does this by:
// 1. Assigning the full model to the GPU with the largest available free memory
// 2. Attempting to allocate the layout and receiving the memory requirements in response
// 3. Creating a new layout based on the updated memory information
// 4. Going back to step 2 and looping until we either stabilize on a particular layout or discover that we have entered a cycle
//
// This process is repeated for higher levels of loading the model (fit, allocate, commit). The earlier levels are quicker,
// allowing for faster iteration, but may return less information.
func (s *ollamaServer) Load(ctx context.Context, gpus discover.GpuInfoList, requireFull bool) error {
	var success bool
	defer func() {
		if !success {
			s.initModel(ctx, LoadRequest{}, LoadOperationClose)
		}
666
667
668
		if s.mem != nil {
			s.mem.Log(slog.LevelInfo)
		}
Jesse Gross's avatar
Jesse Gross committed
669
670
671
672
673
674
675
676
677
678
679
680
	}()

	slog.Info("loading model", "model layers", s.totalLayers, "requested", s.options.NumGPU)

	systemInfo := discover.GetSystemInfo()
	systemTotalMemory := systemInfo.System.TotalMemory
	systemFreeMemory := systemInfo.System.FreeMemory
	systemSwapFreeMemory := systemInfo.System.FreeSwap
	slog.Info("system memory", "total", format.HumanBytes2(systemTotalMemory), "free", format.HumanBytes2(systemFreeMemory), "free_swap", format.HumanBytes2(systemSwapFreeMemory))

	if !(len(gpus) == 1 && gpus[0].Library == "cpu") {
		for _, gpu := range gpus {
681
682
683
684
			available := gpu.FreeMemory - envconfig.GpuOverhead() - gpu.MinimumMemory
			if gpu.FreeMemory < envconfig.GpuOverhead()+gpu.MinimumMemory {
				available = 0
			}
Jesse Gross's avatar
Jesse Gross committed
685
			slog.Info("gpu memory", "id", gpu.ID,
686
				"available", format.HumanBytes2(available),
Jesse Gross's avatar
Jesse Gross committed
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
				"free", format.HumanBytes2(gpu.FreeMemory),
				"minimum", format.HumanBytes2(gpu.MinimumMemory),
				"overhead", format.HumanBytes2(envconfig.GpuOverhead()))
		}
	}

	pastAllocations := make(map[uint64]struct{})
	var backoff float32

	gpuLayers, err := s.createLayout(systemInfo, gpus, s.mem, requireFull, backoff)
	if err != nil {
		return err
	}

	if err := s.waitUntilRunnerLaunched(ctx); err != nil {
		return err
	}

nextOperation:
	for operation := LoadOperationFit; operation < LoadOperationCommit; operation++ {
	nextLoad:
		for {
			s.loadRequest.GPULayers = gpuLayers
			resp, err := s.initModel(ctx, s.loadRequest, operation)
			if err != nil {
				return err
			}

			resp.Memory.Log(slog.LevelDebug)
			slog.Debug("memory", "success", resp.Success, "required", resp.Memory)

			pastAllocations[gpuLayers.Hash()] = struct{}{}
			s.mem = &resp.Memory

			for {
				newGPULayers, err := s.createLayout(systemInfo, gpus, s.mem, requireFull, backoff)
				if err != nil {
					return err
				}

				slog.Debug("new layout created", "layers", newGPULayers)

				// We get additional memory information over time, which will reduce the number of
				// layers that can fit, so fewer layers is actually better. As long as we haven't seen
				// this layout before and it doesn't have more layers than the last one, we can keep
				// trying to see if we can do better.
				if _, ok := pastAllocations[newGPULayers.Hash()]; !ok && newGPULayers.Sum() <= gpuLayers.Sum() {
					gpuLayers = newGPULayers
					continue nextLoad
				}

				// If we are looping around a few different layouts due to graphs moving off and on
				// GPUs, make sure that we try out the intermediate states. For example, if we are
				// looping between offloading 39 and 41 layers, we should also check 40.
				//
				// This switches strategies to force an incremental number of layers to be offloaded
				// and checking the memory layout. If the allocation succeeds and creating a new layout
				// without forcing offload yields the same or greater number of layers offloaded, then
				// the trial is successful.
				//
				// This alternate strategy does not introduce the possibility of loops with the overall
				// state machine, as it exits this code block either with a successful result, moving
				// to the next operation or the original number of layers offloaded.
				if s.options.NumGPU < 0 && newGPULayers.Sum()-gpuLayers.Sum() > 1 {
					for i := newGPULayers.Sum() - 1; i >= gpuLayers.Sum(); i-- {
						slog.Debug("exploring intermediate layers", "layer", i)

						s.options.NumGPU = i
						newGPULayers, err = s.createLayout(systemInfo, gpus, s.mem, requireFull, backoff)
						s.options.NumGPU = -1
						if err != nil {
							return err
						}

						slog.Debug("new layout created", "layers", newGPULayers)

						s.loadRequest.GPULayers = newGPULayers
						resp, err = s.initModel(ctx, s.loadRequest, operation)
						if err != nil {
							return err
						}

						resp.Memory.Log(slog.LevelDebug)
						slog.Debug("memory", "success", resp.Success, "required", resp.Memory)

						if resp.Success {
							verifyGPULayers, err := s.createLayout(systemInfo, gpus, &resp.Memory, requireFull, backoff)
							if err != nil {
								return err
							}

							slog.Debug("verifying layout", "layers", verifyGPULayers)

							if newGPULayers.Sum() <= verifyGPULayers.Sum() {
								gpuLayers = newGPULayers

								// Since we are going backwards (increasing the number of layers), ensure that
								// we can come back down if needed
								clear(pastAllocations)

								continue nextOperation
							}
						}
					}
				}

				// If we generated a layout a second time or go backwards, then we've converged. Use the last
				// layout before the repeat, which is already allocated.
				if resp.Success {
					continue nextOperation
				}

				if s.options.NumGPU >= 0 {
					return fmt.Errorf("memory layout cannot be allocated with num_gpu = %v", s.options.NumGPU)
				}

				// Memory allocation failed even though we created a layout that we thought should
				// fit in available memory. This could happen if either our free memory reports
				// are incorrect or if available memory is changing between layout and allocation
				// time. Apply an exponential backoff to try to find the real amount of available
				// space.
				if backoff > 1 {
					slog.Warn("memory layout cannot be allocated", "memory", resp.Memory)
					return errors.New("memory layout cannot be allocated")
				} else if backoff == 0 {
					backoff = 0.01
				} else {
					backoff *= 2
				}

				slog.Info("model layout did not fit, applying backoff", "backoff", fmt.Sprintf("%.2f", backoff))
			}
		}
	}

	s.loadRequest.GPULayers = gpuLayers
	resp, err := s.initModel(ctx, s.loadRequest, LoadOperationCommit)
	if err != nil {
		return err
	}

	success = resp.Success
	s.mem = &resp.Memory

	if !success {
		slog.Warn("failed to commit memory for model", "memory", resp.Memory)
		return errors.New("failed to commit memory for model")
	}

	return nil
}

// createLayout uses the current best view of memory requirements and creates a layout of model layers on GPUs.
// It does this by:
// - Calculating how much space each layer requires
// - Calculating how much space each GPU has available for layers, based on free memory and space occupied by the graph
// - Assigning layers
// - Ensuring that we don't exceed limits, such as requirements about partial offloading or system memory
func (s *ollamaServer) createLayout(systemInfo discover.SystemInfo, systemGPUs discover.GpuInfoList, memory *ml.BackendMemory, requireFull bool, backoff float32) (ml.GPULayersList, error) {
	if s.totalLayers == 0 || s.options.NumGPU == 0 || len(systemGPUs) == 0 || (len(systemGPUs) == 1 && systemGPUs[0].Library == "cpu") {
		return ml.GPULayersList{}, nil
	}

	gpus := append(make(discover.GpuInfoList, 0, len(systemGPUs)), systemGPUs...)
	sort.Sort(sort.Reverse(discover.ByFreeMemory(gpus)))

	if memory == nil {
		memory = &ml.BackendMemory{CPU: ml.DeviceMemory{
			Weights: make([]ml.Memory, s.totalLayers),
			Cache:   make([]ml.Memory, s.totalLayers),
		}}
	}

	layers := make([]uint64, len(memory.CPU.Weights))
	for i := range layers {
		for j := range memory.GPUs {
			layers[i] += memory.GPUs[j].Weights[i].Size
			layers[i] += memory.GPUs[j].Cache[i].Size
		}
		layers[i] += memory.CPU.Weights[i].Size
		layers[i] += memory.CPU.Cache[i].Size
868
		logutil.Trace("layer to assign", "layer", i, "size", format.HumanBytes2(layers[i]))
Jesse Gross's avatar
Jesse Gross committed
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
	}

	gpuLayers := ml.GPULayersList{}
	for _, gl := range gpus.ByLibrary() {
		// If a GPU already has a graph allocated on it, then we should continue to use it.
		// Otherwise, we lose information that we got from previous allocations, which can
		// cause cycling. Plus, we get more information about required allocation from each
		// iteration, so it doesn't make sense that a later iteration would use fewer GPUs.
		lastUsedGPU := 0
		for i := range gl {
			found := false
			for j := range memory.GPUs {
				if gl[i].ID == memory.GPUs[j].ID {
					if memory.GPUs[j].Graph.Size != 0 {
						lastUsedGPU = i
					}

					reserved := uint64(float32(gl[i].FreeMemory)*backoff) + gl[i].MinimumMemory + envconfig.GpuOverhead() + memory.GPUs[j].Graph.Size
					if gl[i].FreeMemory > reserved {
						gl[i].FreeMemory -= reserved
					} else {
						gl[i].FreeMemory = 0
					}

					slog.Debug("available gpu", "id", gl[i].ID,
						"available layer vram", format.HumanBytes2(gl[i].FreeMemory),
						"backoff", fmt.Sprintf("%.2f", backoff), "minimum", format.HumanBytes2(gl[i].MinimumMemory),
						"overhead", format.HumanBytes2(envconfig.GpuOverhead()),
						"graph", format.HumanBytes2(memory.GPUs[j].Graph.Size))

					found = true
					break
				}
			}
			if !found {
				// The runner doesn't report seeing this GPU
				gl[i].FreeMemory = 0
			}
		}

		libraryGpuLayers := assignLayers(layers, gl, s.options.NumGPU, lastUsedGPU)
		if libraryGpuLayers.Sum() > gpuLayers.Sum() {
			gpuLayers = libraryGpuLayers
		}
	}

	// These sizes will only increase as we go through additional iterations and get additional information.
	cpuSize := memory.InputWeights.Size + memory.CPU.Graph.Size
	var vramSize uint64
	for _, gl := range gpuLayers {
		for _, gpu := range memory.GPUs {
			if gl.ID == gpu.ID {
				vramSize += gpu.Graph.Size
				break
			}
		}
	}

nextLayer:
	for i := range layers {
		for _, g := range gpuLayers {
			for _, gl := range g.Layers {
				if i == gl {
					vramSize += layers[i]
					continue nextLayer
				}
			}
		}
		cpuSize += layers[i]
	}

	if requireFull {
		if gpuLayers.Sum() < len(layers) && (s.options.NumGPU < 0 || gpuLayers.Sum() < s.options.NumGPU) {
			return nil, ErrLoadRequiredFull
		}

		if cpuSize > systemInfo.System.FreeMemory {
			return nil, ErrLoadRequiredFull
		}
	}

	// On linux and windows, over-allocating CPU memory will almost always result in an error
	// Darwin has fully dynamic swap so has no direct concept of free swap space
	if runtime.GOOS != "darwin" {
		available := systemInfo.System.FreeMemory + systemInfo.System.FreeSwap
		if cpuSize > available {
			slog.Warn("model request too large for system", "requested", format.HumanBytes2(cpuSize), "available", format.HumanBytes2(available), "total", format.HumanBytes2(systemInfo.System.TotalMemory), "free", format.HumanBytes2(systemInfo.System.FreeMemory), "swap", format.HumanBytes2(systemInfo.System.FreeSwap))
			return nil, fmt.Errorf("model requires more system memory (%s) than is available (%s)", format.HumanBytes2(cpuSize), format.HumanBytes2(available))
		}
	} else {
		if vramSize > systemInfo.System.TotalMemory {
			// disable partial offloading when model is greater than total system memory as this
			// can lead to locking up the system
			s.options.NumGPU = 0
			gpuLayers = ml.GPULayersList{}
		}
	}

	if gpuLayers.Sum() == 0 {
		slog.Debug("insufficient VRAM to load any model layers")
	}

	return gpuLayers, nil
}

// assignLayers packs the maximum number of layers onto the smallest set of GPUs and comes up with a layer assignment
func assignLayers(layers []uint64, gpus discover.GpuInfoList, requestedLayers int, lastUsedGPU int) (gpuLayers ml.GPULayersList) {
	// If we can't fit everything then prefer offloading layers other than the output layer
	for range 2 {
		// requestedLayers may be -1 if nothing was requested
		requestedLayers = min(len(layers), requestedLayers)

		if !envconfig.SchedSpread() {
			for i := lastUsedGPU; i < len(gpus); i++ {
				// Try to pack things into as few GPUs as possible
				forceRequest := i == len(gpus)-1
				gpuLayers = findBestFit(layers, gpus[:i+1], requestedLayers, forceRequest)
				if gpuLayers.Sum() == len(layers) || gpuLayers.Sum() == requestedLayers {
					break
				}
			}
		} else {
			gpuLayers = findBestFit(layers, gpus, requestedLayers, true)
		}

		// We only stop if we've gotten all of the layers - even if we got requestedLayers, we still
		// might want to try dropping the output layer.
		if gpuLayers.Sum() == len(layers) {
			return gpuLayers
		}

		layers = layers[:len(layers)-1]
	}

	return gpuLayers
}

// findBestFit binary searches to find the smallest capacity factor that can fit
// the max number of layers. The capacity factor is multiplied by the free space on
// each GPU and a small one will force even balancing.
func findBestFit(layers []uint64, gpus discover.GpuInfoList, requestedLayers int, forceRequest bool) (gpuLayers ml.GPULayersList) {
	var high float32 = 1
	var low float32 = 0

	// If we need to fulfill the requested number of layers, pretend we have almost infinite VRAM
	if requestedLayers >= 0 && forceRequest {
		high = 1000
	}

	bestAssignments := greedyFit(layers, gpus, high, requestedLayers)
	maxNumGPU := bestAssignments.Sum()
	if maxNumGPU == 0 {
		return bestAssignments
	}

	for high-low > 1e-6 {
		mid := (low + high) / 2
		assignments := greedyFit(layers, gpus, mid, requestedLayers)
		if assignments.Sum() == maxNumGPU {
			high = mid
			bestAssignments = assignments
		} else {
			low = mid
		}
	}

	return bestAssignments
}

// greedyFit assigns layers incrementally to GPUs, spilling over as each runs out of free space
func greedyFit(layers []uint64, gpus discover.GpuInfoList, capacity float32, requestedLayers int) (gpuLayers ml.GPULayersList) {
	device := len(gpus) - 1
	gpuLayers = ml.GPULayersList{{ID: gpus[device].ID}}
	freeSpace := uint64(float32(gpus[device].FreeMemory) * capacity)
	for i := len(layers) - 1; i >= 0; i-- {
		if requestedLayers >= 0 && len(layers)-1-i >= requestedLayers {
			break
		}

		for {
			if layers[i] <= freeSpace {
				gpuLayers[0].Layers = append([]int{i}, gpuLayers[0].Layers...)
				freeSpace -= layers[i]
				break
			}

			device--
			if device < 0 {
				return gpuLayers
			}
			gpuLayers = append(ml.GPULayersList{{ID: gpus[device].ID}}, gpuLayers...)
			freeSpace = uint64(float32(gpus[device].FreeMemory) * capacity)
		}
	}

	return gpuLayers
}

// waitUntilRunnerLaunched sleeps until the runner subprocess is alive enough
// to respond to status requests
func (s *llmServer) waitUntilRunnerLaunched(ctx context.Context) error {
	for {
		_, err := s.getServerStatus(ctx)
		if err == nil {
			break
		}

		t := time.NewTimer(10 * time.Millisecond)
		select {
		case <-t.C:
			continue
		case <-ctx.Done():
			return ctx.Err()
		}
	}

	return nil
}

// initModel sends a load request to the runner based on the request operation (fit, alloc, commit)
// and parameters
func (s *llmServer) initModel(ctx context.Context, req LoadRequest, operation LoadOperation) (*LoadResponse, error) {
	req.Operation = operation

	data, err := json.Marshal(req)
	if err != nil {
		return nil, fmt.Errorf("error marshaling load data: %w", err)
	}

	r, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/load", s.port), bytes.NewBuffer(data))
	if err != nil {
		return nil, fmt.Errorf("error creating load request: %w", err)
	}
	r.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(r)
	if err != nil {
		return nil, fmt.Errorf("do load request: %w", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("read load request: %w", err)
	}

	if resp.StatusCode >= 400 {
		log.Printf("llm load error: %s", body)
		return nil, fmt.Errorf("%s", body)
	}

	var llmResp LoadResponse
	if err := json.Unmarshal(body, &llmResp); err != nil {
		return nil, fmt.Errorf("load unmarshal encode response: %w", err)
	}

	return &llmResp, nil
1126
1127
1128
1129
1130
1131
}

type ServerStatus int

const ( // iota is reset to 0
	ServerStatusReady ServerStatus = iota
1132
	ServerStatusNoSlotsAvailable
Jesse Gross's avatar
Jesse Gross committed
1133
	ServerStatusLaunched
1134
1135
1136
1137
1138
	ServerStatusLoadingModel
	ServerStatusNotResponding
	ServerStatusError
)

1139
func (s ServerStatus) String() string {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1140
1141
1142
	switch s {
	case ServerStatusReady:
		return "llm server ready"
1143
	case ServerStatusNoSlotsAvailable:
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1144
		return "llm busy - no slots available"
Jesse Gross's avatar
Jesse Gross committed
1145
1146
	case ServerStatusLaunched:
		return "llm server launched"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1147
1148
1149
1150
1151
1152
1153
1154
1155
	case ServerStatusLoadingModel:
		return "llm server loading model"
	case ServerStatusNotResponding:
		return "llm server not responding"
	default:
		return "llm server error"
	}
}

1156
1157
1158
type ServerStatusResponse struct {
	Status   ServerStatus `json:"status"`
	Progress float32      `json:"progress"`
1159
1160
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1161
func (s *llmServer) getServerStatus(ctx context.Context) (ServerStatus, error) {
1162
1163
1164
1165
1166
1167
	// Fail fast if its exited
	if s.cmd.ProcessState != nil {
		msg := ""
		if s.status != nil && s.status.LastErrMsg != "" {
			msg = s.status.LastErrMsg
		}
1168
1169
		if s.cmd.ProcessState.ExitCode() == -1 {
			// Most likely a signal killed it, log some more details to try to help troubleshoot
1170
			slog.Warn("llama runner process no longer running", "sys", s.cmd.ProcessState.Sys(), "string", s.cmd.ProcessState)
1171
		}
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
		return ServerStatusError, fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
	}

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/health", s.port), nil)
	if err != nil {
		return ServerStatusError, fmt.Errorf("error creating GET request: %v", err)
	}
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		if errors.Is(err, context.DeadlineExceeded) {
Michael Yang's avatar
Michael Yang committed
1184
			return ServerStatusNotResponding, errors.New("server not responding")
1185
		}
1186
1187
1188
		if strings.Contains(err.Error(), "connection refused") {
			return ServerStatusNotResponding, errors.New("connection refused")
		}
1189
1190
1191
1192
1193
1194
1195
1196
1197
		return ServerStatusError, fmt.Errorf("health resp: %w", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return ServerStatusError, fmt.Errorf("read health request: %w", err)
	}

1198
1199
	var ssr ServerStatusResponse
	if err := json.Unmarshal(body, &ssr); err != nil {
1200
1201
1202
		return ServerStatusError, fmt.Errorf("health unmarshal encode response: %w", err)
	}

1203
1204
1205
1206
	switch ssr.Status {
	case ServerStatusLoadingModel:
		s.loadProgress = ssr.Progress
		return ssr.Status, nil
Jesse Gross's avatar
Jesse Gross committed
1207
	case ServerStatusLaunched, ServerStatusReady, ServerStatusNoSlotsAvailable:
1208
		return ssr.Status, nil
1209
	default:
1210
		return ssr.Status, fmt.Errorf("server error: %+v", ssr)
1211
1212
1213
	}
}

1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
// getServerStatusRetry will retry if ServerStatusNoSlotsAvailable is received
func (s *llmServer) getServerStatusRetry(ctx context.Context) (ServerStatus, error) {
	var retries int
	for {
		status, err := s.getServerStatus(ctx)
		if err != nil {
			return status, err
		}

		if status == ServerStatusNoSlotsAvailable {
			if retries >= 10 {
				return status, fmt.Errorf("no slots available after %d retries", retries)
			}

			time.Sleep(5 * time.Millisecond)
			retries++
			continue
		}

		return status, nil
	}
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1237
func (s *llmServer) Ping(ctx context.Context) error {
1238
1239
1240
1241
1242
1243
1244
1245
	_, err := s.getServerStatus(ctx)
	if err != nil {
		slog.Debug("server unhealthy", "error", err)
		return err
	}
	return nil
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1246
func (s *llmServer) WaitUntilRunning(ctx context.Context) error {
1247
	stallDuration := envconfig.LoadTimeout()    // If no progress happens
1248
	stallTimer := time.Now().Add(stallDuration) // give up if we stall
1249
1250
1251

	slog.Info("waiting for llama runner to start responding")
	var lastStatus ServerStatus = -1
1252
	fullyLoaded := false
ManniX-ITA's avatar
ManniX-ITA committed
1253

1254
1255
	for {
		select {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1256
		case <-ctx.Done():
1257
			slog.Warn("client connection closed before server finished loading, aborting load")
1258
			return fmt.Errorf("timed out waiting for llama runner to start: %w", ctx.Err())
1259
		case err := <-s.done:
1260
			return fmt.Errorf("llama runner process has terminated: %w", err)
1261
1262
		default:
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1263
		if time.Now().After(stallTimer) {
ManniX-ITA's avatar
ManniX-ITA committed
1264
			// timeout
1265
1266
1267
1268
			msg := ""
			if s.status != nil && s.status.LastErrMsg != "" {
				msg = s.status.LastErrMsg
			}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1269
			return fmt.Errorf("timed out waiting for llama runner to start - progress %0.2f - %s", s.loadProgress, msg)
ManniX-ITA's avatar
ManniX-ITA committed
1270
1271
1272
1273
1274
		}
		if s.cmd.ProcessState != nil {
			msg := ""
			if s.status != nil && s.status.LastErrMsg != "" {
				msg = s.status.LastErrMsg
1275
			}
ManniX-ITA's avatar
ManniX-ITA committed
1276
1277
			return fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1278
1279
		ctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
		defer cancel()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1280
		priorProgress := s.loadProgress
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1281
1282
1283
		status, _ := s.getServerStatus(ctx)
		if lastStatus != status && status != ServerStatusReady {
			// Only log on status changes
1284
			slog.Info("waiting for server to become available", "status", status)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1285
		}
ManniX-ITA's avatar
ManniX-ITA committed
1286
1287
		switch status {
		case ServerStatusReady:
Jesse Gross's avatar
Jesse Gross committed
1288
			slog.Info(fmt.Sprintf("llama runner started in %0.2f seconds", time.Since(s.loadStart).Seconds()))
ManniX-ITA's avatar
ManniX-ITA committed
1289
1290
			return nil
		default:
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1291
			lastStatus = status
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1292
1293
1294
1295
			// Reset the timer as long as we're making forward progress on the load
			if priorProgress != s.loadProgress {
				slog.Debug(fmt.Sprintf("model load progress %0.2f", s.loadProgress))
				stallTimer = time.Now().Add(stallDuration)
1296
			} else if !fullyLoaded && int(s.loadProgress*100.0) >= 100 {
1297
				slog.Debug("model load completed, waiting for server to become available", "status", status)
1298
				stallTimer = time.Now().Add(stallDuration)
1299
				fullyLoaded = true
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1300
			}
ManniX-ITA's avatar
ManniX-ITA committed
1301
1302
			time.Sleep(time.Millisecond * 250)
			continue
1303
1304
1305
1306
		}
	}
}

1307
1308
1309
1310
1311
1312
1313
func (s *llmServer) Pid() int {
	if s.cmd != nil && s.cmd.Process != nil {
		return s.cmd.Process.Pid
	}
	return -1
}

1314
var grammarJSON = `
1315
1316
1317
1318
root   ::= object
value  ::= object | array | string | number | ("true" | "false" | "null") ws
object ::=
  "{" ws (
1319
         string ":" ws value
1320
    ("," ws string ":" ws value)*
1321
  )? ws "}" 
1322
1323
1324
1325
array  ::=
  "[" ws (
            value
    ("," ws value)*
1326
  )? ws "]" 
1327
1328
string ::=
  "\"" (
1329
    [^"\\\x7F\x00-\x1F] |
1330
    "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
1331
1332
  )* "\"" 
number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? 
1333
1334
1335
1336
1337
1338
1339
# Optional space: by convention, applied in this grammar after literal chars when allowed
ws ::= ([ \t\n] ws)?
`

const maxBufferSize = 512 * format.KiloByte

type ImageData struct {
1340
1341
	Data []byte `json:"data"`
	ID   int    `json:"id"`
1342
1343
1344
1345
}

type CompletionRequest struct {
	Prompt  string
1346
	Format  json.RawMessage
1347
	Images  []ImageData
Michael Yang's avatar
Michael Yang committed
1348
	Options *api.Options
1349
1350

	Grammar string // set before sending the request to the subprocess
1351
1352
}

1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
// DoneReason represents the reason why a completion response is done
type DoneReason int

const (
	// DoneReasonStop indicates the completion stopped naturally
	DoneReasonStop DoneReason = iota
	// DoneReasonLength indicates the completion stopped due to length limits
	DoneReasonLength
	// DoneReasonConnectionClosed indicates the completion stopped due to the connection being closed
	DoneReasonConnectionClosed
)

func (d DoneReason) String() string {
	switch d {
	case DoneReasonLength:
		return "length"
	case DoneReasonStop:
		return "stop"
	default:
		return "" // closed
	}
}

1376
type CompletionResponse struct {
1377
	Content            string        `json:"content"`
1378
	DoneReason         DoneReason    `json:"done_reason"`
1379
1380
1381
1382
1383
	Done               bool          `json:"done"`
	PromptEvalCount    int           `json:"prompt_eval_count"`
	PromptEvalDuration time.Duration `json:"prompt_eval_duration"`
	EvalCount          int           `json:"eval_count"`
	EvalDuration       time.Duration `json:"eval_duration"`
1384
1385
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1386
func (s *llmServer) Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error {
1387
1388
1389
	slog.Debug("completion request", "images", len(req.Images), "prompt", len(req.Prompt), "format", string(req.Format))
	slog.Log(ctx, logutil.LevelTrace, "completion request", "prompt", req.Prompt)

1390
	if len(req.Format) > 0 {
1391
1392
1393
1394
1395
1396
		switch string(req.Format) {
		case `null`, `""`:
			// Field was set, but "missing" a value. We accept
			// these as "not set".
			break
		case `"json"`:
1397
			req.Grammar = grammarJSON
1398
1399
1400
1401
		default:
			if req.Format[0] != '{' {
				return fmt.Errorf("invalid format: %q; expected \"json\" or a valid JSON Schema object", req.Format)
			}
1402

1403
1404
1405
1406
			// User provided a JSON schema
			g := llama.SchemaToGrammar(req.Format)
			if g == nil {
				return fmt.Errorf("invalid JSON schema in format")
1407
			}
1408
			req.Grammar = string(g)
1409
1410
1411
		}
	}

1412
1413
1414
1415
1416
	if req.Options == nil {
		opts := api.DefaultOptions()
		req.Options = &opts
	}

1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
	if err := s.sem.Acquire(ctx, 1); err != nil {
		if errors.Is(err, context.Canceled) {
			slog.Info("aborting completion request due to client closing the connection")
		} else {
			slog.Error("Failed to acquire semaphore", "error", err)
		}
		return err
	}
	defer s.sem.Release(1)

	// put an upper limit on num_predict to avoid the model running on forever
	if req.Options.NumPredict < 0 || req.Options.NumPredict > 10*s.options.NumCtx {
		req.Options.NumPredict = 10 * s.options.NumCtx
	}

1432
	// Make sure the server is ready
1433
	status, err := s.getServerStatusRetry(ctx)
1434
1435
1436
	if err != nil {
		return err
	} else if status != ServerStatusReady {
1437
		return fmt.Errorf("unexpected server status: %s", status)
1438
1439
	}

1440
1441
1442
1443
	// Handling JSON marshaling with special characters unescaped.
	buffer := &bytes.Buffer{}
	enc := json.NewEncoder(buffer)
	enc.SetEscapeHTML(false)
1444

1445
	if err := enc.Encode(req); err != nil {
1446
1447
		return fmt.Errorf("failed to marshal data: %v", err)
	}
1448

1449
1450
1451
1452
1453
1454
	endpoint := fmt.Sprintf("http://127.0.0.1:%d/completion", s.port)
	serverReq, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, buffer)
	if err != nil {
		return fmt.Errorf("error creating POST request: %v", err)
	}
	serverReq.Header.Set("Content-Type", "application/json")
1455

1456
1457
	res, err := http.DefaultClient.Do(serverReq)
	if err != nil {
1458
1459
		slog.Error("post predict", "error", err)
		return errors.New("model runner has unexpectedly stopped, this may be due to resource limitations or an internal error, check ollama server logs for details")
1460
1461
	}
	defer res.Body.Close()
1462

1463
1464
	if res.StatusCode >= 400 {
		bodyBytes, err := io.ReadAll(res.Body)
1465
		if err != nil {
1466
			return fmt.Errorf("failed reading llm error response: %w", err)
1467
		}
1468
1469
1470
		log.Printf("llm predict error: %s", bodyBytes)
		return fmt.Errorf("%s", bodyBytes)
	}
1471

1472
1473
1474
	scanner := bufio.NewScanner(res.Body)
	buf := make([]byte, 0, maxBufferSize)
	scanner.Buffer(buf, maxBufferSize)
1475

1476
1477
1478
	// keep track of the last token generated, this is used to abort if the model starts looping
	var lastToken string
	var tokenRepeat int
1479

1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
	for scanner.Scan() {
		select {
		case <-ctx.Done():
			// This handles the request cancellation
			return ctx.Err()
		default:
			line := scanner.Bytes()
			if len(line) == 0 {
				continue
			}
1490

1491
1492
			evt, ok := bytes.CutPrefix(line, []byte("data: "))
			if !ok {
1493
				evt = line
1494
			}
1495

1496
			var c CompletionResponse
1497
			if err := json.Unmarshal(evt, &c); err != nil {
1498
				return fmt.Errorf("error unmarshalling llm prediction response: %v", err)
1499
1500
1501
1502
1503
1504
1505
1506
			}
			switch {
			case strings.TrimSpace(c.Content) == lastToken:
				tokenRepeat++
			default:
				lastToken = strings.TrimSpace(c.Content)
				tokenRepeat = 0
			}
1507

1508
1509
1510
1511
1512
			// 30 picked as an arbitrary max token repeat limit, modify as needed
			if tokenRepeat > 30 {
				slog.Debug("prediction aborted, token repeat limit reached")
				return ctx.Err()
			}
1513

1514
1515
1516
1517
1518
			if c.Content != "" {
				fn(CompletionResponse{
					Content: c.Content,
				})
			}
1519

1520
1521
			if c.Done {
				fn(c)
1522
				return nil
1523
1524
			}
		}
1525
	}
1526

1527
	if err := scanner.Err(); err != nil {
1528
		if strings.Contains(err.Error(), "unexpected EOF") || strings.Contains(err.Error(), "forcibly closed") {
1529
			s.Close()
1530
			var msg string
1531
1532
			if s.status != nil && s.status.LastErrMsg != "" {
				msg = s.status.LastErrMsg
1533
1534
			} else {
				msg = err.Error()
1535
			}
1536
			return fmt.Errorf("an error was encountered while running the model: %s", msg)
1537
1538
		}

1539
		return fmt.Errorf("error reading llm response: %v", err)
1540
1541
	}

1542
	return nil
1543
1544
}

1545
1546
type EmbeddingRequest struct {
	Content string `json:"content"`
1547
1548
}

1549
1550
type EmbeddingResponse struct {
	Embedding []float32 `json:"embedding"`
1551
1552
}

1553
func (s *llmServer) Embedding(ctx context.Context, input string) ([]float32, error) {
1554
1555
	slog.Log(ctx, logutil.LevelTrace, "embedding request", "input", input)

1556
	if err := s.sem.Acquire(ctx, 1); err != nil {
1557
1558
1559
1560
1561
		if errors.Is(err, context.Canceled) {
			slog.Info("aborting embedding request due to client closing the connection")
		} else {
			slog.Error("Failed to acquire semaphore", "error", err)
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1562
1563
		return nil, err
	}
1564
	defer s.sem.Release(1)
1565

1566
	// Make sure the server is ready
1567
	status, err := s.getServerStatusRetry(ctx)
1568
1569
1570
	if err != nil {
		return nil, err
	} else if status != ServerStatusReady {
1571
		return nil, fmt.Errorf("unexpected server status: %s", status)
1572
1573
	}

1574
	data, err := json.Marshal(EmbeddingRequest{Content: input})
Michael Yang's avatar
Michael Yang committed
1575
	if err != nil {
1576
1577
1578
		return nil, fmt.Errorf("error marshaling embed data: %w", err)
	}

1579
	r, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/embedding", s.port), bytes.NewBuffer(data))
1580
1581
1582
	if err != nil {
		return nil, fmt.Errorf("error creating embed request: %w", err)
	}
1583
	r.Header.Set("Content-Type", "application/json")
1584

1585
	resp, err := http.DefaultClient.Do(r)
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
	if err != nil {
		return nil, fmt.Errorf("do embedding request: %w", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("error reading embed response: %w", err)
	}

	if resp.StatusCode >= 400 {
1597
		log.Printf("llm embedding error: %s", body)
1598
1599
1600
		return nil, fmt.Errorf("%s", body)
	}

1601
	var e EmbeddingResponse
1602
	if err := json.Unmarshal(body, &e); err != nil {
1603
1604
1605
		return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
	}

1606
	return e.Embedding, nil
1607
1608
}

Michael Yang's avatar
Michael Yang committed
1609
1610
1611
1612
1613
1614
1615
1616
type TokenizeRequest struct {
	Content string `json:"content"`
}

type TokenizeResponse struct {
	Tokens []int `json:"tokens"`
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1617
func (s *llmServer) Tokenize(ctx context.Context, content string) ([]int, error) {
1618
1619
	s.llamaModelLock.Lock()
	defer s.llamaModelLock.Unlock()
1620

1621
1622
	if s.llamaModel != nil {
		return s.llamaModel.Tokenize(content, false, true)
Michael Yang's avatar
Michael Yang committed
1623
	}
1624
	if s.textProcessor != nil {
1625
		tokens, err := s.textProcessor.Encode(content, false)
1626
1627
		if err != nil {
			return nil, err
1628
		}
1629
1630
1631
1632
1633
		toks := make([]int, len(tokens))
		for i, t := range tokens {
			toks[i] = int(t)
		}
		return toks, nil
Michael Yang's avatar
Michael Yang committed
1634
	}
1635
1636
	// not reached
	return nil, fmt.Errorf("no tokenizer configured")
Michael Yang's avatar
Michael Yang committed
1637
1638
1639
1640
1641
1642
1643
1644
}

type DetokenizeRequest struct {
	Tokens []int `json:"tokens"`
}

type DetokenizeResponse struct {
	Content string `json:"content"`
1645
1646
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1647
func (s *llmServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
1648
1649
1650
1651
	s.llamaModelLock.Lock()
	defer s.llamaModelLock.Unlock()

	if s.llamaModel != nil {
1652
1653
		var resp string
		for _, token := range tokens {
1654
			resp += s.llamaModel.TokenToPiece(token)
1655
1656
1657
		}
		return resp, nil
	}
1658
1659
1660
1661
	if s.textProcessor != nil {
		toks := make([]int32, len(tokens))
		for i, t := range tokens {
			toks[i] = int32(t)
1662
		}
1663
1664
1665
		content, err := s.textProcessor.Decode(toks)
		if err != nil {
			return "", err
1666
		}
1667
		return content, nil
Michael Yang's avatar
Michael Yang committed
1668
	}
1669
1670
	// not reached
	return "", fmt.Errorf("no tokenizer configured")
1671
1672
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1673
func (s *llmServer) Close() error {
1674
1675
1676
1677
	s.llamaModelLock.Lock()
	if s.llamaModel != nil {
		llama.FreeModel(s.llamaModel)
		s.llamaModel = nil
1678
	}
1679
	s.llamaModelLock.Unlock()
1680

1681
	if s.cmd != nil {
1682
		slog.Debug("stopping llama server", "pid", s.Pid())
1683
1684
1685
		if err := s.cmd.Process.Kill(); err != nil {
			return err
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1686
1687
		// if ProcessState is already populated, Wait already completed, no need to wait again
		if s.cmd.ProcessState == nil {
1688
			slog.Debug("waiting for llama server to exit", "pid", s.Pid())
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1689
1690
			<-s.done
		}
1691

1692
		slog.Debug("llama server stopped", "pid", s.Pid())
1693
1694
1695
1696
1697
	}

	return nil
}

Jesse Gross's avatar
Jesse Gross committed
1698
func (s *llamaServer) VRAMSize() uint64 {
1699
	return s.estimate.VRAMSize
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1700
1701
}

Jesse Gross's avatar
Jesse Gross committed
1702
func (s *llamaServer) TotalSize() uint64 {
1703
	return s.estimate.TotalSize
1704
1705
}

Jesse Gross's avatar
Jesse Gross committed
1706
func (s *llamaServer) VRAMByGPU(gpuID string) uint64 {
1707
1708
	for i, gpu := range s.gpus {
		if gpu.ID == gpuID {
1709
1710
1711
			if i < len(s.estimate.GPUSizes) {
				return s.estimate.GPUSizes[i]
			}
1712
1713
1714
1715
		}
	}
	return 0
}
Jesse Gross's avatar
Jesse Gross committed
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771

func (s *ollamaServer) VRAMSize() uint64 {
	if s.mem == nil {
		return 0
	}

	var mem uint64

	for _, g := range s.mem.GPUs {
		mem += g.Allocated()
	}

	// Some elements are always on CPU. However, if we have allocated all layers
	// on the GPU then include the CPU components as well, to represent complete offloading.
	noCPULayers := true
	for i := range s.mem.CPU.Weights {
		if s.mem.CPU.Weights[i].Size != 0 || s.mem.CPU.Cache[i].Size != 0 {
			noCPULayers = false
			break
		}
	}
	if noCPULayers {
		mem += s.mem.InputWeights.Size
		mem += s.mem.CPU.Graph.Size
	}

	return mem
}

func (s *ollamaServer) TotalSize() uint64 {
	if s.mem == nil {
		return 0
	}

	mem := s.mem.InputWeights.Size
	mem += s.mem.CPU.Allocated()
	for _, g := range s.mem.GPUs {
		mem += g.Allocated()
	}

	return mem
}

func (s *ollamaServer) VRAMByGPU(gpuID string) uint64 {
	if s.mem == nil {
		return 0
	}

	for _, g := range s.mem.GPUs {
		if g.ID == gpuID {
			return g.Allocated()
		}
	}

	return 0
}