gpu.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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"
  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. log.Printf("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. log.Printf("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. log.Printf("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. log.Printf("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. log.Printf("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. log.Printf("CUDA Compute Capability detected: %d.%d", cc.major, cc.minor)
  118. resp.Library = "cuda"
  119. } else {
  120. log.Printf("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. log.Printf("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. }
  131. }
  132. if resp.Library == "" {
  133. C.cpu_check_ram(&memInfo)
  134. // In the future we may offer multiple CPU variants to tune CPU features
  135. if runtime.GOOS == "windows" {
  136. resp.Library = "cpu"
  137. } else {
  138. resp.Library = "default"
  139. }
  140. }
  141. if memInfo.err != nil {
  142. log.Printf("error looking up CPU memory: %s", C.GoString(memInfo.err))
  143. C.free(unsafe.Pointer(memInfo.err))
  144. return resp
  145. }
  146. resp.DeviceCount = uint32(memInfo.count)
  147. resp.FreeMemory = uint64(memInfo.free)
  148. resp.TotalMemory = uint64(memInfo.total)
  149. return resp
  150. }
  151. func getCPUMem() (memInfo, error) {
  152. var ret memInfo
  153. var info C.mem_info_t
  154. C.cpu_check_ram(&info)
  155. if info.err != nil {
  156. defer C.free(unsafe.Pointer(info.err))
  157. return ret, fmt.Errorf(C.GoString(info.err))
  158. }
  159. ret.FreeMemory = uint64(info.free)
  160. ret.TotalMemory = uint64(info.total)
  161. return ret, nil
  162. }
  163. func CheckVRAM() (int64, error) {
  164. gpuInfo := GetGPUInfo()
  165. if gpuInfo.FreeMemory > 0 && (gpuInfo.Library == "cuda" || gpuInfo.Library == "rocm") {
  166. // leave 10% or 512MiB of VRAM free per GPU to handle unaccounted for overhead
  167. overhead := gpuInfo.FreeMemory / 10
  168. gpus := uint64(gpuInfo.DeviceCount)
  169. if overhead < gpus*512*1024*1024 {
  170. overhead = gpus * 512 * 1024 * 1024
  171. }
  172. return int64(gpuInfo.FreeMemory - overhead), nil
  173. }
  174. return 0, fmt.Errorf("no GPU detected") // TODO - better handling of CPU based memory determiniation
  175. }
  176. func FindGPULibs(baseLibName string, patterns []string) []string {
  177. // Multiple GPU libraries may exist, and some may not work, so keep trying until we exhaust them
  178. var ldPaths []string
  179. gpuLibPaths := []string{}
  180. log.Printf("Searching for GPU management library %s", baseLibName)
  181. switch runtime.GOOS {
  182. case "windows":
  183. ldPaths = strings.Split(os.Getenv("PATH"), ";")
  184. case "linux":
  185. ldPaths = strings.Split(os.Getenv("LD_LIBRARY_PATH"), ":")
  186. default:
  187. return gpuLibPaths
  188. }
  189. // Start with whatever we find in the PATH/LD_LIBRARY_PATH
  190. for _, ldPath := range ldPaths {
  191. d, err := filepath.Abs(ldPath)
  192. if err != nil {
  193. continue
  194. }
  195. patterns = append(patterns, filepath.Join(d, baseLibName+"*"))
  196. }
  197. for _, pattern := range patterns {
  198. // Ignore glob discovery errors
  199. matches, _ := filepath.Glob(pattern)
  200. for _, match := range matches {
  201. // Resolve any links so we don't try the same lib multiple times
  202. // and weed out any dups across globs
  203. libPath := match
  204. tmp := match
  205. var err error
  206. for ; err == nil; tmp, err = os.Readlink(libPath) {
  207. if !filepath.IsAbs(tmp) {
  208. tmp = filepath.Join(filepath.Dir(libPath), tmp)
  209. }
  210. libPath = tmp
  211. }
  212. new := true
  213. for _, cmp := range gpuLibPaths {
  214. if cmp == libPath {
  215. new = false
  216. break
  217. }
  218. }
  219. if new {
  220. gpuLibPaths = append(gpuLibPaths, libPath)
  221. }
  222. }
  223. }
  224. log.Printf("Discovered GPU libraries: %v", gpuLibPaths)
  225. return gpuLibPaths
  226. }
  227. func LoadCUDAMgmt(cudaLibPaths []string) *C.cuda_handle_t {
  228. var resp C.cuda_init_resp_t
  229. for _, libPath := range cudaLibPaths {
  230. lib := C.CString(libPath)
  231. defer C.free(unsafe.Pointer(lib))
  232. C.cuda_init(lib, &resp)
  233. if resp.err != nil {
  234. log.Printf("Unable to load CUDA management library %s: %s", libPath, C.GoString(resp.err))
  235. C.free(unsafe.Pointer(resp.err))
  236. } else {
  237. return &resp.ch
  238. }
  239. }
  240. return nil
  241. }
  242. func LoadROCMMgmt(rocmLibPaths []string) *C.rocm_handle_t {
  243. var resp C.rocm_init_resp_t
  244. for _, libPath := range rocmLibPaths {
  245. lib := C.CString(libPath)
  246. defer C.free(unsafe.Pointer(lib))
  247. C.rocm_init(lib, &resp)
  248. if resp.err != nil {
  249. log.Printf("Unable to load ROCm management library %s: %s", libPath, C.GoString(resp.err))
  250. C.free(unsafe.Pointer(resp.err))
  251. } else {
  252. return &resp.rh
  253. }
  254. }
  255. return nil
  256. }