amd_linux.go 12 KB
Newer Older
Daniel Hiltgen's avatar
Daniel Hiltgen committed
1
2
3
4
5
6
7
8
9
10
package gpu

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"os"
	"path/filepath"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
11
	"regexp"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
12
13
14
	"slices"
	"strconv"
	"strings"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
15
16

	"github.com/ollama/ollama/format"
Daniel Hiltgen's avatar
Daniel Hiltgen committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
)

// Discovery logic for AMD/ROCm GPUs

const (
	DriverVersionFile     = "/sys/module/amdgpu/version"
	AMDNodesSysfsDir      = "/sys/class/kfd/kfd/topology/nodes/"
	GPUPropertiesFileGlob = AMDNodesSysfsDir + "*/properties"

	// Prefix with the node dir
	GPUTotalMemoryFileGlob = "mem_banks/*/properties" // size_in_bytes line
	GPUUsedMemoryFileGlob  = "mem_banks/*/used_memory"
)

var (
	// Used to validate if the given ROCm lib is usable
33
34
	ROCmLibGlobs          = []string{"libhipblas.so.2*", "rocblas"} // TODO - probably include more coverage of files here...
	RocmStandardLocations = []string{"/opt/rocm/lib", "/usr/lib64"}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
35
36
37
)

// Gather GPU information from the amdgpu driver if any supported GPUs are detected
Daniel Hiltgen's avatar
Daniel Hiltgen committed
38
39
func AMDGetGPUInfo() []GpuInfo {
	resp := []GpuInfo{}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
40
	if !AMDDetected() {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
41
		return resp
Daniel Hiltgen's avatar
Daniel Hiltgen committed
42
43
44
	}

	// Opportunistic logging of driver version to aid in troubleshooting
Daniel Hiltgen's avatar
Daniel Hiltgen committed
45
46
	driverMajor, driverMinor, err := AMDDriverVersion()
	if err != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
47
		// TODO - if we see users crash and burn with the upstreamed kernel this can be adjusted to hard-fail rocm support and fallback to CPU
Daniel Hiltgen's avatar
Daniel Hiltgen committed
48
		slog.Warn("ollama recommends running the https://www.amd.com/en/support/linux-drivers", "error", err)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
49
50
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
	// Determine if the user has already pre-selected which GPUs to look at, then ignore the others
	var visibleDevices []string
	hipVD := os.Getenv("HIP_VISIBLE_DEVICES")   // zero based index only
	rocrVD := os.Getenv("ROCR_VISIBLE_DEVICES") // zero based index or UUID, but consumer cards seem to not support UUID
	gpuDO := os.Getenv("GPU_DEVICE_ORDINAL")    // zero based index
	switch {
	// TODO is this priorty order right?
	case hipVD != "":
		visibleDevices = strings.Split(hipVD, ",")
	case rocrVD != "":
		visibleDevices = strings.Split(rocrVD, ",")
		// TODO - since we don't yet support UUIDs, consider detecting and reporting here
		// all our test systems show GPU-XX indicating UUID is not supported
	case gpuDO != "":
		visibleDevices = strings.Split(gpuDO, ",")
Daniel Hiltgen's avatar
Daniel Hiltgen committed
66
67
	}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
68
69
70
71
72
73
74
75
76
77
78
79
80
	gfxOverride := os.Getenv("HSA_OVERRIDE_GFX_VERSION")
	var supported []string
	libDir := ""

	// The amdgpu driver always exposes the host CPU(s) first, but we have to skip them and subtract
	// from the other IDs to get alignment with the HIP libraries expectations (zero is the first GPU, not the CPU)
	matches, _ := filepath.Glob(GPUPropertiesFileGlob)
	cpuCount := 0
	for _, match := range matches {
		slog.Debug("evaluating amdgpu node " + match)
		fp, err := os.Open(match)
		if err != nil {
			slog.Debug("failed to open sysfs node", "file", match, "error", err)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
81
82
			continue
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
83
84
85
86
87
		defer fp.Close()
		nodeID, err := strconv.Atoi(filepath.Base(filepath.Dir(match)))
		if err != nil {
			slog.Debug("failed to parse node ID", "error", err)
			continue
Daniel Hiltgen's avatar
Daniel Hiltgen committed
88
89
		}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
90
91
92
		scanner := bufio.NewScanner(fp)
		isCPU := false
		var major, minor, patch uint64
Daniel Hiltgen's avatar
Daniel Hiltgen committed
93
		var vendor, device uint64
Daniel Hiltgen's avatar
Daniel Hiltgen committed
94
95
96
97
98
		for scanner.Scan() {
			line := strings.TrimSpace(scanner.Text())
			// Note: we could also use "cpu_cores_count X" where X is greater than zero to detect CPUs
			if strings.HasPrefix(line, "gfx_target_version") {
				ver := strings.Fields(line)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
99

Daniel Hiltgen's avatar
Daniel Hiltgen committed
100
101
102
103
104
105
				// Detect CPUs
				if len(ver) == 2 && ver[1] == "0" {
					slog.Debug("detected CPU " + match)
					isCPU = true
					break
				}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
106

Daniel Hiltgen's avatar
Daniel Hiltgen committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
				if len(ver) != 2 || len(ver[1]) < 5 {
					slog.Warn("malformed "+match, "gfx_target_version", line)
					// If this winds up being a CPU, our offsets may be wrong
					continue
				}
				l := len(ver[1])
				var err1, err2, err3 error
				patch, err1 = strconv.ParseUint(ver[1][l-2:l], 10, 32)
				minor, err2 = strconv.ParseUint(ver[1][l-4:l-2], 10, 32)
				major, err3 = strconv.ParseUint(ver[1][:l-4], 10, 32)
				if err1 != nil || err2 != nil || err3 != nil {
					slog.Debug("malformed int " + line)
					continue
				}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
			} else if strings.HasPrefix(line, "vendor_id") {
				ver := strings.Fields(line)
				if len(ver) != 2 {
					slog.Debug("malformed vendor_id", "vendor_id", line)
					continue
				}
				vendor, err = strconv.ParseUint(ver[1], 10, 32)
				if err != nil {
					slog.Debug("malformed vendor_id" + line)
				}
			} else if strings.HasPrefix(line, "device_id") {
				ver := strings.Fields(line)
				if len(ver) != 2 {
					slog.Debug("malformed device_id", "device_id", line)
					continue
				}
				device, err = strconv.ParseUint(ver[1], 10, 32)
				if err != nil {
					slog.Debug("malformed device_id" + line)
				}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
141
			}
142

Daniel Hiltgen's avatar
Daniel Hiltgen committed
143
144
145
			// TODO - any other properties we want to extract and record?
			// vendor_id + device_id -> pci lookup for "Name"
			// Other metrics that may help us understand relative performance between multiple GPUs
Daniel Hiltgen's avatar
Daniel Hiltgen committed
146
147
		}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
148
149
150
		if isCPU {
			cpuCount++
			continue
Daniel Hiltgen's avatar
Daniel Hiltgen committed
151
152
		}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
153
154
		// CPUs are always first in the list
		gpuID := nodeID - cpuCount
Daniel Hiltgen's avatar
Daniel Hiltgen committed
155

Daniel Hiltgen's avatar
Daniel Hiltgen committed
156
157
158
159
		// Shouldn't happen, but just in case...
		if gpuID < 0 {
			slog.Error("unexpected amdgpu sysfs data resulted in negative GPU ID, please set OLLAMA_DEBUG=1 and report an issue")
			return []GpuInfo{}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
160
161
		}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
162
		if int(major) < RocmComputeMin {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
163
			slog.Warn(fmt.Sprintf("amdgpu too old gfx%d%x%x", major, minor, patch), "gpu", gpuID)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
164
165
			continue
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
166
167

		// Look up the memory for the current node
Daniel Hiltgen's avatar
Daniel Hiltgen committed
168
169
		totalMemory := uint64(0)
		usedMemory := uint64(0)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
170
		propGlob := filepath.Join(AMDNodesSysfsDir, strconv.Itoa(nodeID), GPUTotalMemoryFileGlob)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
171
172
		propFiles, err := filepath.Glob(propGlob)
		if err != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
173
			slog.Warn("error looking up total GPU memory", "glob", propGlob, "error", err)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
174
175
176
177
178
		}
		// 1 or more memory banks - sum the values of all of them
		for _, propFile := range propFiles {
			fp, err := os.Open(propFile)
			if err != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
179
				slog.Warn("failed to open sysfs node", "file", propFile, "erroir", err)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
				continue
			}
			defer fp.Close()
			scanner := bufio.NewScanner(fp)
			for scanner.Scan() {
				line := strings.TrimSpace(scanner.Text())
				if strings.HasPrefix(line, "size_in_bytes") {
					ver := strings.Fields(line)
					if len(ver) != 2 {
						slog.Warn("malformed " + line)
						continue
					}
					bankSizeInBytes, err := strconv.ParseUint(ver[1], 10, 64)
					if err != nil {
						slog.Warn("malformed int " + line)
						continue
					}
					totalMemory += bankSizeInBytes
				}
			}
		}
		if totalMemory == 0 {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
202
			slog.Warn("amdgpu reports zero total memory", "gpu", gpuID)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
203
204
			continue
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
205
		usedGlob := filepath.Join(AMDNodesSysfsDir, strconv.Itoa(nodeID), GPUUsedMemoryFileGlob)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
206
207
		usedFiles, err := filepath.Glob(usedGlob)
		if err != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
208
			slog.Warn("error looking up used GPU memory", "glob", usedGlob, "error", err)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
209
210
211
212
213
			continue
		}
		for _, usedFile := range usedFiles {
			fp, err := os.Open(usedFile)
			if err != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
214
				slog.Warn("failed to open sysfs node", "file", usedFile, "error", err)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
215
216
217
218
219
				continue
			}
			defer fp.Close()
			data, err := io.ReadAll(fp)
			if err != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
220
				slog.Warn("failed to read sysfs node", "file", usedFile, "error", err)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
221
222
223
224
				continue
			}
			used, err := strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64)
			if err != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
