server.go 53.8 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/envconfig"
31
	"github.com/ollama/ollama/format"
Michael Yang's avatar
Michael Yang committed
32
	"github.com/ollama/ollama/fs/ggml"
33
	"github.com/ollama/ollama/llama"
34
	"github.com/ollama/ollama/logutil"
Jesse Gross's avatar
Jesse Gross committed
35
	"github.com/ollama/ollama/ml"
36
	"github.com/ollama/ollama/model"
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
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
66
type LlamaServer interface {
Jesse Gross's avatar
Jesse Gross committed
67
	ModelPath() string
68
	Load(ctx context.Context, systemInfo ml.SystemInfo, gpus []ml.DeviceInfo, requireFull bool) ([]ml.DeviceID, error)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
69
70
71
	Ping(ctx context.Context) error
	WaitUntilRunning(ctx context.Context) error
	Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error
72
	Embedding(ctx context.Context, input string) ([]float32, int, error)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
73
74
75
	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
76
77
	VRAMSize() uint64 // Total VRAM across all GPUs
	TotalSize() uint64
78
	VRAMByGPU(id ml.DeviceID) uint64
79
	Pid() int
80
81
82
	GetPort() int
	GetDeviceInfos(ctx context.Context) []ml.DeviceInfo
	HasExited() bool
Daniel Hiltgen's avatar
Daniel Hiltgen committed
83
84
}

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

94
95
	loadRequest LoadRequest       // Parameters used to initialize the runner
	mem         *ml.BackendMemory // Memory allocations for this model
Jesse Gross's avatar
Jesse Gross committed
96

97
98
99
	// 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
100
	llamaModelLock *sync.Mutex
101

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

	sem *semaphore.Weighted
107
108
}

Jesse Gross's avatar
Jesse Gross committed
109
110
111
type llamaServer struct {
	llmServer

112
	ggml *ggml.GGML
Jesse Gross's avatar
Jesse Gross committed
113
114
115
116
}

type ollamaServer struct {
	llmServer
117
118

	textProcessor model.TextProcessor // textProcessor handles text encoding/decoding
Jesse Gross's avatar
Jesse Gross committed
119
120
}

121
122
123
124
125
// 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
126
func LoadModel(model string, maxArraySize int) (*ggml.GGML, error) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
127
128
129
130
	if _, err := os.Stat(model); err != nil {
		return nil, err
	}

131
132
133
134
135
136
	f, err := os.Open(model)
	if err != nil {
		return nil, err
	}
	defer f.Close()

137
	ggml, err := ggml.Decode(f, maxArraySize)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
138
139
	return ggml, err
}
140

Daniel Hiltgen's avatar
Daniel Hiltgen committed
141
// NewLlamaServer will run a server for the given GPUs
142
func NewLlamaServer(systemInfo ml.SystemInfo, gpus []ml.DeviceInfo, modelPath string, f *ggml.GGML, adapters, projectors []string, opts api.Options, numParallel int) (LlamaServer, error) {
Jesse Gross's avatar
Jesse Gross committed
143
144
145
146
	var llamaModel *llama.Model
	var textProcessor model.TextProcessor
	var err error
	if envconfig.NewEngine() || f.KV().OllamaEngineRequired() {
147
148
149
150
151
		if len(projectors) == 0 {
			textProcessor, err = model.NewTextProcessor(modelPath)
		} else {
			err = errors.New("split vision models aren't supported")
		}
Jesse Gross's avatar
Jesse Gross committed
152
153
154
155
		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
167
168
	// 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)
169
170
	}

171
172
	opts.NumBatch = min(opts.NumBatch, opts.NumCtx)

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

175
	defaultThreads := systemInfo.ThreadCount
Jesse Gross's avatar
Jesse Gross committed
176
177
178
179
	if opts.NumThread > 0 {
		loadRequest.NumThreads = opts.NumThread
	} else if defaultThreads > 0 {
		loadRequest.NumThreads = defaultThreads
180
	}
Michael Yang's avatar
Michael Yang committed
181

Jesse Gross's avatar
Jesse Gross committed
182
	// TODO - NUMA support currently doesn't work properly
183
184

	if opts.MainGPU > 0 {
Jesse Gross's avatar
Jesse Gross committed
185
		loadRequest.MainGPU = opts.MainGPU
186
187
	}

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

192
193
	fa := envconfig.FlashAttention(f.FlashAttention())

Jesse Gross's avatar
Jesse Gross committed
194
195
	// 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.
196
	if fa && !ml.FlashAttentionSupported(gpus) {
197
198
199
		slog.Warn("flash attention enabled but not supported by gpu")
		fa = false
	}
Sam's avatar
Sam committed
200

Michael Yang's avatar
Michael Yang committed
201
	if fa && !f.SupportsFlashAttention() {
202
203
204
205
		slog.Warn("flash attention enabled but not supported by model")
		fa = false
	}

206
	kvct := strings.ToLower(envconfig.KvCacheType())
207
208
209

	if fa {
		slog.Info("enabling flash attention")
Jesse Gross's avatar
Jesse Gross committed
210
		loadRequest.FlashAttention = true
211
212
213

		// Flash Attention also supports kv cache quantization
		// Enable if the requested and kv cache type is supported by the model
214
		if f.SupportsKVCacheType(kvct) {
Jesse Gross's avatar
Jesse Gross committed
215
			loadRequest.KvCacheType = kvct
216
217
		} else {
			slog.Warn("kv cache type not supported by model", "type", kvct)
Sam's avatar
Sam committed
218
		}
219
220
221
	} else if kvct != "" && kvct != "f16" {
		slog.Warn("quantized kv cache requested but flash attention disabled", "type", kvct)
	}
222

223
224
225
226
227
228
229
	gpuLibs := ml.LibraryPaths(gpus)
	status := NewStatusWriter(os.Stderr)
	cmd, port, err := StartRunner(
		textProcessor != nil,
		modelPath,
		gpuLibs,
		status,
230
		ml.GetVisibleDevicesEnv(gpus, false),
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
	)

	s := llmServer{
		port:           port,
		cmd:            cmd,
		status:         status,
		options:        opts,
		modelPath:      modelPath,
		loadRequest:    loadRequest,
		llamaModel:     llamaModel,
		llamaModelLock: &sync.Mutex{},
		sem:            semaphore.NewWeighted(int64(numParallel)),
		totalLayers:    f.KV().BlockCount() + 1,
		loadStart:      time.Now(),
		done:           make(chan error, 1),
Jesse Gross's avatar
Jesse Gross committed
246
247
	}

248
249
250
251
252
253
254
255
256
257
	if err != nil {
		var msg string
		if s.status != nil && s.status.LastErrMsg != "" {
			msg = s.status.LastErrMsg
		}
		err := fmt.Errorf("error starting runner: %v %s", err, msg)
		if llamaModel != nil {
			llama.FreeModel(llamaModel)
		}
		return nil, err
Michael Yang's avatar
Michael Yang committed
258
259
	}

260
261
262
263
264
265
266
267
	// reap subprocess when it exits
	go func() {
		err := s.cmd.Wait()
		// Favor a more detailed message over the process exit status
		if err != nil && s.status != nil && s.status.LastErrMsg != "" {
			slog.Error("llama runner terminated", "error", err)
			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"
Jesse Gross's avatar
Jesse Gross committed
268
			}
269
270
271
			s.done <- errors.New(s.status.LastErrMsg)
		} else {
			s.done <- err
272
		}
273
	}()
