llm.go 2.04 KB
Newer Older
1
2
3
package llm

import (
4
	"context"
5
	"fmt"
6
	"log"
7
	"os"
8
	"runtime"
9

10
11
	"github.com/pbnjay/memory"

12
	"github.com/jmorganca/ollama/api"
Michael Yang's avatar
Michael Yang committed
13
	"github.com/jmorganca/ollama/format"
14
15
16
)

type LLM interface {
Bruce MacDonald's avatar
Bruce MacDonald committed
17
	Predict(context.Context, PredictOpts, func(PredictResult)) error
18
19
20
	Embedding(context.Context, string) ([]float64, error)
	Encode(context.Context, string) ([]int, error)
	Decode(context.Context, []int) (string, error)
21
	Close()
22
	Ping(context.Context) error
23
24
}

Michael Yang's avatar
Michael Yang committed
25
func New(workDir, model string, adapters, projectors []string, opts api.Options) (LLM, error) {
26
27
28
29
30
31
32
33
	if _, err := os.Stat(model); err != nil {
		return nil, err
	}

	f, err := os.Open(model)
	if err != nil {
		return nil, err
	}
Michael Yang's avatar
Michael Yang committed
34
	defer f.Close()
35

Bruce MacDonald's avatar
Bruce MacDonald committed
36
	ggml, err := DecodeGGML(f)
37
38
39
40
	if err != nil {
		return nil, err
	}

41
42
	if runtime.GOOS == "darwin" {
		switch ggml.FileType() {
43
		case "F32", "Q5_0", "Q5_1", "Q8_0":
44
45
46
47
48
49
			if ggml.Name() != "gguf" && opts.NumGPU != 0 {
				// GGML Q8_0 do not support Metal API and will
				// cause the runner to segmentation fault so disable GPU
				log.Printf("WARNING: GPU disabled for F32, Q5_0, Q5_1, and Q8_0")
				opts.NumGPU = 0
			}
50
		}
Michael Yang's avatar
Michael Yang committed
51

52
53
		var requiredMemory int64
		var f16Multiplier int64 = 2
54

55
56
57
58
59
60
61
62
63
64
65
66
67
		switch ggml.ModelType() {
		case "3B", "7B":
			requiredMemory = 8 * format.GigaByte
		case "13B":
			requiredMemory = 16 * format.GigaByte
		case "30B", "34B", "40B":
			requiredMemory = 32 * format.GigaByte
		case "65B", "70B":
			requiredMemory = 64 * format.GigaByte
		case "180B":
			requiredMemory = 128 * format.GigaByte
			f16Multiplier = 4
		}
68

69
		systemMemory := int64(memory.TotalMemory())
70

71
72
73
74
75
		if ggml.FileType() == "F16" && requiredMemory*f16Multiplier > systemMemory {
			return nil, fmt.Errorf("F16 model requires at least %s of total memory", format.HumanBytes(requiredMemory))
		} else if requiredMemory > systemMemory {
			return nil, fmt.Errorf("model requires at least %s of total memory", format.HumanBytes(requiredMemory))
		}
76
77
	}

Bruce MacDonald's avatar
Bruce MacDonald committed
78
79
80
	opts.NumGQA = 0
	opts.RopeFrequencyBase = 0.0
	opts.RopeFrequencyScale = 0.0
81
	return newLlamaExtServer(model, adapters, projectors, ggml.NumLayers(), opts)
82
}