amd_linux.go 14 KB

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