gpu.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. //go:build linux || windows
  2. package gpu
  3. /*
  4. #cgo linux LDFLAGS: -lrt -lpthread -ldl -lstdc++ -lm
  5. #cgo windows LDFLAGS: -lpthread
  6. #include "gpu_info.h"
  7. */
  8. import "C"
  9. import (
  10. "fmt"
  11. "log/slog"
  12. "os"
  13. "path/filepath"
  14. "runtime"
  15. "strings"
  16. "sync"
  17. "unsafe"
  18. )
  19. type handles struct {
  20. cuda *C.cuda_handle_t
  21. rocm *C.rocm_handle_t
  22. }
  23. var gpuMutex sync.Mutex
  24. var gpuHandles *handles = nil
  25. // With our current CUDA compile flags, 5.2 and older will not work properly
  26. const CudaComputeMajorMin = 6
  27. // Possible locations for the nvidia-ml library
  28. var CudaLinuxGlobs = []string{
  29. "/usr/local/cuda/lib64/libnvidia-ml.so*",
  30. "/usr/lib/x86_64-linux-gnu/nvidia/current/libnvidia-ml.so*",
  31. "/usr/lib/x86_64-linux-gnu/libnvidia-ml.so*",
  32. "/usr/lib/wsl/lib/libnvidia-ml.so*",
  33. "/opt/cuda/lib64/libnvidia-ml.so*",
  34. "/usr/lib*/libnvidia-ml.so*",
  35. "/usr/local/lib*/libnvidia-ml.so*",
  36. "/usr/lib/aarch64-linux-gnu/nvidia/current/libnvidia-ml.so*",
  37. "/usr/lib/aarch64-linux-gnu/libnvidia-ml.so*",
  38. }
  39. var CudaWindowsGlobs = []string{
  40. "c:\\Windows\\System32\\nvml.dll",
  41. }
  42. var RocmLinuxGlobs = []string{
  43. "/opt/rocm*/lib*/librocm_smi64.so*",
  44. }
  45. var RocmWindowsGlobs = []string{
  46. "c:\\Windows\\System32\\rocm_smi64.dll",
  47. }
  48. // Note: gpuMutex must already be held
  49. func initGPUHandles() {
  50. // TODO - if the ollama build is CPU only, don't do these checks as they're irrelevant and confusing
  51. var cudaMgmtName string
  52. var cudaMgmtPatterns []string
  53. var rocmMgmtName string
  54. var rocmMgmtPatterns []string
  55. switch runtime.GOOS {
  56. case "windows":
  57. cudaMgmtName = "nvml.dll"
  58. cudaMgmtPatterns = make([]string, len(CudaWindowsGlobs))
  59. copy(cudaMgmtPatterns, CudaWindowsGlobs)
  60. rocmMgmtName = "rocm_smi64.dll"
  61. rocmMgmtPatterns = make([]string, len(RocmWindowsGlobs))
  62. copy(rocmMgmtPatterns, RocmWindowsGlobs)
  63. case "linux":
  64. cudaMgmtName = "libnvidia-ml.so"
  65. cudaMgmtPatterns = make([]string, len(CudaLinuxGlobs))
  66. copy(cudaMgmtPatterns, CudaLinuxGlobs)
  67. rocmMgmtName = "librocm_smi64.so"
  68. rocmMgmtPatterns = make([]string, len(RocmLinuxGlobs))
  69. copy(rocmMgmtPatterns, RocmLinuxGlobs)
  70. default:
  71. return
  72. }
  73. slog.Info("Detecting GPU type")
  74. gpuHandles = &handles{nil, nil}
  75. cudaLibPaths := FindGPULibs(cudaMgmtName, cudaMgmtPatterns)
  76. if len(cudaLibPaths) > 0 {
  77. cuda := LoadCUDAMgmt(cudaLibPaths)
  78. if cuda != nil {
  79. slog.Info("Nvidia GPU detected")
  80. gpuHandles.cuda = cuda
  81. return
  82. }
  83. }
  84. rocmLibPaths := FindGPULibs(rocmMgmtName, rocmMgmtPatterns)
  85. if len(rocmLibPaths) > 0 {
  86. rocm := LoadROCMMgmt(rocmLibPaths)
  87. if rocm != nil {
  88. slog.Info("Radeon GPU detected")
  89. gpuHandles.rocm = rocm
  90. return
  91. }
  92. }
  93. }
  94. func GetGPUInfo() GpuInfo {
  95. // TODO - consider exploring lspci (and equivalent on windows) to check for
  96. // GPUs so we can report warnings if we see Nvidia/AMD but fail to load the libraries
  97. gpuMutex.Lock()
  98. defer gpuMutex.Unlock()
  99. if gpuHandles == nil {
  100. initGPUHandles()
  101. }
  102. var memInfo C.mem_info_t
  103. resp := GpuInfo{}
  104. if gpuHandles.cuda != nil {
  105. C.cuda_check_vram(*gpuHandles.cuda, &memInfo)
  106. if memInfo.err != nil {
  107. slog.Info(fmt.Sprintf("error looking up CUDA GPU memory: %s", C.GoString(memInfo.err)))
  108. C.free(unsafe.Pointer(memInfo.err))
  109. } else {
  110. // Verify minimum compute capability
  111. var cc C.cuda_compute_capability_t
  112. C.cuda_compute_capability(*gpuHandles.cuda, &cc)
  113. if cc.err != nil {
  114. slog.Info(fmt.Sprintf("error looking up CUDA GPU compute capability: %s", C.GoString(cc.err)))
  115. C.free(unsafe.Pointer(cc.err))
  116. } else if cc.major >= CudaComputeMajorMin {
  117. slog.Info(fmt.Sprintf("CUDA Compute Capability detected: %d.%d", cc.major, cc.minor))
  118. resp.Library = "cuda"
  119. } else {
  120. slog.Info(fmt.Sprintf("CUDA GPU is too old. Falling back to CPU mode. Compute Capability detected: %d.%d", cc.major, cc.minor))
  121. }
  122. }
  123. } else if gpuHandles.rocm != nil {
  124. C.rocm_check_vram(*gpuHandles.rocm, &memInfo)
  125. if memInfo.err != nil {
  126. slog.Info(fmt.Sprintf("error looking up ROCm GPU memory: %s", C.GoString(memInfo.err)))
  127. C.free(unsafe.Pointer(memInfo.err))
  128. } else {
  129. resp.Library = "rocm"
  130. var version C.rocm_version_resp_t
  131. C.rocm_get_version(*gpuHandles.rocm, &version)
  132. verString := C.GoString(version.str)
  133. if version.status == 0 {
  134. resp.Variant = "v" + verString
  135. } else {
  136. slog.Info(fmt.Sprintf("failed to look up ROCm version: %s", verString))
  137. }
  138. C.free(unsafe.Pointer(version.str))
  139. }
  140. }
  141. if resp.Library == "" {
  142. C.cpu_check_ram(&memInfo)
  143. resp.Library = "cpu"
  144. resp.Variant = GetCPUVariant()
  145. }
  146. if memInfo.err != nil {
  147. slog.Info(fmt.Sprintf("error looking up CPU memory: %s", C.GoString(memInfo.err)))
  148. C.free(unsafe.Pointer(memInfo.err))
  149. return resp
  150. }
  151. resp.DeviceCount = uint32(memInfo.count)
  152. resp.FreeMemory = uint64(memInfo.free)
  153. resp.TotalMemory = uint64(memInfo.total)
  154. return resp
  155. }
  156. func getCPUMem() (memInfo, error) {
  157. var ret memInfo
  158. var info C.mem_info_t
  159. C.cpu_check_ram(&info)
  160. if info.err != nil {
  161. defer C.free(unsafe.Pointer(info.err))
  162. return ret, fmt.Errorf(C.GoString(info.err))
  163. }
  164. ret.FreeMemory = uint64(info.free)
  165. ret.TotalMemory = uint64(info.total)
  166. return ret, nil
  167. }
  168. func CheckVRAM() (int64, error) {
  169. gpuInfo := GetGPUInfo()
  170. if gpuInfo.FreeMemory > 0 && (gpuInfo.Library == "cuda" || gpuInfo.Library == "rocm") {
  171. // leave 10% or 512MiB of VRAM free per GPU to handle unaccounted for overhead
  172. overhead := gpuInfo.FreeMemory / 10
  173. gpus := uint64(gpuInfo.DeviceCount)
  174. if overhead < gpus*512*1024*1024 {
  175. overhead = gpus * 512 * 1024 * 1024
  176. }
  177. return int64(gpuInfo.FreeMemory - overhead), nil
  178. }
  179. return 0, fmt.Errorf("no GPU detected") // TODO - better handling of CPU based memory determiniation
  180. }
  181. func FindGPULibs(baseLibName string, patterns []string) []string {
  182. // Multiple GPU libraries may exist, and some may not work, so keep trying until we exhaust them
  183. var ldPaths []string
  184. gpuLibPaths := []string{}
  185. slog.Info(fmt.Sprintf("Searching for GPU management library %s", baseLibName))
  186. switch runtime.GOOS {
  187. case "windows":
  188. ldPaths = strings.Split(os.Getenv("PATH"), ";")
  189. case "linux":
  190. ldPaths = strings.Split(os.Getenv("LD_LIBRARY_PATH"), ":")
  191. default:
  192. return gpuLibPaths
  193. }
  194. // Start with whatever we find in the PATH/LD_LIBRARY_PATH
  195. for _, ldPath := range ldPaths {
  196. d, err := filepath.Abs(ldPath)
  197. if err != nil {
  198. continue
  199. }
  200. patterns = append(patterns, filepath.Join(d, baseLibName+"*"))
  201. }
  202. slog.Debug(fmt.Sprintf("gpu management search paths: %v", patterns))
  203. for _, pattern := range patterns {
  204. // Ignore glob discovery errors
  205. matches, _ := filepath.Glob(pattern)
  206. for _, match := range matches {
  207. // Resolve any links so we don't try the same lib multiple times
  208. // and weed out any dups across globs
  209. libPath := match
  210. tmp := match
  211. var err error
  212. for ; err == nil; tmp, err = os.Readlink(libPath) {
  213. if !filepath.IsAbs(tmp) {
  214. tmp = filepath.Join(filepath.Dir(libPath), tmp)
  215. }
  216. libPath = tmp
  217. }
  218. new := true
  219. for _, cmp := range gpuLibPaths {
  220. if cmp == libPath {
  221. new = false
  222. break
  223. }
  224. }
  225. if new {
  226. gpuLibPaths = append(gpuLibPaths, libPath)
  227. }
  228. }
  229. }
  230. slog.Info(fmt.Sprintf("Discovered GPU libraries: %v", gpuLibPaths))
  231. return gpuLibPaths
  232. }
  233. func LoadCUDAMgmt(cudaLibPaths []string) *C.cuda_handle_t {
  234. var resp C.cuda_init_resp_t
  235. for _, libPath := range cudaLibPaths {
  236. lib := C.CString(libPath)
  237. defer C.free(unsafe.Pointer(lib))
  238. C.cuda_init(lib, &resp)
  239. if resp.err != nil {
  240. slog.Info(fmt.Sprintf("Unable to load CUDA management library %s: %s", libPath, C.GoString(resp.err)))
  241. C.free(unsafe.Pointer(resp.err))
  242. } else {
  243. return &resp.ch
  244. }
  245. }
  246. return nil
  247. }
  248. func LoadROCMMgmt(rocmLibPaths []string) *C.rocm_handle_t {
  249. var resp C.rocm_init_resp_t
  250. for _, libPath := range rocmLibPaths {
  251. lib := C.CString(libPath)
  252. defer C.free(unsafe.Pointer(lib))
  253. C.rocm_init(lib, &resp)
  254. if resp.err != nil {
  255. slog.Info(fmt.Sprintf("Unable to load ROCm management library %s: %s", libPath, C.GoString(resp.err)))
  256. C.free(unsafe.Pointer(resp.err))
  257. } else {
  258. return &resp.rh
  259. }
  260. }
  261. return nil
  262. }