274

275
	if textProcessor != nil {
276
		return &ollamaServer{llmServer: s, textProcessor: textProcessor}, nil
277
278
	} else {
		return &llamaServer{llmServer: s, ggml: f}, nil
Michael Yang's avatar
Michael Yang committed
279
	}
280
}
Jesse Gross's avatar
Jesse Gross committed
281

282
283
284
func StartRunner(ollamaEngine bool, modelPath string, gpuLibs []string, out io.Writer, extraEnvs map[string]string) (cmd *exec.Cmd, port int, err error) {
	var exe string
	exe, err = os.Executable()
285
	if err != nil {
286
		return nil, 0, fmt.Errorf("unable to lookup executable path: %w", err)
287
288
289
290
291
292
	}

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

293
294
295
296
297
298
	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()
Jesse Gross's avatar
Jesse Gross committed
299
		}
300
301
302
303
304
305
306
307
308
309
	}
	if port == 0 {
		slog.Debug("ResolveTCPAddr failed, using random port")
		port = rand.Intn(65535-49152) + 49152 // get a random port in the ephemeral range
	}
	params := []string{"runner"}
	if ollamaEngine {
		params = append(params, "--ollama-engine")
	}
	if modelPath != "" {
Jesse Gross's avatar
Jesse Gross committed
310
		params = append(params, "--model", modelPath)
311
312
	}
	params = append(params, "--port", strconv.Itoa(port))
Daniel Hiltgen's avatar
Daniel Hiltgen committed
313

314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
	var pathEnv string
	switch runtime.GOOS {
	case "windows":
		pathEnv = "PATH"
	case "darwin":
		pathEnv = "DYLD_LIBRARY_PATH"
	default:
		pathEnv = "LD_LIBRARY_PATH"
	}

	// Note: we always put our dependency paths first
	// since these are the exact version we compiled/linked against
	libraryPaths := append([]string{}, gpuLibs...)
	if libraryPath, ok := os.LookupEnv(pathEnv); ok {
		libraryPaths = append(libraryPaths, filepath.SplitList(libraryPath)...)
	}

	cmd = exec.Command(exe, params...)

	cmd.Env = os.Environ()
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350

	if out != nil {
		stdout, err := cmd.StdoutPipe()
		if err != nil {
			return nil, 0, fmt.Errorf("failed to spawn server stdout pipe: %w", err)
		}
		stderr, err := cmd.StderrPipe()
		if err != nil {
			return nil, 0, fmt.Errorf("failed to spawn server stderr pipe: %w", err)
		}
		go func() {
			io.Copy(out, stdout) //nolint:errcheck
		}()
		go func() {
			io.Copy(out, stderr) //nolint:errcheck
		}()
	}
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
	cmd.SysProcAttr = LlamaServerSysProcAttr

	// Always filter down the set of GPUs in case there are any unsupported devices that might crash
	pathEnvVal := strings.Join(libraryPaths, string(filepath.ListSeparator))

	// Update or add the path variable with our adjusted version
	pathNeeded := true
	ollamaPathNeeded := true
	extraEnvsDone := map[string]bool{}
	for k := range extraEnvs {
		extraEnvsDone[k] = false
	}
	for i := range cmd.Env {
		cmp := strings.SplitN(cmd.Env[i], "=", 2)
		if strings.EqualFold(cmp[0], pathEnv) {
			cmd.Env[i] = pathEnv + "=" + pathEnvVal
			pathNeeded = false
		} else if strings.EqualFold(cmp[0], "OLLAMA_LIBRARY_PATH") {
			cmd.Env[i] = "OLLAMA_LIBRARY_PATH=" + strings.Join(gpuLibs, string(filepath.ListSeparator))
			ollamaPathNeeded = false
		} else if len(extraEnvs) != 0 {
			for k, v := range extraEnvs {
				if strings.EqualFold(cmp[0], k) {
					cmd.Env[i] = k + "=" + v
					extraEnvsDone[k] = true
Daniel Hiltgen's avatar
Daniel Hiltgen committed
376
				}
377
			}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
378
		}
379
380
381
382
383
384
385
386
387
388
	}
	if pathNeeded {
		cmd.Env = append(cmd.Env, pathEnv+"="+pathEnvVal)
	}
	if ollamaPathNeeded {
		cmd.Env = append(cmd.Env, "OLLAMA_LIBRARY_PATH="+strings.Join(gpuLibs, string(filepath.ListSeparator)))
	}
	for k, done := range extraEnvsDone {
		if !done {
			cmd.Env = append(cmd.Env, k+"="+extraEnvs[k])
389
		}
390
	}
391

392
393
	slog.Info("starting runner", "cmd", cmd)
	slog.Debug("subprocess", "", filteredEnv(cmd.Env))
Daniel Hiltgen's avatar
Daniel Hiltgen committed
394

395
396
	if err = cmd.Start(); err != nil {
		return nil, 0, err
Jesse Gross's avatar
Jesse Gross committed
397
	}
398
399
	err = nil
	return
Jesse Gross's avatar
Jesse Gross committed
400
401
402
403
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
453
454
455
456
457
}

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")

