amd_linux.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. package discover
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/fs"
  8. "log/slog"
  9. "os"
  10. "path/filepath"
  11. "regexp"
  12. "slices"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "github.com/ollama/ollama/envconfig"
  17. "github.com/ollama/ollama/format"
  18. )
  19. // Discovery logic for AMD/ROCm GPUs
  20. const (
  21. DriverVersionFile = "/sys/module/amdgpu/version"
  22. AMDNodesSysfsDir = "/sys/class/kfd/kfd/topology/nodes/"
  23. GPUPropertiesFileGlob = AMDNodesSysfsDir + "*/properties"
  24. // Prefix with the node dir
  25. GPUTotalMemoryFileGlob = "mem_banks/*/properties" // size_in_bytes line
  26. // Direct Rendering Manager sysfs location
  27. DRMDeviceDirGlob = "/sys/class/drm/card*/device"
  28. DRMTotalMemoryFile = "mem_info_vram_total"
  29. DRMUsedMemoryFile = "mem_info_vram_used"
  30. // In hex; properties file is in decimal
  31. DRMUniqueIDFile = "unique_id"
  32. DRMVendorFile = "vendor"
  33. DRMDeviceFile = "device"
  34. )
  35. var (
  36. // Used to validate if the given ROCm lib is usable
  37. ROCmLibGlobs = []string{"libhipblas.so.2*", "rocblas"} // TODO - probably include more coverage of files here...
  38. RocmStandardLocations = []string{"/opt/rocm/lib", "/usr/lib64"}
  39. )
  40. // Gather GPU information from the amdgpu driver if any supported GPUs are detected
  41. // Only called once during bootstrap
  42. func AMDGetGPUInfo() ([]RocmGPUInfo, error) {
  43. resp := []RocmGPUInfo{}
  44. if !AMDDetected() {
  45. return resp, fmt.Errorf("AMD GPUs not detected")
  46. }
  47. // Opportunistic logging of driver version to aid in troubleshooting
  48. driverMajor, driverMinor, err := AMDDriverVersion()
  49. if err != nil {
  50. // 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
  51. slog.Warn("ollama recommends running the https://www.amd.com/en/support/linux-drivers", "error", err)
  52. }
  53. // Determine if the user has already pre-selected which GPUs to look at, then ignore the others
  54. var visibleDevices []string
  55. hipVD := envconfig.HipVisibleDevices() // zero based index only
  56. rocrVD := envconfig.RocrVisibleDevices() // zero based index or UUID
  57. gpuDO := envconfig.GpuDeviceOrdinal() // zero based index
  58. switch {
  59. case rocrVD != "":
  60. visibleDevices = strings.Split(rocrVD, ",")
  61. case hipVD != "":
  62. visibleDevices = strings.Split(hipVD, ",")
  63. case gpuDO != "":
  64. visibleDevices = strings.Split(gpuDO, ",")
  65. }
  66. gfxOverride := envconfig.HsaOverrideGfxVersion()
  67. var supported []string
  68. libDir := ""
  69. // The amdgpu driver always exposes the host CPU(s) first, but we have to skip them and subtract
  70. // from the other IDs to get alignment with the HIP libraries expectations (zero is the first GPU, not the CPU)
  71. matches, _ := filepath.Glob(GPUPropertiesFileGlob)
  72. sort.Slice(matches, func(i, j int) bool {
  73. // /sys/class/kfd/kfd/topology/nodes/<number>/properties
  74. a, err := strconv.ParseInt(filepath.Base(filepath.Dir(matches[i])), 10, 64)
  75. if err != nil {
  76. slog.Debug("parse err", "error", err, "match", matches[i])
  77. return false
  78. }
  79. b, err := strconv.ParseInt(filepath.Base(filepath.Dir(matches[j])), 10, 64)
  80. if err != nil {
  81. slog.Debug("parse err", "error", err, "match", matches[i])
  82. return false
  83. }
  84. return a < b
  85. })
  86. gpuCount := 0
  87. for _, match := range matches {
  88. slog.Debug("evaluating amdgpu node " + match)
  89. fp, err := os.Open(match)
  90. if err != nil {
  91. slog.Debug("failed to open sysfs node", "file", match, "error", err)
  92. continue
  93. }
  94. defer fp.Close()
  95. scanner := bufio.NewScanner(fp)
  96. isCPU := false
  97. var major, minor, patch uint64
  98. var vendor, device, uniqueID uint64
  99. for scanner.Scan() {
  100. line := strings.TrimSpace(scanner.Text())
  101. // Note: we could also use "cpu_cores_count X" where X is greater than zero to detect CPUs
  102. if strings.HasPrefix(line, "gfx_target_version") {
  103. ver := strings.Fields(line)
  104. // Detect CPUs
  105. if len(ver) == 2 && ver[1] == "0" {
  106. slog.Debug("detected CPU " + match)
  107. isCPU = true
  108. break
  109. }
  110. if len(ver) != 2 || len(ver[1]) < 5 {
  111. slog.Warn("malformed "+match, "gfx_target_version", line)
  112. // If this winds up being a CPU, our offsets may be wrong
  113. continue
  114. }
  115. l := len(ver[1])
  116. var err1, err2, err3 error
  117. patch, err1 = strconv.ParseUint(ver[1][l-2:l], 10, 32)
  118. minor, err2 = strconv.ParseUint(ver[1][l-4:l-2], 10, 32)
  119. major, err3 = strconv.ParseUint(ver[1][:l-4], 10, 32)
  120. if err1 != nil || err2 != nil || err3 != nil {
  121. slog.Debug("malformed int " + line)
  122. continue
  123. }
  124. } else if strings.HasPrefix(line, "vendor_id") {
  125. ver := strings.Fields(line)
  126. if len(ver) != 2 {
  127. slog.Debug("malformed", "vendor_id", line)
  128. continue
  129. }
  130. vendor, err = strconv.ParseUint(ver[1], 10, 64)
  131. if err != nil {
  132. slog.Debug("malformed", "vendor_id", line, "error", err)
  133. }
  134. } else if strings.HasPrefix(line, "device_id") {
  135. ver := strings.Fields(line)
  136. if len(ver) != 2 {
  137. slog.Debug("malformed", "device_id", line)
  138. continue
  139. }
  140. device, err = strconv.ParseUint(ver[1], 10, 64)
  141. if err != nil {
  142. slog.Debug("malformed", "device_id", line, "error", err)
  143. }
  144. } else if strings.HasPrefix(line, "unique_id") {
  145. ver := strings.Fields(line)
  146. if len(ver) != 2 {
  147. slog.Debug("malformed", "unique_id", line)
  148. continue
  149. }
  150. uniqueID, err = strconv.ParseUint(ver[1], 10, 64)
  151. if err != nil {
  152. slog.Debug("malformed", "unique_id", line, "error", err)
  153. }
  154. }
  155. // TODO - any other properties we want to extract and record?
  156. // vendor_id + device_id -> pci lookup for "Name"
  157. // Other metrics that may help us understand relative performance between multiple GPUs
  158. }
  159. // Note: while ./mem_banks/*/used_memory exists, it doesn't appear to take other VRAM consumers
  160. // into consideration, so we instead map the device over to the DRM driver sysfs nodes which
  161. // do reliably report VRAM usage.
  162. if isCPU {
  163. continue
  164. }
  165. // Skip over any GPUs that are masked
  166. if major == 0 && minor == 0 && patch == 0 {
  167. slog.Debug("skipping gpu with gfx000")
  168. continue
  169. }
  170. // Keep track of numeric IDs based on valid GPUs
  171. gpuID := gpuCount
  172. gpuCount += 1
  173. // Look up the memory for the current node
  174. totalMemory := uint64(0)
  175. usedMemory := uint64(0)
  176. var usedFile string
  177. mapping := []struct {
  178. id uint64
  179. filename string
  180. }{
  181. {vendor, DRMVendorFile},
  182. {device, DRMDeviceFile},
  183. {uniqueID, DRMUniqueIDFile}, // Not all devices will report this
  184. }
  185. slog.Debug("mapping amdgpu to drm sysfs nodes", "amdgpu", match, "vendor", vendor, "device", device, "unique_id", uniqueID)
  186. // Map over to DRM location to find the total/free memory
  187. drmMatches, _ := filepath.Glob(DRMDeviceDirGlob)
  188. for _, devDir := range drmMatches {
  189. matched := true
  190. for _, m := range mapping {
  191. if m.id == 0 {
  192. // Null ID means it didn't populate, so we can't use it to match
  193. continue
  194. }
  195. filename := filepath.Join(devDir, m.filename)
  196. buf, err := os.ReadFile(filename)
  197. if err != nil {
  198. slog.Debug("failed to read sysfs node", "file", filename, "error", err)
  199. matched = false
  200. break
  201. }
  202. // values here are in hex, strip off the lead 0x and parse so we can compare the numeric (decimal) values in amdgpu
  203. cmp, err := strconv.ParseUint(strings.TrimPrefix(strings.TrimSpace(string(buf)), "0x"), 16, 64)
  204. if err != nil {
  205. slog.Debug("failed to parse sysfs node", "file", filename, "error", err)
  206. matched = false
  207. break
  208. }
  209. if cmp != m.id {
  210. matched = false
  211. break
  212. }
  213. }
  214. if !matched {
  215. continue
  216. }
  217. // Found the matching DRM directory
  218. slog.Debug("matched", "amdgpu", match, "drm", devDir)
  219. totalFile := filepath.Join(devDir, DRMTotalMemoryFile)
  220. buf, err := os.ReadFile(totalFile)
  221. if err != nil {
  222. slog.Debug("failed to read sysfs node", "file", totalFile, "error", err)
  223. break
  224. }
  225. totalMemory, err = strconv.ParseUint(strings.TrimSpace(string(buf)), 10, 64)
  226. if err != nil {
  227. slog.Debug("failed to parse sysfs node", "file", totalFile, "error", err)
  228. break
  229. }
  230. usedFile = filepath.Join(devDir, DRMUsedMemoryFile)
  231. usedMemory, err = getFreeMemory(usedFile)
  232. if err != nil {
  233. slog.Debug("failed to update used memory", "error", err)
  234. }
  235. break
  236. }
  237. var name string
  238. // TODO - PCI ID lookup
  239. if vendor > 0 && device > 0 {
  240. name = fmt.Sprintf("%04x:%04x", vendor, device)
  241. }
  242. // Favor UUIDs if available to reduce possibility of getting the numeric IDs wrong
  243. var ID string
  244. if uniqueID != 0 {
  245. ID = fmt.Sprintf("GPU-%016x", uniqueID)
  246. } else {
  247. ID = strconv.Itoa(gpuID)
  248. }
  249. gpuInfo := RocmGPUInfo{
  250. GpuInfo: GpuInfo{
  251. Library: "rocm",
  252. memInfo: memInfo{
  253. TotalMemory: totalMemory,
  254. FreeMemory: (totalMemory - usedMemory),
  255. },
  256. ID: ID,
  257. Name: name,
  258. Compute: fmt.Sprintf("gfx%d%x%x", major, minor, patch),
  259. MinimumMemory: rocmMinimumMemory,
  260. DriverMajor: driverMajor,
  261. DriverMinor: driverMinor,
  262. },
  263. usedFilepath: usedFile,
  264. index: gpuID,
  265. }
  266. // iGPU detection, remove this check once we can support an iGPU variant of the rocm library
  267. if totalMemory < IGPUMemLimit {
  268. reason := "unsupported Radeon iGPU detected skipping"
  269. slog.Info(reason, "id", gpuID, "total", format.HumanBytes2(totalMemory))
  270. unsupportedGPUs = append(unsupportedGPUs, UnsupportedGPUInfo{
  271. GpuInfo: gpuInfo.GpuInfo,
  272. Reason: reason,
  273. })
  274. continue
  275. }
  276. if int(major) < RocmComputeMin {
  277. reason := fmt.Sprintf("amdgpu too old gfx%d%x%x", major, minor, patch)
  278. slog.Warn(reason, "gpu", gpuID)
  279. unsupportedGPUs = append(unsupportedGPUs, UnsupportedGPUInfo{
  280. GpuInfo: gpuInfo.GpuInfo,
  281. Reason: reason,
  282. })
  283. continue
  284. }
  285. slog.Debug("amdgpu memory", "gpu", gpuID, "total", format.HumanBytes2(totalMemory))
  286. slog.Debug("amdgpu memory", "gpu", gpuID, "available", format.HumanBytes2(totalMemory-usedMemory))
  287. // If the user wants to filter to a subset of devices, filter out if we aren't a match
  288. if len(visibleDevices) > 0 {
  289. include := false
  290. for _, visible := range visibleDevices {
  291. if visible == gpuInfo.ID || visible == strconv.Itoa(gpuInfo.index) {
  292. include = true
  293. break
  294. }
  295. }
  296. if !include {
  297. reason := "filtering out device per user request"
  298. slog.Info(reason, "id", gpuInfo.ID, "visible_devices", visibleDevices)
  299. unsupportedGPUs = append(unsupportedGPUs, UnsupportedGPUInfo{
  300. GpuInfo: gpuInfo.GpuInfo,
  301. Reason: reason,
  302. })
  303. continue
  304. }
  305. }
  306. // Final validation is gfx compatibility - load the library if we haven't already loaded it
  307. // even if the user overrides, we still need to validate the library
  308. if libDir == "" {
  309. libDir, err = AMDValidateLibDir()
  310. if err != nil {
  311. err = fmt.Errorf("unable to verify rocm library: %w", err)
  312. slog.Warn(err.Error())
  313. unsupportedGPUs = append(unsupportedGPUs, UnsupportedGPUInfo{
  314. GpuInfo: gpuInfo.GpuInfo,
  315. Reason: err.Error(),
  316. })
  317. return nil, err
  318. }
  319. }
  320. gpuInfo.DependencyPath = libDir
  321. if gfxOverride == "" {
  322. // Only load supported list once
  323. if len(supported) == 0 {
  324. supported, err = GetSupportedGFX(libDir)
  325. if err != nil {
  326. err = fmt.Errorf("failed to lookup supported GFX types: %w", err)
  327. slog.Warn(err.Error())
  328. unsupportedGPUs = append(unsupportedGPUs, UnsupportedGPUInfo{
  329. GpuInfo: gpuInfo.GpuInfo,
  330. Reason: err.Error(),
  331. })
  332. return nil, err
  333. }
  334. slog.Debug("rocm supported GPUs", "types", supported)
  335. }
  336. gfx := gpuInfo.Compute
  337. if !slices.Contains[[]string, string](supported, gfx) {
  338. reason := fmt.Sprintf("amdgpu is not supported (supported types:%s)", supported)
  339. slog.Warn(reason, "gpu_type", gfx, "gpu", gpuInfo.ID, "library", libDir)
  340. unsupportedGPUs = append(unsupportedGPUs, UnsupportedGPUInfo{
  341. GpuInfo: gpuInfo.GpuInfo,
  342. Reason: reason,
  343. })
  344. // TODO - consider discrete markdown just for ROCM troubleshooting?
  345. slog.Warn("See https://github.com/ollama/ollama/blob/main/docs/gpu.md#overrides for HSA_OVERRIDE_GFX_VERSION usage")
  346. continue
  347. } else {
  348. slog.Info("amdgpu is supported", "gpu", gpuInfo.ID, "gpu_type", gfx)
  349. }
  350. } else {
  351. slog.Info("skipping rocm gfx compatibility check", "HSA_OVERRIDE_GFX_VERSION", gfxOverride)
  352. }
  353. // Check for env var workarounds
  354. if name == "1002:687f" { // Vega RX 56
  355. gpuInfo.EnvWorkarounds = append(gpuInfo.EnvWorkarounds, [2]string{"HSA_ENABLE_SDMA", "0"})
  356. }
  357. // The GPU has passed all the verification steps and is supported
  358. resp = append(resp, gpuInfo)
  359. }
  360. if len(resp) == 0 {
  361. err := fmt.Errorf("no compatible amdgpu devices detected")
  362. slog.Info(err.Error())
  363. return nil, err
  364. }
  365. if err := verifyKFDDriverAccess(); err != nil {
  366. err = fmt.Errorf("amdgpu devices detected but permission problems block access: %w", err)
  367. slog.Error(err.Error())
  368. return nil, err
  369. }
  370. return resp, nil
  371. }
  372. // Quick check for AMD driver so we can skip amdgpu discovery if not present
  373. func AMDDetected() bool {
  374. // Some driver versions (older?) don't have a version file, so just lookup the parent dir
  375. sysfsDir := filepath.Dir(DriverVersionFile)
  376. _, err := os.Stat(sysfsDir)
  377. if errors.Is(err, os.ErrNotExist) {
  378. slog.Debug("amdgpu driver not detected " + sysfsDir)
  379. return false
  380. } else if err != nil {
  381. slog.Debug("error looking up amd driver", "path", sysfsDir, "error", err)
  382. return false
  383. }
  384. return true
  385. }
  386. // Prefer to use host installed ROCm, as long as it meets our minimum requirements
  387. // failing that, tell the user how to download it on their own
  388. func AMDValidateLibDir() (string, error) {
  389. libDir, err := commonAMDValidateLibDir()
  390. if err == nil {
  391. return libDir, nil
  392. }
  393. // Well known ollama installer path
  394. installedRocmDir := "/usr/share/ollama/lib/rocm"
  395. if rocmLibUsable(installedRocmDir) {
  396. return installedRocmDir, nil
  397. }
  398. // If we still haven't found a usable rocm, the user will have to install it on their own
  399. 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")
  400. return "", errors.New("no suitable rocm found, falling back to CPU")
  401. }
  402. func AMDDriverVersion() (driverMajor, driverMinor int, err error) {
  403. _, err = os.Stat(DriverVersionFile)
  404. if err != nil {
  405. return 0, 0, fmt.Errorf("amdgpu version file missing: %s %w", DriverVersionFile, err)
  406. }
  407. fp, err := os.Open(DriverVersionFile)
  408. if err != nil {
  409. return 0, 0, err
  410. }
  411. defer fp.Close()
  412. verString, err := io.ReadAll(fp)
  413. if err != nil {
  414. return 0, 0, err
  415. }
  416. pattern := `\A(\d+)\.(\d+).*`
  417. regex := regexp.MustCompile(pattern)
  418. match := regex.FindStringSubmatch(string(verString))
  419. if len(match) < 2 {
  420. return 0, 0, fmt.Errorf("malformed version string %s", string(verString))
  421. }
  422. driverMajor, err = strconv.Atoi(match[1])
  423. if err != nil {
  424. return 0, 0, err
  425. }
  426. driverMinor, err = strconv.Atoi(match[2])
  427. if err != nil {
  428. return 0, 0, err
  429. }
  430. return driverMajor, driverMinor, nil
  431. }
  432. func (gpus RocmGPUInfoList) RefreshFreeMemory() error {
  433. if len(gpus) == 0 {
  434. return nil
  435. }
  436. for i := range gpus {
  437. usedMemory, err := getFreeMemory(gpus[i].usedFilepath)
  438. if err != nil {
  439. return err
  440. }
  441. slog.Debug("updating rocm free memory", "gpu", gpus[i].ID, "name", gpus[i].Name, "before", format.HumanBytes2(gpus[i].FreeMemory), "now", format.HumanBytes2(gpus[i].TotalMemory-usedMemory))
  442. gpus[i].FreeMemory = gpus[i].TotalMemory - usedMemory
  443. }
  444. return nil
  445. }
  446. func getFreeMemory(usedFile string) (uint64, error) {
  447. buf, err := os.ReadFile(usedFile)
  448. if err != nil {
  449. return 0, fmt.Errorf("failed to read sysfs node %s %w", usedFile, err)
  450. }
  451. usedMemory, err := strconv.ParseUint(strings.TrimSpace(string(buf)), 10, 64)
  452. if err != nil {
  453. slog.Debug("failed to parse sysfs node", "file", usedFile, "error", err)
  454. return 0, fmt.Errorf("failed to parse sysfs node %s %w", usedFile, err)
  455. }
  456. return usedMemory, nil
  457. }
  458. func verifyKFDDriverAccess() error {
  459. // Verify we have permissions - either running as root, or we have group access to the driver
  460. fd, err := os.OpenFile("/dev/kfd", os.O_RDWR, 0o666)
  461. if err != nil {
  462. if errors.Is(err, fs.ErrPermission) {
  463. return fmt.Errorf("permissions not set up properly. Either run ollama as root, or add you user account to the render group. %w", err)
  464. } else if errors.Is(err, fs.ErrNotExist) {
  465. // Container runtime failure?
  466. return fmt.Errorf("kfd driver not loaded. If running in a container, remember to include '--device /dev/kfd --device /dev/dri'")
  467. }
  468. return fmt.Errorf("failed to check permission on /dev/kfd: %w", err)
  469. }
  470. fd.Close()
  471. return nil
  472. }
  473. func rocmGetVisibleDevicesEnv(gpuInfo []GpuInfo) (string, string) {
  474. ids := []string{}
  475. for _, info := range gpuInfo {
  476. if info.Library != "rocm" {
  477. // TODO shouldn't happen if things are wired correctly...
  478. slog.Debug("rocmGetVisibleDevicesEnv skipping over non-rocm device", "library", info.Library)
  479. continue
  480. }
  481. ids = append(ids, info.ID)
  482. }
  483. // There are 3 potential env vars to use to select GPUs.
  484. // ROCR_VISIBLE_DEVICES supports UUID or numeric so is our preferred on linux
  485. // GPU_DEVICE_ORDINAL supports numeric IDs only
  486. // HIP_VISIBLE_DEVICES supports numeric IDs only
  487. return "ROCR_VISIBLE_DEVICES", strings.Join(ids, ",")
  488. }