amd_linux.go 16 KB

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