"projects/DensePose/densepose/modeling/losses/chart.py" did not exist on "5b3792fc3ef9ab6a6f8f30634ab2e52fb0941af3"
payload_common.go 6.23 KB
Newer Older
1
2
3
package llm

import (
4
	"compress/gzip"
5
6
7
8
	"errors"
	"fmt"
	"io"
	"io/fs"
9
	"log/slog"
10
11
12
13
	"os"
	"path/filepath"
	"runtime"
	"strings"
14
	"sync"
15

16
17
18
	"golang.org/x/exp/slices"
	"golang.org/x/sync/errgroup"

19
	"github.com/ollama/ollama/gpu"
20
21
)

22
// Libraries names may contain an optional variant separated by '_'
23
// For example, "rocm_v6" and "rocm_v5" or "cpu" and "cpu_avx2"
24
// Any library without a variant is the lowest common denominator
25
var availableDynLibs = map[string]string{}
26

27
const pathComponentCount = 7
28

29
30
// getDynLibs returns an ordered list of LLM libraries to try, starting with the best
func getDynLibs(gpuInfo gpu.GpuInfo) []string {
31
32
33
34
	// Short circuit if we know we're using the default built-in (darwin only)
	if gpuInfo.Library == "default" {
		return []string{"default"}
	}
35
36
37
38
39
40
41
	// TODO - temporary until we have multiple CPU variations for Darwin
	// Short circuit on darwin with metal only
	if len(availableDynLibs) == 1 {
		if _, onlyMetal := availableDynLibs["metal"]; onlyMetal {
			return []string{availableDynLibs["metal"]}
		}
	}
42

43
	exactMatch := ""
44
45
	dynLibs := []string{}
	altDynLibs := []string{}
46
47
48
49
	requested := gpuInfo.Library
	if gpuInfo.Variant != "" {
		requested += "_" + gpuInfo.Variant
	}
50
	// Try to find an exact match
51
	for cmp := range availableDynLibs {
52
53
		if requested == cmp {
			exactMatch = cmp
54
			dynLibs = []string{availableDynLibs[cmp]}
55
56
57
			break
		}
	}
58
	// Then for GPUs load alternates and sort the list for consistent load ordering
59
	if gpuInfo.Library != "cpu" {
60
		for cmp := range availableDynLibs {
61
			if gpuInfo.Library == strings.Split(cmp, "_")[0] && cmp != exactMatch {
62
				altDynLibs = append(altDynLibs, cmp)
63
64
			}
		}
65
66
67
		slices.Sort(altDynLibs)
		for _, altDynLib := range altDynLibs {
			dynLibs = append(dynLibs, availableDynLibs[altDynLib])
68
69
		}
	}
70
71
72
73
74
75
76
77
78

	// Load up the best CPU variant if not primary requested
	if gpuInfo.Library != "cpu" {
		variant := gpu.GetCPUVariant()
		// 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
		if variant != "" {
79
			for cmp := range availableDynLibs {
80
				if cmp == "cpu_"+variant {
81
					dynLibs = append(dynLibs, availableDynLibs[cmp])
82
83
84
85
					break
				}
			}
		} else {
86
			dynLibs = append(dynLibs, availableDynLibs["cpu"])
87
88
89
		}
	}

Michael Yang's avatar
Michael Yang committed
90
	// Finally, if we didn't find any matches, LCD CPU FTW
91
92
	if len(dynLibs) == 0 {
		dynLibs = []string{availableDynLibs["cpu"]}
93
	}
94
	slog.Debug(fmt.Sprintf("ordered list of LLM libraries to try %v", dynLibs))
95
	return dynLibs
96
97
}

