amd_linux.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. package gpu
  2. import (
  3. "bufio"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "log/slog"
  8. "os"
  9. "path/filepath"
  10. "regexp"
  11. "slices"
  12. "strconv"
  13. "strings"
  14. "github.com/ollama/ollama/format"
  15. )
  16. // Discovery logic for AMD/ROCm GPUs
  17. const (
  18. DriverVersionFile = "/sys/module/amdgpu/version"
  19. AMDNodesSysfsDir = "/sys/class/kfd/kfd/topology/nodes/"
  20. GPUPropertiesFileGlob = AMDNodesSysfsDir + "*/properties"
  21. // Prefix with the node dir
  22. GPUTotalMemoryFileGlob = "mem_banks/*/properties" // size_in_bytes line
  23. // Direct Rendering Manager sysfs location
  24. DRMDeviceDirGlob = "/sys/class/drm/card[0-9]/device"
  25. DRMTotalMemoryFile = "mem_info_vram_total"
  26. DRMUsedMemoryFile = "mem_info_vram_used"
  27. // In hex; properties file is in decimal
  28. DRMUniqueIDFile = "unique_id"
  29. DRMVendorFile = "vendor"
  30. DRMDeviceFile = "device"
  31. )
  32. var (
  33. // Used to validate if the given ROCm lib is usable
  34. ROCmLibGlobs = []string{"libhipblas.so.2*", "rocblas"} // TODO - probably include more coverage of files here...
  35. RocmStandardLocations = []string{"/opt/rocm/lib", "/usr/lib64"}
  36. )
  37. // Gather GPU information from the amdgpu driver if any supported GPUs are detected
  38. func AMDGetGPUInfo() []GpuInfo {
  39. resp := []GpuInfo{}
  40. if !AMDDetected() {
  41. return resp
  42. }
  43. // Opportunistic logging of driver version to aid in troubleshooting
  44. driverMajor, driverMinor, err := AMDDriverVersion()
  45. if err != nil {
  46. // 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
  47. slog.Warn("ollama recommends running the https://www.amd.com/en/support/linux-drivers", "error", err)
  48. }
  49. // Determine if the user has already pre-selected which GPUs to look at, then ignore the others
  50. var visibleDevices []string
  51. hipVD := os.Getenv("HIP_VISIBLE_DEVICES") // zero based index only
  52. rocrVD := os.Getenv("ROCR_VISIBLE_DEVICES") // zero based index or UUID, but consumer cards seem to not support UUID
  53. gpuDO := os.Getenv("GPU_DEVICE_ORDINAL") // zero based index
  54. switch {
  55. // TODO is this priorty order right?
  56. case hipVD != "":
  57. visibleDevices = strings.Split(hipVD, ",")
  58. case rocrVD != "":
  59. visibleDevices = strings.Split(rocrVD, ",")
  60. // TODO - since we don't yet support UUIDs, consider detecting and reporting here
  61. // all our test systems show GPU-XX indicating UUID is not supported
  62. case gpuDO != "":
  63. visibleDevices = strings.Split(gpuDO, ",")
  64. }
  65. gfxOverride := os.Getenv("HSA_OVERRIDE_GFX_VERSION")
  66. var supported []string
  67. libDir := ""
  68. // The amdgpu driver always exposes the host CPU(s) first, but we have to skip them and subtract
  69. // from the other IDs to get alignment with the HIP libraries expectations (zero is the first GPU, not the CPU)
  70. matches, _ := filepath.Glob(GPUPropertiesFileGlob)
  71. cpuCount := 0
  72. for _, match := range matches {
  73. slog.Debug("evaluating amdgpu node " + match)
  74. fp, err := os.Open(match)
  75. if err != nil {
  76. slog.Debug("failed to open sysfs node", "file", match, "error", err)
  77. continue
  78. }
  79. defer fp.Close()
  80. nodeID, err := strconv.Atoi(filepath.Base(filepath.Dir(match)))
  81. if err != nil {
  82. slog.Debug("failed to parse node ID", "error", err)
  83. continue
  84. }
  85. scanner := bufio.NewScanner(fp)
  86. isCPU := false
  87. var major, minor, patch uint64
  88. var vendor, device, uniqueID uint64
  89. for scanner.Scan() {
  90. line := strings.TrimSpace(scanner.Text())
  91. // Note: we could also use "cpu_cores_count X" where X is greater than zero to detect CPUs
  92. if strings.HasPrefix(line, "gfx_target_version") {
  93. ver := strings.Fields(line)
  94. // Detect CPUs
  95. if len(ver) == 2 && ver[1] == "0" {
  96. slog.Debug("detected CPU " + match)
  97. isCPU = true
  98. break
  99. }
  100. if len(ver) != 2 || len(ver[1]) < 5 {
  101. slog.Warn("malformed "+match, "gfx_target_version", line)
  102. // If this winds up being a CPU, our offsets may be wrong
  103. continue
  104. }
  105. l := len(ver[1])
  106. var err1, err2, err3 error
  107. patch, err1 = strconv.ParseUint(ver[1][l-2:l], 10, 32)
  108. minor, err2 = strconv.ParseUint(ver[1][l-4:l-2], 10, 32)
  109. major, err3 = strconv.ParseUint(ver[1][:l-4], 10, 32)
  110. if err1 != nil || err2 != nil || err3 != nil {
  111. slog.Debug("malformed int " + line)
  112. continue
  113. }
  114. } else if strings.HasPrefix(line, "vendor_id") {
  115. ver := strings.Fields(line)
  116. if len(ver) != 2 {
  117. slog.Debug("malformed", "vendor_id", line)
  118. continue
  119. }
  120. vendor, err = strconv.ParseUint(ver[1], 10, 64)
  121. if err != nil {
  122. slog.Debug("malformed", "vendor_id", line, "error", err)
  123. }
  124. } else if strings.HasPrefix(line, "device_id") {
  125. ver := strings.Fields(line)
  126. if len(ver) != 2 {
  127. slog.Debug("malformed", "device_id", line)
  128. continue
  129. }
  130. device, err = strconv.ParseUint(ver[1], 10, 64)
  131. if err != nil {
  132. slog.Debug("malformed", "device_id", line, "error", err)
  133. }
  134. } else if strings.HasPrefix(line, "unique_id") {
  135. ver := strings.Fields(line)
  136. if len(ver) != 2 {
  137. slog.Debug("malformed", "unique_id", line)
  138. continue
  139. }
  140. uniqueID, err = strconv.ParseUint(ver[1], 10, 64)
  141. if err != nil {
  142. slog.Debug("malformed", "unique_id", line, "error", err)
  143. }
  144. }
  145. // TODO - any other properties we want to extract and record?
  146. // vendor_id + device_id -> pci lookup for "Name"
  147. // Other metrics that may help us understand relative performance between multiple GPUs
  148. }
  149. // Note: while ./mem_banks/*/used_memory exists, it doesn't appear to take other VRAM consumers
  150. // into consideration, so we instead map the device over to the DRM driver sysfs nodes which
  151. // do reliably report VRAM usage.
  152. if isCPU {
  153. cpuCount++
  154. continue
  155. }
  156. // CPUs are always first in the list
  157. gpuID := nodeID - cpuCount
  158. // Shouldn't happen, but just in case...
  159. if gpuID < 0 {
  160. slog.Error("unexpected amdgpu sysfs data resulted in negative GPU ID, please set OLLAMA_DEBUG=1 and report an issue")
  161. return []GpuInfo{}
  162. }
  163. if int(major) < RocmComputeMin {
  164. slog.Warn(fmt.Sprintf("amdgpu too old gfx%d%x%x", major, minor, patch), "gpu", gpuID)
  165. continue
  166. }
  167. // Look up the memory for the current node
  168. totalMemory := uint64(0)
  169. usedMemory := uint64(0)
  170. mapping := []struct {
  171. id uint64
  172. filename string
  173. }{
  174. {vendor, DRMVendorFile},
  175. {device, DRMDeviceFile},
  176. {uniqueID, DRMUniqueIDFile}, // Not all devices will report this
  177. }
  178. slog.Debug("mapping amdgpu to drm sysfs nodes", "amdgpu", match, "vendor", vendor, "device", device, "unique_id", uniqueID)
  179. // Map over to DRM location to find the total/free memory
  180. drmMatches, _ := filepath.Glob(DRMDeviceDirGlob)
  181. for _, devDir := range drmMatches {
  182. matched := true
  183. for _, m := range mapping {
  184. if m.id == 0 {
  185. continue
  186. }
  187. filename := filepath.Join(devDir, m.filename)
  188. fp, err := os.Open(filename)
  189. if err != nil {
  190. slog.Debug("failed to open sysfs node", "file", filename, "error", err)
  191. matched = false
  192. break
  193. }
  194. defer fp.Close()
  195. buf, err := io.ReadAll(fp)
  196. if err != nil {
  197. slog.Debug("failed to read sysfs node", "file", filename, "error", err)
  198. matched = false
  199. break
  200. }
  201. cmp, err := strconv.ParseUint(strings.TrimPrefix(strings.TrimSpace(string(buf)), "0x"), 16, 64)
  202. if err != nil {
  203. slog.Debug("failed to parse sysfs node", "file", filename, "error", err)
  204. matched = false
  205. break
  206. }
  207. if cmp != m.id {
  208. matched = false
  209. break
  210. }
  211. }
  212. if !matched {
  213. continue
  214. }
  215. // Found the matching DRM directory
  216. slog.Debug("matched", "amdgpu", match, "drm", devDir)
  217. totalFile := filepath.Join(devDir, DRMTotalMemoryFile)
  218. totalFp, err := os.Open(totalFile)
  219. if err != nil {
  220. slog.Debug("failed to open sysfs node", "file", totalFile, "error", err)
  221. break
  222. }
  223. defer totalFp.Close()
  224. buf, err := io.ReadAll(totalFp)
  225. if err != nil {
  226. slog.Debug("failed to read sysfs node", "file", totalFile, "error", err)
  227. break
  228. }
  229. totalMemory, err = strconv.ParseUint(strings.TrimSpace(string(buf)), 10, 64)
  230. if err != nil {
  231. slog.Debug("failed to parse sysfs node", "file", totalFile, "error", err)
  232. break
  233. }
  234. usedFile := filepath.Join(devDir, DRMUsedMemoryFile)
  235. usedFp, err := os.Open(usedFile)
  236. if err != nil {
  237. slog.Debug("failed to open sysfs node", "file", usedFile, "error", err)
  238. break
  239. }
  240. defer totalFp.Close()
  241. buf, err = io.ReadAll(usedFp)
  242. if err != nil {
  243. slog.Debug("failed to read sysfs node", "file", usedFile, "error", err)
  244. break
  245. }
  246. usedMemory, err = strconv.ParseUint(strings.TrimSpace(string(buf)), 10, 64)
  247. if err != nil {
  248. slog.Debug("failed to parse sysfs node", "file", usedFile, "error", err)
  249. break
  250. }
  251. break
  252. }
  253. // iGPU detection, remove this check once we can support an iGPU variant of the rocm library
  254. if totalMemory < IGPUMemLimit {
  255. slog.Info("unsupported Radeon iGPU detected skipping", "id", gpuID, "total", format.HumanBytes2(totalMemory))
  256. continue
  257. }
  258. var name string
  259. // TODO - PCI ID lookup
  260. if vendor > 0 && device > 0 {
  261. name = fmt.Sprintf("%04x:%04x", vendor, device)
  262. }
  263. slog.Debug("amdgpu memory", "gpu", gpuID, "total", format.HumanBytes2(totalMemory))
  264. slog.Debug("amdgpu memory", "gpu", gpuID, "available", format.HumanBytes2(totalMemory-usedMemory))
  265. gpuInfo := GpuInfo{
  266. Library: "rocm",
  267. memInfo: memInfo{
  268. TotalMemory: totalMemory,
  269. FreeMemory: (totalMemory - usedMemory),
  270. },
  271. ID: fmt.Sprintf("%d", gpuID),
  272. Name: name,
  273. Compute: fmt.Sprintf("gfx%d%x%x", major, minor, patch),
  274. MinimumMemory: rocmMinimumMemory,
  275. DriverMajor: driverMajor,
  276. DriverMinor: driverMinor,
  277. }
  278. // If the user wants to filter to a subset of devices, filter out if we aren't a match
  279. if len(visibleDevices) > 0 {
  280. include := false
  281. for _, visible := range visibleDevices {
  282. if visible == gpuInfo.ID {
  283. include = true
  284. break
  285. }
  286. }
  287. if !include {
  288. slog.Info("filtering out device per user request", "id", gpuInfo.ID, "visible_devices", visibleDevices)
  289. continue
  290. }
  291. }
  292. // Final validation is gfx compatibility - load the library if we haven't already loaded it
  293. // even if the user overrides, we still need to validate the library
  294. if libDir == "" {
  295. libDir, err = AMDValidateLibDir()
  296. if err != nil {
  297. slog.Warn("unable to verify rocm library, will use cpu", "error", err)
  298. return []GpuInfo{}
  299. }
  300. }
  301. gpuInfo.DependencyPath = libDir
  302. if gfxOverride == "" {
  303. // Only load supported list once
  304. if len(supported) == 0 {
  305. supported, err = GetSupportedGFX(libDir)
  306. if err != nil {
  307. slog.Warn("failed to lookup supported GFX types, falling back to CPU mode", "error", err)
  308. return []GpuInfo{}
  309. }
  310. slog.Debug("rocm supported GPUs", "types", supported)
  311. }
  312. gfx := gpuInfo.Compute
  313. if !slices.Contains[[]string, string](supported, gfx) {
  314. slog.Warn("amdgpu is not supported", "gpu", gpuInfo.ID, "gpu_type", gfx, "library", libDir, "supported_types", supported)
  315. // TODO - consider discrete markdown just for ROCM troubleshooting?
  316. slog.Warn("See https://github.com/ollama/ollama/blob/main/docs/gpu.md#overrides for HSA_OVERRIDE_GFX_VERSION usage")
  317. continue
  318. } else {
  319. slog.Info("amdgpu is supported", "gpu", gpuInfo.ID, "gpu_type", gfx)
  320. }
  321. } else {
  322. slog.Info("skipping rocm gfx compatibility check", "HSA_OVERRIDE_GFX_VERSION", gfxOverride)
  323. }
  324. // The GPU has passed all the verification steps and is supported
  325. resp = append(resp, gpuInfo)
  326. }
  327. if len(resp) == 0 {
  328. slog.Info("no compatible amdgpu devices detected")
  329. }
  330. return resp
  331. }
  332. // Quick check for AMD driver so we can skip amdgpu discovery if not present
  333. func AMDDetected() bool {
  334. // Some driver versions (older?) don't have a version file, so just lookup the parent dir
  335. sysfsDir := filepath.Dir(DriverVersionFile)
  336. _, err := os.Stat(sysfsDir)
  337. if errors.Is(err, os.ErrNotExist) {
  338. slog.Debug("amdgpu driver not detected " + sysfsDir)
  339. return false
  340. } else if err != nil {
  341. slog.Debug("error looking up amd driver", "path", sysfsDir, "error", err)
  342. return false
  343. }
  344. return true
  345. }
  346. // Prefer to use host installed ROCm, as long as it meets our minimum requirements
  347. // failing that, tell the user how to download it on their own
  348. func AMDValidateLibDir() (string, error) {
  349. libDir, err := commonAMDValidateLibDir()
  350. if err == nil {
  351. return libDir, nil
  352. }
  353. // Well known ollama installer path
  354. installedRocmDir := "/usr/share/ollama/lib/rocm"
  355. if rocmLibUsable(installedRocmDir) {
  356. return installedRocmDir, nil
  357. }
  358. // If we still haven't found a usable rocm, the user will have to install it on their own
  359. 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")
  360. return "", fmt.Errorf("no suitable rocm found, falling back to CPU")
  361. }
  362. func AMDDriverVersion() (driverMajor, driverMinor int, err error) {
  363. _, err = os.Stat(DriverVersionFile)
  364. if err != nil {
  365. return 0, 0, fmt.Errorf("amdgpu version file missing: %s %w", DriverVersionFile, err)
  366. }
  367. fp, err := os.Open(DriverVersionFile)
  368. if err != nil {
  369. return 0, 0, err
  370. }
  371. defer fp.Close()
  372. verString, err := io.ReadAll(fp)
  373. if err != nil {
  374. return 0, 0, err
  375. }
  376. pattern := `\A(\d+)\.(\d+).*`
  377. regex := regexp.MustCompile(pattern)
  378. match := regex.FindStringSubmatch(string(verString))
  379. if len(match) < 2 {
  380. return 0, 0, fmt.Errorf("malformed version string %s", string(verString))
  381. }
  382. driverMajor, err = strconv.Atoi(match[1])
  383. if err != nil {
  384. return 0, 0, err
  385. }
  386. driverMinor, err = strconv.Atoi(match[2])
  387. if err != nil {
  388. return 0, 0, err
  389. }
  390. return driverMajor, driverMinor, nil
  391. }