amd_linux.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. var libDir string
  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. minVer, err := strconv.Atoi(RocmComputeMajorMin)
  277. if err != nil {
  278. slog.Error("invalid RocmComputeMajorMin setting", "value", RocmComputeMajorMin, "error", err)
  279. }
  280. if int(major) < minVer {
  281. reason := fmt.Sprintf("amdgpu too old gfx%d%x%x", major, minor, patch)
  282. slog.Warn(reason, "gpu", gpuID)
  283. unsupportedGPUs = append(unsupportedGPUs, UnsupportedGPUInfo{
  284. GpuInfo: gpuInfo.GpuInfo,
  285. Reason: reason,
  286. })
  287. continue
  288. }
  289. slog.Debug("amdgpu memory", "gpu", gpuID, "total", format.HumanBytes2(totalMemory))
  290. slog.Debug("amdgpu memory", "gpu", gpuID, "available", format.HumanBytes2(totalMemory-usedMemory))
  291. // If the user wants to filter to a subset of devices, filter out if we aren't a match
  292. if len(visibleDevices) > 0 {
  293. include := false
  294. for _, visible := range visibleDevices {
  295. if visible == gpuInfo.ID || visible == strconv.Itoa(gpuInfo.index) {
  296. include = true
  297. break
  298. }
  299. }
  300. if !include {
  301. reason := "filtering out device per user request"
  302. slog.Info(reason, "id", gpuInfo.ID, "visible_devices", visibleDevices)
  303. unsupportedGPUs = append(unsupportedGPUs, UnsupportedGPUInfo{
  304. GpuInfo: gpuInfo.GpuInfo,
  305. Reason: reason,
  306. })
  307. continue
  308. }
  309. }
  310. // Final validation is gfx compatibility - load the library if we haven't already loaded it
  311. // even if the user overrides, we still need to validate the library
  312. if libDir == "" {
  313. libDir, err = AMDValidateLibDir()
  314. if err != nil {
  315. err = fmt.Errorf("unable to verify rocm library: %w", err)
  316. slog.Warn(err.Error())
  317. unsupportedGPUs = append(unsupportedGPUs, UnsupportedGPUInfo{
  318. GpuInfo: gpuInfo.GpuInfo,
  319. Reason: err.Error(),
  320. })
  321. return nil, err
  322. }
  323. }
  324. gpuInfo.DependencyPath = []string{libDir}
  325. if gfxOverride == "" {
  326. // Only load supported list once
  327. if len(supported) == 0 {
  328. supported, err = GetSupportedGFX(libDir)
  329. if err != nil {
  330. err = fmt.Errorf("failed to lookup supported GFX types: %w", err)
  331. slog.Warn(err.Error())
  332. unsupportedGPUs = append(unsupportedGPUs, UnsupportedGPUInfo{
  333. GpuInfo: gpuInfo.GpuInfo,
  334. Reason: err.Error(),
  335. })
  336. return nil, err
  337. }
  338. slog.Debug("rocm supported GPUs", "types", supported)
  339. }
  340. gfx := gpuInfo.Compute
  341. if !slices.Contains[[]string, string](supported, gfx) {
  342. reason := fmt.Sprintf("amdgpu is not supported (supported types:%s)", supported)
  343. slog.Warn(reason, "gpu_type", gfx, "gpu", gpuInfo.ID, "library", libDir)
  344. unsupportedGPUs = append(unsupportedGPUs, UnsupportedGPUInfo{
  345. GpuInfo: gpuInfo.GpuInfo,
  346. Reason: reason,
  347. })
  348. // TODO - consider discrete markdown just for ROCM troubleshooting?
  349. slog.Warn("See https://github.com/ollama/ollama/blob/main/docs/gpu.md#overrides for HSA_OVERRIDE_GFX_VERSION usage")
  350. continue
  351. } else {
  352. slog.Info("amdgpu is supported", "gpu", gpuInfo.ID, "gpu_type", gfx)
  353. }
  354. } else {
  355. slog.Info("skipping rocm gfx compatibility check", "HSA_OVERRIDE_GFX_VERSION", gfxOverride)
  356. }
  357. // Check for env var workarounds
  358. if name == "1002:687f" { // Vega RX 56
  359. gpuInfo.EnvWorkarounds = append(gpuInfo.EnvWorkarounds, [2]string{"HSA_ENABLE_SDMA", "0"})
  360. }
  361. // The GPU has passed all the verification steps and is supported
  362. resp = append(resp, gpuInfo)
  363. }
  364. if len(resp) == 0 {
  365. err := fmt.Errorf("no compatible amdgpu devices detected")
  366. slog.Info(err.Error())
  367. return nil, err
  368. }
  369. if err := verifyKFDDriverAccess(); err != nil {
  370. err = fmt.Errorf("amdgpu devices detected but permission problems block access: %w", err)
  371. slog.Error(err.Error())
  372. return nil, err
  373. }
  374. return resp, nil
  375. }
  376. // Quick check for AMD driver so we can skip amdgpu discovery if not present
  377. func AMDDetected() bool {
  378. // Some driver versions (older?) don't have a version file, so just lookup the parent dir
  379. sysfsDir := filepath.Dir(DriverVersionFile)
  380. _, err := os.Stat(sysfsDir)
  381. if errors.Is(err, os.ErrNotExist) {
  382. slog.Debug("amdgpu driver not detected " + sysfsDir)
  383. return false
  384. } else if err != nil {
  385. slog.Debug("error looking up amd driver", "path", sysfsDir, "error", err)
  386. return false
  387. }
  388. return true
  389. }
  390. // Prefer to use host installed ROCm, as long as it meets our minimum requirements
  391. // failing that, tell the user how to download it on their own
  392. func AMDValidateLibDir() (string, error) {
  393. libDir, err := commonAMDValidateLibDir()
  394. if err == nil {
  395. return libDir, nil
  396. }
  397. // Well known ollama installer path
  398. installedRocmDir := "/usr/share/ollama/lib/rocm"
  399. if rocmLibUsable(installedRocmDir) {
  400. return installedRocmDir, nil
  401. }
  402. // If we still haven't found a usable rocm, the user will have to install it on their own
  403. 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")
  404. return "", errors.New("no suitable rocm found, falling back to CPU")
  405. }
  406. func AMDDriverVersion() (driverMajor, driverMinor int, err error) {
  407. _, err = os.Stat(DriverVersionFile)
  408. if err != nil {
  409. return 0, 0, fmt.Errorf("amdgpu version file missing: %s %w", DriverVersionFile, err)
  410. }
  411. fp, err := os.Open(DriverVersionFile)
  412. if err != nil {
  413. return 0, 0, err
  414. }
  415. defer fp.Close()
  416. verString, err := io.ReadAll(fp)
  417. if err != nil {
  418. return 0, 0, err
  419. }
  420. pattern := `\A(\d+)\.(\d+).*`
  421. regex := regexp.MustCompile(pattern)
  422. match := regex.FindStringSubmatch(string(verString))
  423. if len(match) < 2 {
  424. return 0, 0, fmt.Errorf("malformed version string %s", string(verString))
  425. }
  426. driverMajor, err = strconv.Atoi(match[1])
  427. if err != nil {
  428. return 0, 0, err
  429. }
  430. driverMinor, err = strconv.Atoi(match[2])
  431. if err != nil {
  432. return 0, 0, err
  433. }
  434. return driverMajor, driverMinor, nil
  435. }
  436. func (gpus RocmGPUInfoList) RefreshFreeMemory() error {
  437. if len(gpus) == 0 {
  438. return nil
  439. }
  440. for i := range gpus {
  441. usedMemory, err := getFreeMemory(gpus[i].usedFilepath)
  442. if err != nil {
  443. return err
  444. }
  445. 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))
  446. gpus[i].FreeMemory = gpus[i].TotalMemory - usedMemory
  447. }
  448. return nil
  449. }
  450. func getFreeMemory(usedFile string) (uint64, error) {
  451. buf, err := os.ReadFile(usedFile)
  452. if err != nil {
  453. return 0, fmt.Errorf("failed to read sysfs node %s %w", usedFile, err)
  454. }
  455. usedMemory, err := strconv.ParseUint(strings.TrimSpace(string(buf)), 10, 64)
  456. if err != nil {
  457. slog.Debug("failed to parse sysfs node", "file", usedFile, "error", err)
  458. return 0, fmt.Errorf("failed to parse sysfs node %s %w", usedFile, err)
  459. }
  460. return usedMemory, nil
  461. }
  462. func verifyKFDDriverAccess() error {
  463. // Verify we have permissions - either running as root, or we have group access to the driver
  464. fd, err := os.OpenFile("/dev/kfd", os.O_RDWR, 0o666)
  465. if err != nil {
  466. if errors.Is(err, fs.ErrPermission) {
  467. return fmt.Errorf("permissions not set up properly. Either run ollama as root, or add you user account to the render group. %w", err)
  468. } else if errors.Is(err, fs.ErrNotExist) {
  469. // Container runtime failure?
  470. return fmt.Errorf("kfd driver not loaded. If running in a container, remember to include '--device /dev/kfd --device /dev/dri'")
  471. }
  472. return fmt.Errorf("failed to check permission on /dev/kfd: %w", err)
  473. }
  474. fd.Close()
  475. return nil
  476. }
  477. func rocmGetVisibleDevicesEnv(gpuInfo []GpuInfo) (string, string) {
  478. ids := []string{}
  479. for _, info := range gpuInfo {
  480. if info.Library != "rocm" {
  481. // TODO shouldn't happen if things are wired correctly...
  482. slog.Debug("rocmGetVisibleDevicesEnv skipping over non-rocm device", "library", info.Library)
  483. continue
  484. }
  485. ids = append(ids, info.ID)
  486. }
  487. // There are 3 potential env vars to use to select GPUs.
  488. // ROCR_VISIBLE_DEVICES supports UUID or numeric so is our preferred on linux
  489. // GPU_DEVICE_ORDINAL supports numeric IDs only
  490. // HIP_VISIBLE_DEVICES supports numeric IDs only
  491. return "ROCR_VISIBLE_DEVICES", strings.Join(ids, ",")
  492. }