98
99
100
func rocmDynLibPresent() bool {
	for dynLibName := range availableDynLibs {
		if strings.HasPrefix(dynLibName, "rocm") {
101
102
103
104
105
106
			return true
		}
	}
	return false
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
107
func nativeInit() error {
108
	payloadsDir, err := gpu.PayloadsDir()
Daniel Hiltgen's avatar
Daniel Hiltgen committed
109
110
111
	if err != nil {
		return err
	}
112

113
	slog.Info(fmt.Sprintf("Extracting dynamic libraries to %s ...", payloadsDir))
114

115
	libs, err := extractDynamicLibs(payloadsDir, "llama.cpp/build/*/*/*/lib/*")
116
	if err != nil {
117
		if errors.Is(err, payloadMissing) {
118
			slog.Info(fmt.Sprintf("%s", payloadMissing))
119
120
121
122
123
124
125
			return nil
		}
		return err
	}
	for _, lib := range libs {
		// The last dir component is the variant name
		variant := filepath.Base(filepath.Dir(lib))
126
		availableDynLibs[variant] = lib
127
128
129
130
131
132
133
	}

	if err := verifyDriverAccess(); err != nil {
		return err
	}

	// Report which dynamic libraries we have loaded to assist troubleshooting
134
	variants := make([]string, len(availableDynLibs))
135
	i := 0
136
	for variant := range availableDynLibs {
137
138
139
		variants[i] = variant
		i++
	}
140
141
	slog.Info(fmt.Sprintf("Dynamic LLM libraries %v", variants))
	slog.Debug("Override detection logic by setting OLLAMA_LLM_LIBRARY")
142
143
144
145

	return nil
}

146
func extractDynamicLibs(payloadsDir, glob string) ([]string, error) {
147
148
149
150
151
	files, err := fs.Glob(libEmbed, glob)
	if err != nil || len(files) == 0 {
		return nil, payloadMissing
	}

152
153
154
	var mu sync.Mutex
	var libs []string
	var g errgroup.Group
155
156
157
	for _, file := range files {
		pathComps := strings.Split(file, "/")
		if len(pathComps) != pathComponentCount {
158
			slog.Error(fmt.Sprintf("unexpected payload components: %v", pathComps))
159
160
161
			continue
		}

162
163
164
165
		file := file
		g.Go(func() error {
			// llama.cpp/build/$OS/$GOARCH/$VARIANT/lib/$LIBRARY
			// Include the variant in the path to avoid conflicts between multiple server libs
166
			targetDir := filepath.Join(payloadsDir, pathComps[pathComponentCount-3])
167
			srcFile, err := libEmbed.Open(file)
168
			if err != nil {
169
				return fmt.Errorf("read payload %s: %v", file, err)
170
			}
171
172
			defer srcFile.Close()
			if err := os.MkdirAll(targetDir, 0o755); err != nil {
173
				return fmt.Errorf("create payload lib dir %s: %v", payloadsDir, err)
174
			}
175
176
			src := io.Reader(srcFile)
			filename := file
177
178
179
180
181
182
			if strings.HasSuffix(file, ".gz") {
				src, err = gzip.NewReader(src)
				if err != nil {
					return fmt.Errorf("decompress payload %s: %v", file, err)
				}
				filename = strings.TrimSuffix(filename, ".gz")
183
184
185
186
			}

			destFile := filepath.Join(targetDir, filepath.Base(filename))
			if strings.Contains(destFile, "server") {
187
				mu.Lock()
188
				libs = append(libs, destFile)
189
				mu.Unlock()
190
191
			}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
192
193
194
195
196
197
198
			destFp, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
			if err != nil {
				return fmt.Errorf("write payload %s: %v", file, err)
			}
			defer destFp.Close()
			if _, err := io.Copy(destFp, src); err != nil {
				return fmt.Errorf("copy payload %s: %v", file, err)
199
200
201
			}
			return nil
		})
202
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
203
204
205
206
207
208
209
	err = g.Wait()
	if err != nil {
		// If we fail to extract, the payload dir is unusable, so cleanup whatever we extracted
		gpu.Cleanup()
		return nil, err
	}
	return libs, nil
210
211
212
213
214
215
216
}

func verifyDriverAccess() error {
	if runtime.GOOS != "linux" {
		return nil
	}
	// Only check ROCm access if we have the dynamic lib loaded
217
	if rocmDynLibPresent() {
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
		// Verify we have permissions - either running as root, or we have group access to the driver
		fd, err := os.OpenFile("/dev/kfd", os.O_RDWR, 0666)
		if err != nil {
			if errors.Is(err, fs.ErrPermission) {
				return fmt.Errorf("Radeon card detected, but permissions not set up properly.  Either run ollama as root, or add you user account to the render group.")
			} else if errors.Is(err, fs.ErrNotExist) {
				// expected behavior without a radeon card
				return nil
			}

			return fmt.Errorf("failed to check permission on /dev/kfd: %w", err)
		}
		fd.Close()
	}
	return nil
}