payload.go 5.53 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
package llm

import (
	"compress/gzip"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"log/slog"
	"os"
	"path/filepath"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
12
	"runtime"
13
	"slices"
14
15
16
17
18
19
20
	"strings"

	"golang.org/x/sync/errgroup"

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

21
var errPayloadMissing = errors.New("expected payloads not included in this build of ollama")
22
23
24
25
26
27
28

func Init() error {
	payloadsDir, err := gpu.PayloadsDir()
	if err != nil {
		return err
	}

29
30
31
	if runtime.GOOS != "windows" {
		slog.Info("extracting embedded files", "dir", payloadsDir)
		binGlob := "build/*/*/*/bin/*"
32

33
34
35
36
37
		// extract server libraries
		err = extractFiles(payloadsDir, binGlob)
		if err != nil {
			return fmt.Errorf("extract binaries: %v", err)
		}
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
	}

	var variants []string
	for v := range availableServers() {
		variants = append(variants, v)
	}
	slog.Info(fmt.Sprintf("Dynamic LLM libraries %v", variants))
	slog.Debug("Override detection logic by setting OLLAMA_LLM_LIBRARY")

	return nil
}

// binary names may contain an optional variant separated by '_'
// For example, "ollama_rocm_v6" and "ollama_rocm_v5" or "ollama_cpu" and "ollama_cpu_avx2"
// Any library without a variant is the lowest common denominator
func availableServers() map[string]string {
	payloadsDir, err := gpu.PayloadsDir()
	if err != nil {
		slog.Error("payload lookup error", "error", err)
		return nil
	}

	// glob payloadsDir for files that start with ollama_
	pattern := filepath.Join(payloadsDir, "*")

	files, err := filepath.Glob(pattern)
	if err != nil {
		slog.Debug("could not glob", "pattern", pattern, "error", err)
		return nil
	}

	servers := make(map[string]string)
	for _, file := range files {
		slog.Debug("availableServers : found", "file", file)
		servers[filepath.Base(file)] = file
	}

	return servers
}

// serversForGpu returns a list of compatible servers give the provided GPU
// info, ordered by performance. assumes Init() has been called
// TODO - switch to metadata based mapping
func serversForGpu(info gpu.GpuInfo) []string {
	// glob workDir for files that start with ollama_
	availableServers := availableServers()
	requested := info.Library
Daniel Hiltgen's avatar
Daniel Hiltgen committed
85
86
	if info.Variant != gpu.CPUCapabilityNone {
		requested += "_" + info.Variant.String()
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
	}

	servers := []string{}

	// exact match first
	for a := range availableServers {
		if a == requested {
			servers = []string{a}

			if a == "metal" {
				return servers
			}

			break
		}
	}

	alt := []string{}

	// Then for GPUs load alternates and sort the list for consistent load ordering
	if info.Library != "cpu" {
		for a := range availableServers {
			if info.Library == strings.Split(a, "_")[0] && a != requested {
				alt = append(alt, a)
			}
		}

		slices.Sort(alt)
		servers = append(servers, alt...)
	}

	// Load up the best CPU variant if not primary requested
	if info.Library != "cpu" {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
120
		variant := gpu.GetCPUCapability()
121
122
123
124
		// If no variant, then we fall back to default
		// If we have a variant, try that if we find an exact match
		// Attempting to run the wrong CPU instructions will panic the
		// process
Daniel Hiltgen's avatar
Daniel Hiltgen committed
125
		if variant != gpu.CPUCapabilityNone {
126
			for cmp := range availableServers {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
127
				if cmp == "cpu_"+variant.String() {
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
					servers = append(servers, cmp)
					break
				}
			}
		} else {
			servers = append(servers, "cpu")
		}
	}

	if len(servers) == 0 {
		servers = []string{"cpu"}
	}

	return servers
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
144
145
146
147
148
// Return the optimal server for this CPU architecture
func serverForCpu() string {
	if runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" {
		return "metal"
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
149
	variant := gpu.GetCPUCapability()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
150
	availableServers := availableServers()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
151
	if variant != gpu.CPUCapabilityNone {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
152
		for cmp := range availableServers {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
153
			if cmp == "cpu_"+variant.String() {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
154
155
156
157
158
159
160
				return cmp
			}
		}
	}
	return "cpu"
}

161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// extract extracts the embedded files to the target directory
func extractFiles(targetDir string, glob string) error {
	files, err := fs.Glob(libEmbed, glob)
	if err != nil || len(files) == 0 {
		return errPayloadMissing
	}

	if err := os.MkdirAll(targetDir, 0o755); err != nil {
		return fmt.Errorf("extractFiles could not mkdir %s: %v", targetDir, err)
	}

	g := new(errgroup.Group)

	// build/$OS/$GOARCH/$VARIANT/{bin,lib}/$FILE
	for _, file := range files {
		filename := file

		variant := filepath.Base(filepath.Dir(filepath.Dir(filename)))

		slog.Debug("extracting", "variant", variant, "file", filename)

		g.Go(func() error {
			srcf, err := libEmbed.Open(filename)
			if err != nil {
				return err
			}
			defer srcf.Close()

			src := io.Reader(srcf)
			if strings.HasSuffix(filename, ".gz") {
				src, err = gzip.NewReader(src)
				if err != nil {
					return fmt.Errorf("decompress payload %s: %v", filename, err)
				}
				filename = strings.TrimSuffix(filename, ".gz")
			}

			variantDir := filepath.Join(targetDir, variant)
			if err := os.MkdirAll(variantDir, 0o755); err != nil {
				return fmt.Errorf("extractFiles could not mkdir %s: %v", variantDir, err)
			}

			base := filepath.Base(filename)
			destFilename := filepath.Join(variantDir, base)

			_, err = os.Stat(destFilename)
			switch {
			case errors.Is(err, os.ErrNotExist):
				destFile, err := os.OpenFile(destFilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
				if err != nil {
					return fmt.Errorf("write payload %s: %v", filename, err)
				}
				defer destFile.Close()
				if _, err := io.Copy(destFile, src); err != nil {
					return fmt.Errorf("copy payload %s: %v", filename, err)
				}
			case err != nil:
				return fmt.Errorf("stat payload %s: %v", filename, err)
			}
			return nil
		})
	}

	err = g.Wait()
	if err != nil {
		// If we fail to extract, the payload dir is unusable, so cleanup whatever we extracted
		gpu.Cleanup()
		return err
	}
	return nil
}