458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
func (s *llamaServer) Load(ctx context.Context, systemInfo ml.SystemInfo, systemGPUs []ml.DeviceInfo, requireFull bool) ([]ml.DeviceID, error) {
	slog.Info("loading model", "model layers", s.totalLayers, "requested", s.options.NumGPU)

	gpus := append(make([]ml.DeviceInfo, 0, len(systemGPUs)), systemGPUs...)

	// Synthesize memory allocation information based on our estimates
	s.mem = &ml.BackendMemory{CPU: ml.DeviceMemory{
		Name:    "CPU",
		Weights: make([]uint64, s.totalLayers),
		Cache:   make([]uint64, s.totalLayers),
	}, GPUs: make([]ml.DeviceMemory, len(gpus))}

	for i := range s.mem.GPUs {
		s.mem.GPUs[i].Name = gpus[i].Name
		s.mem.GPUs[i].DeviceID = gpus[i].DeviceID
		s.mem.GPUs[i].Weights = make([]uint64, s.totalLayers)
		s.mem.GPUs[i].Cache = make([]uint64, s.totalLayers)
	}
Jesse Gross's avatar
Jesse Gross committed
476

477
478
479
480
481
482
483
	// Check if embedding model and adjust batch size accordingly
	_, isEmbedding := s.ggml.KV()[fmt.Sprintf("%s.pooling_type", s.ggml.KV().Architecture())]
	if isEmbedding && s.loadRequest.BatchSize < s.options.NumCtx {
		s.loadRequest.BatchSize = s.options.NumCtx
		slog.Info("embedding model detected, setting batch size to context length", "batch_size", s.loadRequest.BatchSize)
	}

484
485
486
487
488
489
490
491
	kv, graphPartialOffload, graphFullOffload := s.ggml.GraphSize(uint64(s.options.NumCtx), uint64(s.loadRequest.BatchSize),
		s.loadRequest.Parallel, s.loadRequest.KvCacheType, s.loadRequest.FlashAttention)

	// Use the size of one layer as a buffer
	layers := s.ggml.Tensors().GroupLayers()
	if blk0, ok := layers["blk.0"]; ok {
		for i := range gpus {
			gpus[i].FreeMemory -= blk0.Size() + kv[0]
492
493
		}
	} else {
494
495
496
497
498
499
500
501
		slog.Warn("model missing blk.0 layer size")
	}

	// Assign all the layers to the CPU for now, they will get reassigned later
	for i := range s.ggml.KV().BlockCount() {
		if blk, ok := layers[fmt.Sprintf("blk.%d", i)]; ok {
			s.mem.CPU.Weights[i] = blk.Size()
			s.mem.CPU.Cache[i] += kv[i]
Jesse Gross's avatar
Jesse Gross committed
502
503
504
		}
	}

505
506
507
508
509
510
511
512
513
514
515
	// We historically haven't included InputWeights in the model size
	var outputWeights uint64
	if layer, ok := layers["output_norm"]; ok {
		outputWeights += layer.Size()
	}
	if layer, ok := layers["output"]; ok {
		outputWeights += layer.Size()
	} else if layer, ok := layers["token_embd"]; ok {
		outputWeights += layer.Size()
	}
	s.mem.CPU.Weights[s.totalLayers-1] = outputWeights
Jesse Gross's avatar
Jesse Gross committed
516

517
518
519
520
521
522
523
	// The vision projector is always loaded on the first GPU if available.
	// This can't be assigned by us, so just subtract it from free space
	projectorGPU := -1
	var projectorWeights uint64
	if len(gpus) > 0 {
		for _, projector := range s.loadRequest.LoraPath {
			projectorWeights += projectorMemoryRequirements(projector)
Jesse Gross's avatar
Jesse Gross committed
524
		}
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541

		// llama.cpp uses the first discrete GPU if available, otherwise the first iGPU
		firstIntegrated := -1
		for i := range gpus {
			if !gpus[i].Integrated {
				projectorGPU = i
				break
			}
			if firstIntegrated == -1 {
				firstIntegrated = i
			}
		}
		if projectorGPU == -1 {
			projectorGPU = firstIntegrated
		}

		gpus[projectorGPU].FreeMemory -= projectorWeights
Jesse Gross's avatar
Jesse Gross committed
542
543
	}

544
545
546
547
548
549
550
551
552
	var kvTotal uint64
	for _, kvLayer := range kv {
		kvTotal += kvLayer
	}

	if graphPartialOffload == 0 {
		headsKV := s.ggml.KV().HeadCountKVMin()
		if headsKV == 0 {
			headsKV = 1
Jesse Gross's avatar
Jesse Gross committed
553
		}
554
555
556
557
558
		gqa := s.ggml.KV().HeadCountMax() / headsKV
		graphPartialOffload = gqa * kvTotal / 6
	}
	if graphFullOffload == 0 {
		graphFullOffload = graphPartialOffload
Jesse Gross's avatar
Jesse Gross committed
559
560
	}

561
562
563
564
	// On Metal there's no partial offload overhead
	if len(gpus) > 0 && gpus[0].Library == "Metal" {
		graphPartialOffload = graphFullOffload
	}
Jesse Gross's avatar
Jesse Gross committed
565

566
567
568
569
570
	// Create a layout based on the memory data that we've built. The compute graph
	// for GPUs is iteratively assigned based on the number of GPUs that are required.
	var gpuLayers ml.GPULayersList
	for {
		prevGPULayers := gpuLayers
Jesse Gross's avatar
Jesse Gross committed
571

572
573
574
575
576
		var err error
		gpuLayers, err = s.createLayout(systemInfo, gpus, s.mem, requireFull, 0)
		if err != nil {
			return nil, err
		}
Jesse Gross's avatar
Jesse Gross committed
577

578
579
580
581
582
583
584
585
		if len(gpuLayers) > len(prevGPULayers) {
			for _, gl := range gpuLayers {
				for i := range s.mem.GPUs {
					if gl.DeviceID == s.mem.GPUs[i].DeviceID {
						s.mem.GPUs[i].Graph = max(graphPartialOffload, graphFullOffload)
						break
					}
				}
Jesse Gross's avatar
Jesse Gross committed
586
			}
587
588
		} else {
			break
Jesse Gross's avatar
Jesse Gross committed
589
		}
590
591
592
593
594
595
596
	}

	// This maintains the historical assignment of graph sizes, though it isn't fully accurate
	graphSize := graphFullOffload
	if gpuLayers.Sum() < int(s.totalLayers) {
		graphSize = graphPartialOffload
	}
Jesse Gross's avatar
Jesse Gross committed
597

598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
	// For all layers that we have assigned to GPUs, move them in the memory data so
	// that it is reported accurately
	for _, gl := range gpuLayers {
		for i := range s.mem.GPUs {
			if gl.DeviceID == s.mem.GPUs[i].DeviceID {
				for _, l := range gl.Layers {
					s.mem.GPUs[i].Weights[l] = s.mem.CPU.Weights[l]
					s.mem.GPUs[i].Cache[l] = s.mem.CPU.Cache[l]

					s.mem.CPU.Weights[l] = 0
					s.mem.CPU.Cache[l] = 0
				}

				s.mem.GPUs[i].Graph = graphSize
				break
			}
Jesse Gross's avatar
Jesse Gross committed
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
	if projectorGPU > 0 && len(s.mem.GPUs[projectorGPU].Weights) > 0 {
		s.mem.GPUs[projectorGPU].Weights[s.totalLayers-1] += projectorWeights
	}

	slog.Debug("memory", "estimate", s.mem)
	s.mem.Log(slog.LevelInfo)

	// The llama engine uses mmap by default
	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.totalLayers {
			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" && len(gpus) > 0 && gpus[0].Library == "CUDA" && s.options.UseMMap == nil) ||
		(runtime.GOOS == "linux" && systemInfo.FreeMemory < s.TotalSize() && s.options.UseMMap == nil) ||
		(len(gpus) == 0 && s.options.UseMMap == nil) ||
		(len(gpus) > 0 && gpus[0].Library == "Vulkan" && s.options.UseMMap == nil) ||
		(s.options.UseMMap != nil && !*s.options.UseMMap) {
		s.loadRequest.UseMmap = false
	}

Jesse Gross's avatar
Jesse Gross committed
648
	if err := s.waitUntilRunnerLaunched(ctx); err != nil {
649
		return nil, err
Jesse Gross's avatar
Jesse Gross committed
650
651
	}

652
	s.loadRequest.GPULayers = gpuLayers
Jesse Gross's avatar
Jesse Gross committed
653
654
	resp, err := s.initModel(ctx, s.loadRequest, LoadOperationCommit)
	if err != nil {
655
		return nil, err
Jesse Gross's avatar
Jesse Gross committed
656
657
658
	}

	if !resp.Success {
659
		return nil, errors.New("failed to allocate memory for model")
Jesse Gross's avatar
Jesse Gross committed
660
661
662
663
664
	}

	// 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
665
	return uniqueDeviceIDs(s.loadRequest.GPULayers), s.WaitUntilRunning(ctx)
Jesse Gross's avatar
Jesse Gross committed
666
667
}

668
669
670
671
func projectorMemoryRequirements(filename string) (weights uint64) {
	file, err := os.Open(filename)
	if err != nil {
		return 0
Jesse Gross's avatar
Jesse Gross committed
672
	}
673
	defer file.Close()
Jesse Gross's avatar
Jesse Gross committed
674

675
676
677
	ggml, err := ggml.Decode(file, 1024)
	if err != nil {
		return 0
Jesse Gross's avatar
Jesse Gross committed
678
679
	}

680
681
	for _, layer := range ggml.Tensors().GroupLayers() {
		weights += layer.Size()
Jesse Gross's avatar
Jesse Gross committed
682
683
	}

684
	return weights
Jesse Gross's avatar
Jesse Gross committed
685
686
687
688
689
690
691
692
693
694
695
}

// 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.
696
697
//
// Returns the list of GPU IDs that were used in the final allocation on success
698
func (s *ollamaServer) Load(ctx context.Context, systemInfo ml.SystemInfo, gpus []ml.DeviceInfo, requireFull bool) ([]ml.DeviceID, error) {
Jesse Gross's avatar
Jesse Gross committed
699
700
701
702
703
	var success bool
	defer func() {
		if !success {
			s.initModel(ctx, LoadRequest{}, LoadOperationClose)
		}
704
705
706
		if s.mem != nil {
			s.mem.Log(slog.LevelInfo)
		}
Jesse Gross's avatar
Jesse Gross committed
707
708
709
710
711
712
713
714
715
	}()

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

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

	gpuLayers, err := s.createLayout(systemInfo, gpus, s.mem, requireFull, backoff)
	if err != nil {
716
		return nil, err
Jesse Gross's avatar
Jesse Gross committed
717
718
719
	}

	if err := s.waitUntilRunnerLaunched(ctx); err != nil {
720
		return nil, err
Jesse Gross's avatar
Jesse Gross committed
721
722
723
724
725
726
727
728
729
	}

nextOperation:
	for operation := LoadOperationFit; operation < LoadOperationCommit; operation++ {
	nextLoad:
		for {
			s.loadRequest.GPULayers = gpuLayers
			resp, err := s.initModel(ctx, s.loadRequest, operation)
			if err != nil {
730
				return nil, err
Jesse Gross's avatar
Jesse Gross committed
731
732
733
734
735
736
737
738
739
740
741
			}

			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 {
742
					return nil, err
Jesse Gross's avatar
Jesse Gross committed
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
				}

				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 {
776
							return nil, err
Jesse Gross's avatar
Jesse Gross committed
777
778
779
780
781
782
						}
						slog.Debug("new layout created", "layers", newGPULayers)

						s.loadRequest.GPULayers = newGPULayers
						resp, err = s.initModel(ctx, s.loadRequest, operation)
						if err != nil {
783
							return nil, err
Jesse Gross's avatar
Jesse Gross committed
784
785
786
787
788
789
790
791
						}

						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 {
792
								return nil, err
Jesse Gross's avatar
Jesse Gross committed
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
							}

							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 {
817
					return nil, fmt.Errorf("memory layout cannot be allocated with num_gpu = %v", s.options.NumGPU)
Jesse Gross's avatar
Jesse Gross committed
818
819
820
821
822
				}

				// 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
823
				// time. Apply a backoff to try to find the real amount of available space.
Jesse Gross's avatar
Jesse Gross committed
824
825
				if backoff > 1 {
					slog.Warn("memory layout cannot be allocated", "memory", resp.Memory)
826
					return nil, errors.New("memory layout cannot be allocated")
Jesse Gross's avatar
Jesse Gross committed
827
				} else {
828
					backoff += 0.1
Jesse Gross's avatar
Jesse Gross committed
829
830
831
832
833
834
835
836
837
838
				}

				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 {
839
		return nil, err
Jesse Gross's avatar
Jesse Gross committed
840
841
842
843
844
845
846
	}

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

	if !success {
		slog.Warn("failed to commit memory for model", "memory", resp.Memory)
847
		return nil, errors.New("failed to commit memory for model")
Jesse Gross's avatar
Jesse Gross committed
848
849
	}

850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
	return uniqueDeviceIDs(gpuLayers), nil
}

func uniqueDeviceIDs(gpuLayers ml.GPULayersList) []ml.DeviceID {
	devices := []ml.DeviceID{}
	for _, layer := range gpuLayers {
		new := true
		for _, ID := range devices {
			if layer.DeviceID == ID {
				new = false
				break
			}
		}
		if new {
			devices = append(devices, layer.DeviceID)
		}
	}
	return devices
Jesse Gross's avatar
Jesse Gross committed
868
869
870
871
872
873
874
875
}

// 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
876
func (s *llmServer) createLayout(systemInfo ml.SystemInfo, systemGPUs []ml.DeviceInfo, memory *ml.BackendMemory, requireFull bool, backoff float32) (ml.GPULayersList, error) {
Jesse Gross's avatar
Jesse Gross committed
877
878
	if memory == nil {
		memory = &ml.BackendMemory{CPU: ml.DeviceMemory{
879
880
			Weights: make([]uint64, s.totalLayers),
			Cache:   make([]uint64, s.totalLayers),
Jesse Gross's avatar
Jesse Gross committed
881
882
		}}
	}
883
	gpuLayers, layers := s.buildLayout(systemGPUs, memory, requireFull, backoff)
884
	err := s.verifyLayout(systemInfo, systemGPUs, memory, requireFull, gpuLayers, layers)
885
886
887
888
889
890
	if err != nil {
		return nil, err
	}
	return gpuLayers, nil
}

891
func (s *llmServer) buildLayout(systemGPUs []ml.DeviceInfo, memory *ml.BackendMemory, requireFull bool, backoff float32) (ml.GPULayersList, []uint64) {
892
893
	gpus := append(make([]ml.DeviceInfo, 0, len(systemGPUs)), systemGPUs...)
	sort.Sort(sort.Reverse(ml.ByFreeMemory(gpus)))
Jesse Gross's avatar
Jesse Gross committed
894
895
896
897

	layers := make([]uint64, len(memory.CPU.Weights))
	for i := range layers {
		for j := range memory.GPUs {
898
899
			layers[i] += memory.GPUs[j].Weights[i]
			layers[i] += memory.GPUs[j].Cache[i]
Jesse Gross's avatar
Jesse Gross committed
900
		}
901
902
		layers[i] += memory.CPU.Weights[i]
		layers[i] += memory.CPU.Cache[i]
903
		logutil.Trace("layer to assign", "layer", i, "size", format.HumanBytes2(layers[i]))
Jesse Gross's avatar
Jesse Gross committed
904
905
906
	}

	gpuLayers := ml.GPULayersList{}
907
	for _, gl := range ml.ByLibrary(gpus) {
Jesse Gross's avatar
Jesse Gross committed
908
909
910
911
912
913
914
915
		// 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 {
916
				if gl[i].DeviceID == memory.GPUs[j].DeviceID {
917
					if memory.GPUs[j].Graph != 0 {
Jesse Gross's avatar
Jesse Gross committed
918
919
920
						lastUsedGPU = i
					}

921
					reserved := uint64(float32(gl[i].FreeMemory)*backoff) + gl[i].MinimumMemory() + envconfig.GpuOverhead() + memory.GPUs[j].Graph
Jesse Gross's avatar
Jesse Gross committed
922
923
924
925
926
927
					if gl[i].FreeMemory > reserved {
						gl[i].FreeMemory -= reserved
					} else {
						gl[i].FreeMemory = 0
					}

928
					slog.Debug("available gpu", "id", gl[i].ID, "library", gl[i].Library,
Jesse Gross's avatar
Jesse Gross committed
929
						"available layer vram", format.HumanBytes2(gl[i].FreeMemory),
930
						"backoff", fmt.Sprintf("%.2f", backoff), "minimum", format.HumanBytes2(gl[i].MinimumMemory()),
Jesse Gross's avatar
Jesse Gross committed
931
						"overhead", format.HumanBytes2(envconfig.GpuOverhead()),
932
						"graph", format.HumanBytes2(memory.GPUs[j].Graph))
Jesse Gross's avatar
Jesse Gross committed
933
934
935
936
937
938
939
940
941
942
943

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

944
		libraryGpuLayers := assignLayers(layers, gl, requireFull, s.options.NumGPU, lastUsedGPU)
Jesse Gross's avatar
Jesse Gross committed
945
946
947
948
		if libraryGpuLayers.Sum() > gpuLayers.Sum() {
			gpuLayers = libraryGpuLayers
		}
	}
949
	return gpuLayers, layers
950
}
Jesse Gross's avatar
Jesse Gross committed
951

952
// verifyLayout ensures that we don't exceed limits, such as requirements about partial offloading or system memory
953
func (s *llmServer) verifyLayout(systemInfo ml.SystemInfo, systemGPUs []ml.DeviceInfo, memory *ml.BackendMemory, requireFull bool, gpuLayers ml.GPULayersList, layers []uint64) error {
Jesse Gross's avatar
Jesse Gross committed
954
	// These sizes will only increase as we go through additional iterations and get additional information.
955
	cpuSize := memory.InputWeights + memory.CPU.Graph
Jesse Gross's avatar
Jesse Gross committed
956
957
958
	var vramSize uint64
	for _, gl := range gpuLayers {
		for _, gpu := range memory.GPUs {
959
			if gl.DeviceID == gpu.DeviceID {
960
				vramSize += gpu.Graph
Jesse Gross's avatar
Jesse Gross committed
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
				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 {
980
981
		if len(systemGPUs) > 0 && gpuLayers.Sum() < len(layers) && (s.options.NumGPU < 0 || gpuLayers.Sum() < s.options.NumGPU) {
			slog.Info("model requires more gpu memory than is currently available, evicting a model to make space", "loaded layers", gpuLayers.Sum())
982
			return ErrLoadRequiredFull
Jesse Gross's avatar
Jesse Gross committed
983
984
		}

985
		if cpuSize > systemInfo.FreeMemory {
986
987
			slog.Info("model requires more system memory than is currently available, evicting a model to make space", "required", cpuSize, "free", systemInfo.FreeMemory)
			return fmt.Errorf("model requires more system memory than is currently available %w", ErrLoadRequiredFull)
Jesse Gross's avatar
Jesse Gross committed
988
989
990
991
992
993
		}
	}

	// 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" {
994
		available := systemInfo.FreeMemory + systemInfo.FreeSwap
Jesse Gross's avatar
Jesse Gross committed
995
		if cpuSize > available {
996
997
			slog.Warn("model request too large for system", "requested", format.HumanBytes2(cpuSize), "available", format.HumanBytes2(available), "total", format.HumanBytes2(systemInfo.TotalMemory), "free", format.HumanBytes2(systemInfo.FreeMemory), "swap", format.HumanBytes2(systemInfo.FreeSwap))
			return fmt.Errorf("model requires more system memory (%s) than is available (%s)", format.HumanBytes2(cpuSize), format.HumanBytes2(available))
Jesse Gross's avatar
Jesse Gross committed
998
999
		}
	} else {
1000
		if vramSize > systemInfo.TotalMemory {
Jesse Gross's avatar
Jesse Gross committed
1001
1002
1003
1004
1005
1006
1007
			// 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{}
		}
	}

1008
	if len(systemGPUs) > 0 && gpuLayers.Sum() == 0 {
Jesse Gross's avatar
Jesse Gross committed
1009
1010
1011
		slog.Debug("insufficient VRAM to load any model layers")
	}

1012
	return nil
Jesse Gross's avatar
Jesse Gross committed
1013
1014
1015
}

// assignLayers packs the maximum number of layers onto the smallest set of GPUs and comes up with a layer assignment
1016
func assignLayers(layers []uint64, gpus []ml.DeviceInfo, requireFull bool, requestedLayers int, lastUsedGPU int) (gpuLayers ml.GPULayersList) {
1017
1018
1019
1020
1021
1022
1023
	// If the user is manually overriding parameters, treat all GPUs equally so they split according to VRAM
	if requestedLayers >= 0 || envconfig.SchedSpread() {
		for i := range gpus {
			gpus[i].Integrated = false
		}
	}

Jesse Gross's avatar
Jesse Gross committed
1024
1025
1026
1027
1028
1029
1030
1031
	// 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
1032
				forceRequest := i == len(gpus)-1 && !requireFull
Jesse Gross's avatar
Jesse Gross committed
1033
1034
1035
1036
1037
1038
				gpuLayers = findBestFit(layers, gpus[:i+1], requestedLayers, forceRequest)
				if gpuLayers.Sum() == len(layers) || gpuLayers.Sum() == requestedLayers {
					break
				}
			}
		} else {
1039
			gpuLayers = findBestFit(layers, gpus, requestedLayers, !requireFull)
Jesse Gross's avatar
Jesse Gross committed
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
		}

		// 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
1056
1057
// each GPU and a small one will force even balancing. Higher performance GPUs are
// used first.
1058
func findBestFit(layers []uint64, gpus []ml.DeviceInfo, requestedLayers int, forceRequest bool) (gpuLayers ml.GPULayersList) {
1059
1060
1061
	for _, gl := range ml.ByPerformance(gpus) {
		var high float32 = 1
		var low float32 = 0
Jesse Gross's avatar
Jesse Gross committed
1062

1063
1064
1065
1066
		// If we need to fulfill the requested number of layers, pretend we have almost infinite VRAM
		if requestedLayers >= 0 && forceRequest {
			high = 1000
		}
Jesse Gross's avatar
Jesse Gross committed
1067

1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
		bestAssignments := greedyFit(layers, gl, high, requestedLayers)
		maxNumGPU := bestAssignments.Sum()

		for high-low > 1e-6 {
			mid := (low + high) / 2
			assignments := greedyFit(layers, gl, mid, requestedLayers)
			if assignments.Sum() == maxNumGPU {
				high = mid
				bestAssignments = assignments
			} else {
				low = mid
			}
Jesse Gross's avatar
Jesse Gross committed
1080
		}
1081
1082
1083
1084

		layers = layers[:len(layers)-bestAssignments.Sum()]
		requestedLayers -= bestAssignments.Sum()
		gpuLayers = append(bestAssignments, gpuLayers...)
Jesse Gross's avatar
Jesse Gross committed
1085
	}
1086
1087

	return gpuLayers
Jesse Gross's avatar
Jesse Gross committed
1088
1089
1090
}

// greedyFit assigns layers incrementally to GPUs, spilling over as each runs out of free space
1091
func greedyFit(layers []uint64, gpus []ml.DeviceInfo, capacity float32, requestedLayers int) (gpuLayers ml.GPULayersList) {
Jesse Gross's avatar
Jesse Gross committed
1092
	device := len(gpus) - 1
1093
	gpuLayers = ml.GPULayersList{{DeviceID: gpus[device].DeviceID}}
Jesse Gross's avatar
Jesse Gross committed
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
	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
			}
1111
			gpuLayers = append(ml.GPULayersList{{DeviceID: gpus[device].DeviceID}}, gpuLayers...)
Jesse Gross's avatar
Jesse Gross committed
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
			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
1177
1178
1179
1180
1181
1182
}

type ServerStatus int

const ( // iota is reset to 0
	ServerStatusReady ServerStatus = iota
1183
	ServerStatusNoSlotsAvailable
Jesse Gross's avatar
Jesse Gross committed
1184
	ServerStatusLaunched
1185
1186
1187
1188
1189
	ServerStatusLoadingModel
	ServerStatusNotResponding
	ServerStatusError
)

1190
func (s ServerStatus) String() string {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1191
1192
1193
	switch s {
	case ServerStatusReady:
		return "llm server ready"
1194
	case ServerStatusNoSlotsAvailable:
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1195
		return "llm busy - no slots available"
Jesse Gross's avatar
Jesse Gross committed
1196
1197
	case ServerStatusLaunched:
		return "llm server launched"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1198
1199
1200
1201
1202
1203
1204
1205
1206
	case ServerStatusLoadingModel:
		return "llm server loading model"
	case ServerStatusNotResponding:
		return "llm server not responding"
	default:
		return "llm server error"
	}
}

1207
1208
1209
type ServerStatusResponse struct {
	Status   ServerStatus `json:"status"`
	Progress float32      `json:"progress"`
1210
1211
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1212
func (s *llmServer) getServerStatus(ctx context.Context) (ServerStatus, error) {
1213
1214
1215
1216
1217
1218
	// Fail fast if its exited
	if s.cmd.ProcessState != nil {
		msg := ""
		if s.status != nil && s.status.LastErrMsg != "" {
			msg = s.status.LastErrMsg
		}
1219
1220
		if s.cmd.ProcessState.ExitCode() == -1 {
			// Most likely a signal killed it, log some more details to try to help troubleshoot
1221
			slog.Warn("llama runner process no longer running", "sys", s.cmd.ProcessState.Sys(), "string", s.cmd.ProcessState)
1222
		}
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
		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
1235
			return ServerStatusNotResponding, errors.New("server not responding")
1236
		}
1237
1238
1239
		if strings.Contains(err.Error(), "connection refused") {
			return ServerStatusNotResponding, errors.New("connection refused")
		}
1240
1241
1242
1243
1244
1245
1246
1247
1248
		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)
	}

1249
1250
	var ssr ServerStatusResponse
	if err := json.Unmarshal(body, &ssr); err != nil {
1251
1252
1253
		return ServerStatusError, fmt.Errorf("health unmarshal encode response: %w", err)
	}

1254
1255
1256
1257
	switch ssr.Status {
	case ServerStatusLoadingModel:
		s.loadProgress = ssr.Progress
		return ssr.Status, nil
Jesse Gross's avatar
Jesse Gross committed
1258
	case ServerStatusLaunched, ServerStatusReady, ServerStatusNoSlotsAvailable:
1259
		return ssr.Status, nil
1260
	default:
1261
		return ssr.Status, fmt.Errorf("server error: %+v", ssr)
1262
1263
1264
	}
}

1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
// 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
1288
func (s *llmServer) Ping(ctx context.Context) error {
1289
1290
1291
1292
1293
1294
1295
1296
	_, err := s.getServerStatus(ctx)
	if err != nil {
		slog.Debug("server unhealthy", "error", err)
		return err
	}
	return nil
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1297
func (s *llmServer) WaitUntilRunning(ctx context.Context) error {
1298
	stallDuration := envconfig.LoadTimeout()    // If no progress happens
1299
	stallTimer := time.Now().Add(stallDuration) // give up if we stall
1300
1301
1302

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

1305
1306
	for {
		select {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1307
		case <-ctx.Done():
1308
			slog.Warn("client connection closed before server finished loading, aborting load")
1309
			return fmt.Errorf("timed out waiting for llama runner to start: %w", ctx.Err())
1310
		case err := <-s.done:
1311
			return fmt.Errorf("llama runner process has terminated: %w", err)
1312
1313
		default:
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1314
		if time.Now().After(stallTimer) {
ManniX-ITA's avatar
ManniX-ITA committed
1315
			// timeout
1316
1317
1318
1319
			msg := ""
			if s.status != nil && s.status.LastErrMsg != "" {
				msg = s.status.LastErrMsg
			}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1320
			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
1321
1322
1323
1324
1325
		}
		if s.cmd.ProcessState != nil {
			msg := ""
			if s.status != nil && s.status.LastErrMsg != "" {
				msg = s.status.LastErrMsg
1326
			}
ManniX-ITA's avatar
ManniX-ITA committed
1327
1328
			return fmt.Errorf("llama runner process no longer running: %d %s", s.cmd.ProcessState.ExitCode(), msg)
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1329
1330
		ctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
		defer cancel()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1331
		priorProgress := s.loadProgress
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1332
1333
1334
		status, _ := s.getServerStatus(ctx)
		if lastStatus != status && status != ServerStatusReady {
			// Only log on status changes
1335
			slog.Info("waiting for server to become available", "status", status)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1336
		}
ManniX-ITA's avatar
ManniX-ITA committed
1337
1338
		switch status {
		case ServerStatusReady:
Jesse Gross's avatar
Jesse Gross committed
1339
			slog.Info(fmt.Sprintf("llama runner started in %0.2f seconds", time.Since(s.loadStart).Seconds()))
ManniX-ITA's avatar
ManniX-ITA committed
1340
1341
			return nil
		default:
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1342
			lastStatus = status
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1343
1344
1345
1346
			// 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)
1347
			} else if !fullyLoaded && int(s.loadProgress*100.0) >= 100 {
1348
				slog.Debug("model load completed, waiting for server to become available", "status", status)
1349
				stallTimer = time.Now().Add(stallDuration)
1350
				fullyLoaded = true
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1351
			}
ManniX-ITA's avatar
ManniX-ITA committed
1352
1353
			time.Sleep(time.Millisecond * 250)
			continue
1354
1355
1356
1357
		}
	}
}

1358
1359
1360
1361
1362
1363
1364
func (s *llmServer) Pid() int {
	if s.cmd != nil && s.cmd.Process != nil {
		return s.cmd.Process.Pid
	}
	return -1
}

1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
func (s *llmServer) GetPort() int {
	return s.port
}

func (s *llmServer) HasExited() bool {
	if s.cmd != nil && s.cmd.ProcessState != nil && s.cmd.ProcessState.ExitCode() >= 0 {
		return true
	}
	return false
}

1376
var grammarJSON = `
1377
1378
1379
1380
root   ::= object
value  ::= object | array | string | number | ("true" | "false" | "null") ws
object ::=
  "{" ws (
1381
         string ":" ws value
1382
    ("," ws string ":" ws value)*
1383
  )? ws "}" 
1384
1385
1386
1387
array  ::=
  "[" ws (
            value
    ("," ws value)*
1388
  )? ws "]" 
1389
1390
string ::=
  "\"" (
1391
    [^"\\\x7F\x00-\x1F] |
1392
    "\\" (["\\/bfnrt] | "u" [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]) # escapes
1393
1394
  )* "\"" 
number ::= ("-"? ([0-9] | [1-9] [0-9]*)) ("." [0-9]+)? ([eE] [-+]? [0-9]+)? 
1395
1396
1397
1398
1399
1400
1401
# 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 {
1402
1403
	Data []byte `json:"data"`
	ID   int    `json:"id"`
1404
1405
1406
1407
}

type CompletionRequest struct {
	Prompt  string
1408
	Format  json.RawMessage
1409
	Images  []ImageData
Michael Yang's avatar
Michael Yang committed
1410
	Options *api.Options
1411

1412
1413
1414
	Grammar  string // set before sending the request to the subprocess
	Shift    bool
	Truncate bool
1415
1416
1417
1418
1419
1420

	// Logprobs specifies whether to include log probabilities in the response
	Logprobs bool

	// TopLogprobs specifies the number of most likely alternative tokens to return (0-20)
	TopLogprobs int
1421
1422
}

1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
// 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
	}
}

1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
// TokenLogprob represents log probability information for a single token alternative.
type TokenLogprob struct {
	Token   string  `json:"token"`
	Logprob float64 `json:"logprob"`
}

// Logprob contains log probability information for a generated token.
type Logprob struct {
	TokenLogprob
	TopLogprobs []TokenLogprob `json:"top_logprobs,omitempty"`
}

1458
type CompletionResponse struct {
1459
1460
1461
1462
1463
1464
1465
	Content            string        `json:"content"`
	DoneReason         DoneReason    `json:"done_reason"`
	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"`
1466
1467
1468

	// Logprobs contains log probability information if requested
	Logprobs []Logprob `json:"logprobs,omitempty"`
1469
1470
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1471
func (s *llmServer) Completion(ctx context.Context, req CompletionRequest, fn func(CompletionResponse)) error {
1472
	slog.Debug("completion request", "images", len(req.Images), "prompt", len(req.Prompt), "format", string(req.Format))
1473
	logutil.Trace("completion request", "prompt", req.Prompt)
1474

1475
	if len(req.Format) > 0 {
1476
1477
1478
1479
1480
1481
		switch string(req.Format) {
		case `null`, `""`:
			// Field was set, but "missing" a value. We accept
			// these as "not set".
			break
		case `"json"`:
1482
			req.Grammar = grammarJSON
1483
1484
1485
1486
		default:
			if req.Format[0] != '{' {
				return fmt.Errorf("invalid format: %q; expected \"json\" or a valid JSON Schema object", req.Format)
			}
1487

1488
1489
1490
1491
			// User provided a JSON schema
			g := llama.SchemaToGrammar(req.Format)
			if g == nil {
				return fmt.Errorf("invalid JSON schema in format")
1492
			}
1493
			req.Grammar = string(g)
1494
1495
1496
		}
	}

1497
1498
1499
1500
1501
	if req.Options == nil {
		opts := api.DefaultOptions()
		req.Options = &opts
	}

1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
	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
	}

1517
	// Make sure the server is ready
1518
	status, err := s.getServerStatusRetry(ctx)
1519
1520
1521
	if err != nil {
		return err
	} else if status != ServerStatusReady {
1522
		return fmt.Errorf("unexpected server status: %s", status)
1523
1524
	}

1525
1526
1527
1528
	// Handling JSON marshaling with special characters unescaped.
	buffer := &bytes.Buffer{}
	enc := json.NewEncoder(buffer)
	enc.SetEscapeHTML(false)
1529

1530
	if err := enc.Encode(req); err != nil {
1531
1532
		return fmt.Errorf("failed to marshal data: %v", err)
	}
1533

1534
1535
1536
1537
1538
1539
	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")
1540

1541
	res, err := http.DefaultClient.Do(serverReq)
1542
1543
1544
1545
	if err != nil && errors.Is(err, context.Canceled) {
		// client closed connection
		return err
	} else if err != nil {
1546
1547
		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")
1548
1549
	}
	defer res.Body.Close()
1550

1551
1552
	if res.StatusCode >= 400 {
		bodyBytes, err := io.ReadAll(res.Body)
1553
		if err != nil {
1554
			return fmt.Errorf("failed reading llm error response: %w", err)
1555
		}
1556
		log.Printf("llm predict error: %s", bodyBytes)
1557
		return api.StatusError{StatusCode: res.StatusCode, ErrorMessage: strings.TrimSpace(string(bodyBytes))}
1558
	}
1559

1560
1561
1562
	scanner := bufio.NewScanner(res.Body)
	buf := make([]byte, 0, maxBufferSize)
	scanner.Buffer(buf, maxBufferSize)
1563

1564
1565
1566
	// keep track of the last token generated, this is used to abort if the model starts looping
	var lastToken string
	var tokenRepeat int
1567

1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
	for scanner.Scan() {
		select {
		case <-ctx.Done():
			// This handles the request cancellation
			return ctx.Err()
		default:
			line := scanner.Bytes()
			if len(line) == 0 {
				continue
			}
1578

1579
1580
			evt, ok := bytes.CutPrefix(line, []byte("data: "))
			if !ok {
1581
				evt = line
1582
			}
1583

1584
			var c CompletionResponse
1585
			if err := json.Unmarshal(evt, &c); err != nil {
1586
				return fmt.Errorf("error unmarshalling llm prediction response: %v", err)
1587
1588
			}
			switch {
1589
			case strings.TrimSpace(c.Content) == lastToken:
1590
1591
1592
1593
1594
				tokenRepeat++
			default:
				lastToken = strings.TrimSpace(c.Content)
				tokenRepeat = 0
			}
1595

1596
1597
1598
1599
1600
			// 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()
			}
1601

1602
1603
			if c.Content != "" {
				fn(CompletionResponse{
1604
1605
					Content:  c.Content,
					Logprobs: c.Logprobs,
1606
				})
1607
			}
1608

1609
			if c.Done {
1610
				fn(c)
1611
				return nil
1612
			}
1613
		}
1614
	}
1615

1616
	if err := scanner.Err(); err != nil {
1617
		if strings.Contains(err.Error(), "unexpected EOF") || strings.Contains(err.Error(), "forcibly closed") {
1618
			s.Close()
1619
			var msg string
1620
1621
			if s.status != nil && s.status.LastErrMsg != "" {
				msg = s.status.LastErrMsg
1622
1623
			} else {
				msg = err.Error()
1624
			}
1625
			return fmt.Errorf("an error was encountered while running the model: %s", msg)
1626
1627
		}

1628
		return fmt.Errorf("error reading llm response: %v", err)
1629
1630
	}

1631
	return nil
1632
1633
}

1634
type EmbeddingRequest struct {
1635
	Content string `json:"content"`
1636
1637
}

1638
type EmbeddingResponse struct {
1639
1640
	Embedding       []float32 `json:"embedding"`
	PromptEvalCount int       `json:"prompt_eval_count"`
1641
1642
}

1643
func (s *llmServer) Embedding(ctx context.Context, input string) ([]float32, int, error) {
1644
	logutil.Trace("embedding request", "input", input)
1645

1646
	if err := s.sem.Acquire(ctx, 1); err != nil {
1647
1648
1649
1650
1651
		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)
		}
1652
		return nil, 0, err
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1653
	}
1654
	defer s.sem.Release(1)
1655

1656
	// Make sure the server is ready
1657
	status, err := s.getServerStatusRetry(ctx)
1658
	if err != nil {
1659
		return nil, 0, err
1660
	} else if status != ServerStatusReady {
1661
		return nil, 0, fmt.Errorf("unexpected server status: %s", status)
1662
1663
	}

1664
	data, err := json.Marshal(EmbeddingRequest{Content: input})
Michael Yang's avatar
Michael Yang committed
1665
	if err != nil {
1666
		return nil, 0, fmt.Errorf("error marshaling embed data: %w", err)
1667
1668
	}

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

1675
	resp, err := http.DefaultClient.Do(r)
1676
	if err != nil {
1677
		return nil, 0, fmt.Errorf("do embedding request: %w", err)
1678
1679
1680
1681
1682
	}
	defer resp.Body.Close()

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

	if resp.StatusCode >= 400 {
1687
		log.Printf("llm embedding error: %s", body)
1688
1689
1690
1691
		return nil, 0, api.StatusError{
			StatusCode:   resp.StatusCode,
			ErrorMessage: string(body),
		}
1692
1693
	}

1694
	var e EmbeddingResponse
1695
	if err := json.Unmarshal(body, &e); err != nil {
1696
		return nil, 0, fmt.Errorf("unmarshal tokenize response: %w", err)
1697
1698
	}

1699
	return e.Embedding, e.PromptEvalCount, nil
1700
1701
}

1702
func (s *llamaServer) Tokenize(ctx context.Context, content string) ([]int, error) {
1703
1704
	s.llamaModelLock.Lock()
	defer s.llamaModelLock.Unlock()
1705

1706
1707
	if s.llamaModel == nil {
		return nil, fmt.Errorf("no tokenizer configured")
Michael Yang's avatar
Michael Yang committed
1708
1709
	}

1710
	return s.llamaModel.Tokenize(content, false, true)
Michael Yang's avatar
Michael Yang committed
1711
1712
}

1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
func (s *ollamaServer) Tokenize(ctx context.Context, content string) ([]int, error) {
	tokens, err := s.textProcessor.Encode(content, false)
	if err != nil {
		return nil, err
	}

	toks := make([]int, len(tokens))
	for i, t := range tokens {
		toks[i] = int(t)
	}

	return toks, nil
1725
1726
}

1727
func (s *llamaServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
1728
1729
1730
	s.llamaModelLock.Lock()
	defer s.llamaModelLock.Unlock()

1731
1732
	if s.llamaModel == nil {
		return "", fmt.Errorf("no tokenizer configured")
1733
	}
1734
1735
1736
1737

	var resp string
	for _, token := range tokens {
		resp += s.llamaModel.TokenToPiece(token)
Michael Yang's avatar
Michael Yang committed
1738
	}
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754

	return resp, nil
}

func (s *ollamaServer) Detokenize(ctx context.Context, tokens []int) (string, error) {
	toks := make([]int32, len(tokens))
	for i, t := range tokens {
		toks[i] = int32(t)
	}

	content, err := s.textProcessor.Decode(toks)
	if err != nil {
		return "", err
	}

	return content, nil
1755
1756
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
1757
func (s *llmServer) Close() error {
1758
1759
1760
1761
	s.llamaModelLock.Lock()
	if s.llamaModel != nil {
		llama.FreeModel(s.llamaModel)
		s.llamaModel = nil
1762
	}
1763
	s.llamaModelLock.Unlock()
1764

1765
	if s.cmd != nil {
1766
		slog.Debug("stopping llama server", "pid", s.Pid())
1767
1768
1769
		if err := s.cmd.Process.Kill(); err != nil {
			return err
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1770
1771
		// if ProcessState is already populated, Wait already completed, no need to wait again
		if s.cmd.ProcessState == nil {
1772
			slog.Debug("waiting for llama server to exit", "pid", s.Pid())
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1773
1774
			<-s.done
		}
1775

1776
		slog.Debug("llama server stopped", "pid", s.Pid())
1777
1778
1779
1780
1781
	}

	return nil
}

1782
1783
1784
1785
1786
func (s *llamaServer) GetDeviceInfos(ctx context.Context) []ml.DeviceInfo {
	slog.Debug("llamarunner free vram reporting not supported")
	return nil
}

1787
func (s *llmServer) VRAMSize() uint64 {
Jesse Gross's avatar
Jesse Gross committed
1788
1789
1790
1791
1792
1793
1794
	if s.mem == nil {
		return 0
	}

	var mem uint64

	for _, g := range s.mem.GPUs {
1795
		mem += g.Size()
Jesse Gross's avatar
Jesse Gross committed
1796
1797
1798
1799
1800
1801
	}

	// 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 {
1802
		if s.mem.CPU.Weights[i] != 0 || s.mem.CPU.Cache[i] != 0 {
Jesse Gross's avatar
Jesse Gross committed
1803
1804
1805
1806
1807
			noCPULayers = false
			break
		}
	}
	if noCPULayers {
1808
1809
		mem += s.mem.InputWeights
		mem += s.mem.CPU.Graph
Jesse Gross's avatar
Jesse Gross committed
1810
1811
1812
1813
1814
	}

	return mem
}

1815
func (s *llmServer) TotalSize() uint64 {
Jesse Gross's avatar
Jesse Gross committed
1816
1817
1818
1819
	if s.mem == nil {
		return 0
	}

1820
1821
	mem := s.mem.InputWeights
	mem += s.mem.CPU.Size()
Jesse Gross's avatar
Jesse Gross committed
1822
	for _, g := range s.mem.GPUs {
1823
		mem += g.Size()
Jesse Gross's avatar
Jesse Gross committed
1824
1825
1826
1827
1828
	}

	return mem
}

1829
func (s *llmServer) VRAMByGPU(id ml.DeviceID) uint64 {
Jesse Gross's avatar
Jesse Gross committed
1830
1831
1832
1833
1834
	if s.mem == nil {
		return 0
	}

	for _, g := range s.mem.GPUs {
1835
		if g.DeviceID == id {
1836
			return g.Size()
Jesse Gross's avatar
Jesse Gross committed
1837
1838
1839
1840
1841
		}
	}

	return 0
}
1842
1843

func (s *ollamaServer) GetDeviceInfos(ctx context.Context) []ml.DeviceInfo {
1844
	devices, err := ml.GetDevicesFromRunner(ctx, s)
1845
1846
1847
1848
1849
1850
1851
1852
1853
	if err != nil {
		if s.cmd != nil && s.cmd.ProcessState == nil {
			// Still running but hit an error, log
			slog.Debug("failure refreshing GPU information", "error", err)
		}
		// else no longer running so suppress logging as a failure is expected
	}
	return devices
}