225
				slog.Warn("malformed used memory", "data", string(data), "error", err)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
226
227
228
229
				continue
			}
			usedMemory += used
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
230
231
232

		// iGPU detection, remove this check once we can support an iGPU variant of the rocm library
		if totalMemory < IGPUMemLimit {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
233
			slog.Info("unsupported Radeon iGPU detected skipping", "id", gpuID, "total", format.HumanBytes2(totalMemory))
Daniel Hiltgen's avatar
Daniel Hiltgen committed
234
235
			continue
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
236
237
238
239
240
		var name string
		// TODO - PCI ID lookup
		if vendor > 0 && device > 0 {
			name = fmt.Sprintf("%04x:%04x", vendor, device)
		}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
241

Daniel Hiltgen's avatar
Daniel Hiltgen committed
242
243
		slog.Debug("amdgpu memory", "gpu", gpuID, "total", format.HumanBytes2(totalMemory))
		slog.Debug("amdgpu memory", "gpu", gpuID, "available", format.HumanBytes2(totalMemory-usedMemory))
Daniel Hiltgen's avatar
Daniel Hiltgen committed
244
245
246
247
248
249
		gpuInfo := GpuInfo{
			Library: "rocm",
			memInfo: memInfo{
				TotalMemory: totalMemory,
				FreeMemory:  (totalMemory - usedMemory),
			},
Daniel Hiltgen's avatar
Daniel Hiltgen committed
250
251
252
			ID:            fmt.Sprintf("%d", gpuID),
			Name:          name,
			Compute:       fmt.Sprintf("gfx%d%x%x", major, minor, patch),
Daniel Hiltgen's avatar
Daniel Hiltgen committed
253
			MinimumMemory: rocmMinimumMemory,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
254
255
			DriverMajor:   driverMajor,
			DriverMinor:   driverMinor,
Daniel Hiltgen's avatar
Daniel Hiltgen committed
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
		}

		// If the user wants to filter to a subset of devices, filter out if we aren't a match
		if len(visibleDevices) > 0 {
			include := false
			for _, visible := range visibleDevices {
				if visible == gpuInfo.ID {
					include = true
					break
				}
			}
			if !include {
				slog.Info("filtering out device per user request", "id", gpuInfo.ID, "visible_devices", visibleDevices)
				continue
			}
		}

		// Final validation is gfx compatibility - load the library if we haven't already loaded it
		// even if the user overrides, we still need to validate the library
		if libDir == "" {
			libDir, err = AMDValidateLibDir()
			if err != nil {
				slog.Warn("unable to verify rocm library, will use cpu", "error", err)
				return []GpuInfo{}
			}
		}
		gpuInfo.DependencyPath = libDir

		if gfxOverride == "" {
			// Only load supported list once
			if len(supported) == 0 {
				supported, err = GetSupportedGFX(libDir)
				if err != nil {
					slog.Warn("failed to lookup supported GFX types, falling back to CPU mode", "error", err)
					return []GpuInfo{}
				}
				slog.Debug("rocm supported GPUs", "types", supported)
			}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
294
			gfx := gpuInfo.Compute
Daniel Hiltgen's avatar
Daniel Hiltgen committed
295
296
297
298
299
300
301
302
303
			if !slices.Contains[[]string, string](supported, gfx) {
				slog.Warn("amdgpu is not supported", "gpu", gpuInfo.ID, "gpu_type", gfx, "library", libDir, "supported_types", supported)
				// TODO - consider discrete markdown just for ROCM troubleshooting?
				slog.Warn("See https://github.com/ollama/ollama/blob/main/docs/gpu.md#overrides for HSA_OVERRIDE_GFX_VERSION usage")
				continue
			} else {
				slog.Info("amdgpu is supported", "gpu", gpuInfo.ID, "gpu_type", gfx)
			}
		} else {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
304
			slog.Info("skipping rocm gfx compatibility check", "HSA_OVERRIDE_GFX_VERSION", gfxOverride)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
305
306
307
308
		}

		// The GPU has passed all the verification steps and is supported
		resp = append(resp, gpuInfo)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
309
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
310
311
	if len(resp) == 0 {
		slog.Info("no compatible amdgpu devices detected")
Daniel Hiltgen's avatar
Daniel Hiltgen committed
312
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
313
	return resp
Daniel Hiltgen's avatar
Daniel Hiltgen committed
314
315
316
317
318
319
320
321
322
323
324
}

// Quick check for AMD driver so we can skip amdgpu discovery if not present
func AMDDetected() bool {
	// Some driver versions (older?) don't have a version file, so just lookup the parent dir
	sysfsDir := filepath.Dir(DriverVersionFile)
	_, err := os.Stat(sysfsDir)
	if errors.Is(err, os.ErrNotExist) {
		slog.Debug("amdgpu driver not detected " + sysfsDir)
		return false
	} else if err != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
325
		slog.Debug("error looking up amd driver", "path", sysfsDir, "error", err)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
326
327
328
329
330
331
332
333
		return false
	}
	return true
}

