gpu.go 8.2 KB

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