llm.go 1.71 KB
Newer Older
1
2
3
4
package llm

import (
	"fmt"
5
	"log"
6
7
	"os"

8
9
	"github.com/pbnjay/memory"

10
11
12
13
14
15
16
17
18
19
20
21
	"github.com/jmorganca/ollama/api"
)

type LLM interface {
	Predict([]int, string, func(api.GenerateResponse)) error
	Embedding(string) ([]float64, error)
	Encode(string) []int
	Decode(...int) string
	SetOptions(api.Options)
	Close()
}

22
func New(model string, adapters []string, opts api.Options) (LLM, error) {
23
24
25
26
27
28
29
30
	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
31
	defer f.Close()
32
33
34
35
36
37

	ggml, err := DecodeGGML(f, ModelFamilyLlama)
	if err != nil {
		return nil, err
	}

38
39
40
41
42
43
44
45
46
47
	switch ggml.FileType {
	case FileTypeF32, FileTypeF16, FileTypeQ5_0, FileTypeQ5_1, FileTypeQ8_0:
		if opts.NumGPU != 0 {
			// Q5_0, Q5_1, and 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, F16, Q5_0, Q5_1, and Q8_0")
			opts.NumGPU = 0
		}
	}

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
	totalResidentMemory := memory.TotalMemory()
	switch ggml.ModelType {
	case ModelType3B, ModelType7B:
		if totalResidentMemory < 8*1024*1024 {
			return nil, fmt.Errorf("model requires at least 8GB of memory")
		}
	case ModelType13B:
		if totalResidentMemory < 16*1024*1024 {
			return nil, fmt.Errorf("model requires at least 16GB of memory")
		}
	case ModelType30B:
		if totalResidentMemory < 32*1024*1024 {
			return nil, fmt.Errorf("model requires at least 32GB of memory")
		}
	case ModelType65B:
		if totalResidentMemory < 64*1024*1024 {
			return nil, fmt.Errorf("model requires at least 64GB of memory")
		}
	}

68
69
	switch ggml.ModelFamily {
	case ModelFamilyLlama:
70
		return newLlama(model, adapters, opts)
71
72
73
74
	default:
		return nil, fmt.Errorf("unknown ggml type: %s", ggml.ModelFamily)
	}
}