// Prefer to use host installed ROCm, as long as it meets our minimum requirements
// failing that, tell the user how to download it on their own
func AMDValidateLibDir() (string, error) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
334
	libDir, err := commonAMDValidateLibDir()
335
	if err == nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
336
		return libDir, nil
337
338
	}

339
340
341
	// Well known ollama installer path
	installedRocmDir := "/usr/share/ollama/lib/rocm"
	if rocmLibUsable(installedRocmDir) {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
342
		return installedRocmDir, nil
Daniel Hiltgen's avatar
Daniel Hiltgen committed
343
344
	}

345
346
	// If we still haven't found a usable rocm, the user will have to install it on their own
	slog.Warn("amdgpu detected, but no compatible rocm library found.  Either install rocm v6, or follow manual install instructions at https://github.com/ollama/ollama/blob/main/docs/linux.md#manual-install")
Daniel Hiltgen's avatar
Daniel Hiltgen committed
347
348
349
	return "", fmt.Errorf("no suitable rocm found, falling back to CPU")
}

Daniel Hiltgen's avatar
Daniel Hiltgen committed
350
351
func AMDDriverVersion() (driverMajor, driverMinor int, err error) {
	_, err = os.Stat(DriverVersionFile)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
352
	if err != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
353
		return 0, 0, fmt.Errorf("amdgpu version file missing: %s %w", DriverVersionFile, err)
Daniel Hiltgen's avatar
Daniel Hiltgen committed
354
355
356
	}
	fp, err := os.Open(DriverVersionFile)
	if err != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
357
		return 0, 0, err
Daniel Hiltgen's avatar
Daniel Hiltgen committed
358
359
360
361
	}
	defer fp.Close()
	verString, err := io.ReadAll(fp)
	if err != nil {
Daniel Hiltgen's avatar
Daniel Hiltgen committed
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
		return 0, 0, err
	}

	pattern := `\A(\d+)\.(\d+).*`
	regex := regexp.MustCompile(pattern)
	match := regex.FindStringSubmatch(string(verString))
	if len(match) < 2 {
		return 0, 0, fmt.Errorf("malformed version string %s", string(verString))
	}
	driverMajor, err = strconv.Atoi(match[1])
	if err != nil {
		return 0, 0, err
	}
	driverMinor, err = strconv.Atoi(match[2])
	if err != nil {
		return 0, 0, err
Daniel Hiltgen's avatar
Daniel Hiltgen committed
378
	}
Daniel Hiltgen's avatar
Daniel Hiltgen committed
379
	return driverMajor, driverMinor, nil
Daniel Hiltgen's avatar
Daniel Hiltgen committed
380
}