amd_linux.go 11 KB

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