gpu.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. "strconv"
  16. "strings"
  17. "sync"
  18. "unsafe"
  19. "github.com/ollama/ollama/format"
  20. )
  21. type handles struct {
  22. nvml *C.nvml_handle_t
  23. cudart *C.cudart_handle_t
  24. }
  25. const (
  26. cudaMinimumMemory = 377 * format.MebiByte
  27. rocmMinimumMemory = 377 * format.MebiByte
  28. )
  29. var gpuMutex sync.Mutex
  30. var gpuHandles *handles = nil
  31. // With our current CUDA compile flags, older than 5.0 will not work properly
  32. var CudaComputeMin = [2]C.int{5, 0}
  33. // Possible locations for the nvidia-ml library
  34. var NvmlLinuxGlobs = []string{
  35. "/usr/local/cuda/lib64/libnvidia-ml.so*",
  36. "/usr/lib/x86_64-linux-gnu/nvidia/current/libnvidia-ml.so*",
  37. "/usr/lib/x86_64-linux-gnu/libnvidia-ml.so*",
  38. "/usr/lib/wsl/lib/libnvidia-ml.so*",
  39. "/usr/lib/wsl/drivers/*/libnvidia-ml.so*",
  40. "/opt/cuda/lib64/libnvidia-ml.so*",
  41. "/usr/lib*/libnvidia-ml.so*",
  42. "/usr/lib/aarch64-linux-gnu/nvidia/current/libnvidia-ml.so*",
  43. "/usr/lib/aarch64-linux-gnu/libnvidia-ml.so*",
  44. "/usr/local/lib*/libnvidia-ml.so*",
  45. // TODO: are these stubs ever valid?
  46. "/opt/cuda/targets/x86_64-linux/lib/stubs/libnvidia-ml.so*",
  47. }
  48. var NvmlWindowsGlobs = []string{
  49. "c:\\Windows\\System32\\nvml.dll",
  50. }
  51. var CudartLinuxGlobs = []string{
  52. "/usr/local/cuda/lib64/libcudart.so*",
  53. "/usr/lib/x86_64-linux-gnu/nvidia/current/libcudart.so*",
  54. "/usr/lib/x86_64-linux-gnu/libcudart.so*",
  55. "/usr/lib/wsl/lib/libcudart.so*",
  56. "/usr/lib/wsl/drivers/*/libcudart.so*",
  57. "/opt/cuda/lib64/libcudart.so*",
  58. "/usr/local/cuda*/targets/aarch64-linux/lib/libcudart.so*",
  59. "/usr/lib/aarch64-linux-gnu/nvidia/current/libcudart.so*",
  60. "/usr/lib/aarch64-linux-gnu/libcudart.so*",
  61. "/usr/local/cuda/lib*/libcudart.so*",
  62. "/usr/lib*/libcudart.so*",
  63. "/usr/local/lib*/libcudart.so*",
  64. }
  65. var CudartWindowsGlobs = []string{
  66. "c:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v*\\bin\\cudart64_*.dll",
  67. }
  68. // Jetson devices have JETSON_JETPACK="x.y.z" factory set to the Jetpack version installed.
  69. // Included to drive logic for reducing Ollama-allocated overhead on L4T/Jetson devices.
  70. var CudaTegra string = os.Getenv("JETSON_JETPACK")
  71. // Note: gpuMutex must already be held
  72. func initGPUHandles() {
  73. // TODO - if the ollama build is CPU only, don't do these checks as they're irrelevant and confusing
  74. gpuHandles = &handles{nil, nil}
  75. var nvmlMgmtName string
  76. var nvmlMgmtPatterns []string
  77. var cudartMgmtName string
  78. var cudartMgmtPatterns []string
  79. tmpDir, _ := PayloadsDir()
  80. switch runtime.GOOS {
  81. case "windows":
  82. nvmlMgmtName = "nvml.dll"
  83. nvmlMgmtPatterns = make([]string, len(NvmlWindowsGlobs))
  84. copy(nvmlMgmtPatterns, NvmlWindowsGlobs)
  85. cudartMgmtName = "cudart64_*.dll"
  86. localAppData := os.Getenv("LOCALAPPDATA")
  87. cudartMgmtPatterns = []string{filepath.Join(localAppData, "Programs", "Ollama", cudartMgmtName)}
  88. cudartMgmtPatterns = append(cudartMgmtPatterns, CudartWindowsGlobs...)
  89. case "linux":
  90. nvmlMgmtName = "libnvidia-ml.so"
  91. nvmlMgmtPatterns = make([]string, len(NvmlLinuxGlobs))
  92. copy(nvmlMgmtPatterns, NvmlLinuxGlobs)
  93. cudartMgmtName = "libcudart.so*"
  94. if tmpDir != "" {
  95. // TODO - add "payloads" for subprocess
  96. cudartMgmtPatterns = []string{filepath.Join(tmpDir, "cuda*", cudartMgmtName)}
  97. }
  98. cudartMgmtPatterns = append(cudartMgmtPatterns, CudartLinuxGlobs...)
  99. default:
  100. return
  101. }
  102. slog.Info("Detecting GPU type")
  103. cudartLibPaths := FindGPULibs(cudartMgmtName, cudartMgmtPatterns)
  104. if len(cudartLibPaths) > 0 {
  105. cudart := LoadCUDARTMgmt(cudartLibPaths)
  106. if cudart != nil {
  107. slog.Info("Nvidia GPU detected via cudart")
  108. gpuHandles.cudart = cudart
  109. return
  110. }
  111. }
  112. // TODO once we build confidence, remove this and the gpu_info_nvml.[ch] files
  113. nvmlLibPaths := FindGPULibs(nvmlMgmtName, nvmlMgmtPatterns)
  114. if len(nvmlLibPaths) > 0 {
  115. nvml := LoadNVMLMgmt(nvmlLibPaths)
  116. if nvml != nil {
  117. slog.Info("Nvidia GPU detected via nvidia-ml")
  118. gpuHandles.nvml = nvml
  119. return
  120. }
  121. }
  122. }
  123. func GetGPUInfo() GpuInfo {
  124. // TODO - consider exploring lspci (and equivalent on windows) to check for
  125. // GPUs so we can report warnings if we see Nvidia/AMD but fail to load the libraries
  126. gpuMutex.Lock()
  127. defer gpuMutex.Unlock()
  128. if gpuHandles == nil {
  129. initGPUHandles()
  130. }
  131. // All our GPU builds on x86 have AVX enabled, so fallback to CPU if we don't detect at least AVX
  132. cpuVariant := GetCPUVariant()
  133. if cpuVariant == "" && runtime.GOARCH == "amd64" {
  134. slog.Warn("CPU does not have AVX or AVX2, disabling GPU support.")
  135. }
  136. var memInfo C.mem_info_t
  137. resp := GpuInfo{}
  138. if gpuHandles.nvml != nil && (cpuVariant != "" || runtime.GOARCH != "amd64") {
  139. C.nvml_check_vram(*gpuHandles.nvml, &memInfo)
  140. if memInfo.err != nil {
  141. slog.Info(fmt.Sprintf("[nvidia-ml] error looking up NVML GPU memory: %s", C.GoString(memInfo.err)))
  142. C.free(unsafe.Pointer(memInfo.err))
  143. } else if memInfo.count > 0 {
  144. // Verify minimum compute capability
  145. var cc C.nvml_compute_capability_t
  146. C.nvml_compute_capability(*gpuHandles.nvml, &cc)
  147. if cc.err != nil {
  148. slog.Info(fmt.Sprintf("[nvidia-ml] error looking up NVML GPU compute capability: %s", C.GoString(cc.err)))
  149. C.free(unsafe.Pointer(cc.err))
  150. } else if cc.major > CudaComputeMin[0] || (cc.major == CudaComputeMin[0] && cc.minor >= CudaComputeMin[1]) {
  151. slog.Info(fmt.Sprintf("[nvidia-ml] NVML CUDA Compute Capability detected: %d.%d", cc.major, cc.minor))
  152. resp.Library = "cuda"
  153. resp.MinimumMemory = cudaMinimumMemory
  154. } else {
  155. slog.Info(fmt.Sprintf("[nvidia-ml] CUDA GPU is too old. Falling back to CPU mode. Compute Capability detected: %d.%d", cc.major, cc.minor))
  156. }
  157. }
  158. } else if gpuHandles.cudart != nil && (cpuVariant != "" || runtime.GOARCH != "amd64") {
  159. C.cudart_check_vram(*gpuHandles.cudart, &memInfo)
  160. if memInfo.err != nil {
  161. slog.Info(fmt.Sprintf("[cudart] error looking up CUDART GPU memory: %s", C.GoString(memInfo.err)))
  162. C.free(unsafe.Pointer(memInfo.err))
  163. } else if memInfo.count > 0 {
  164. // Verify minimum compute capability
  165. var cc C.cudart_compute_capability_t
  166. C.cudart_compute_capability(*gpuHandles.cudart, &cc)
  167. if cc.err != nil {
  168. slog.Info(fmt.Sprintf("[cudart] error looking up CUDA compute capability: %s", C.GoString(cc.err)))
  169. C.free(unsafe.Pointer(cc.err))
  170. } else if cc.major > CudaComputeMin[0] || (cc.major == CudaComputeMin[0] && cc.minor >= CudaComputeMin[1]) {
  171. slog.Info(fmt.Sprintf("[cudart] CUDART CUDA Compute Capability detected: %d.%d", cc.major, cc.minor))
  172. resp.Library = "cuda"
  173. resp.MinimumMemory = cudaMinimumMemory
  174. } else {
  175. slog.Info(fmt.Sprintf("[cudart] CUDA GPU is too old. Falling back to CPU mode. Compute Capability detected: %d.%d", cc.major, cc.minor))
  176. }
  177. }
  178. } else {
  179. AMDGetGPUInfo(&resp)
  180. if resp.Library != "" {
  181. resp.MinimumMemory = rocmMinimumMemory
  182. return resp
  183. }
  184. }
  185. if resp.Library == "" {
  186. C.cpu_check_ram(&memInfo)
  187. resp.Library = "cpu"
  188. resp.Variant = cpuVariant
  189. }
  190. if memInfo.err != nil {
  191. slog.Info(fmt.Sprintf("error looking up CPU memory: %s", C.GoString(memInfo.err)))
  192. C.free(unsafe.Pointer(memInfo.err))
  193. return resp
  194. }
  195. resp.DeviceCount = uint32(memInfo.count)
  196. resp.FreeMemory = uint64(memInfo.free)
  197. resp.TotalMemory = uint64(memInfo.total)
  198. return resp
  199. }
  200. func getCPUMem() (memInfo, error) {
  201. var ret memInfo
  202. var info C.mem_info_t
  203. C.cpu_check_ram(&info)
  204. if info.err != nil {
  205. defer C.free(unsafe.Pointer(info.err))
  206. return ret, fmt.Errorf(C.GoString(info.err))
  207. }
  208. ret.FreeMemory = uint64(info.free)
  209. ret.TotalMemory = uint64(info.total)
  210. return ret, nil
  211. }
  212. func CheckVRAM() (int64, error) {
  213. userLimit := os.Getenv("OLLAMA_MAX_VRAM")
  214. if userLimit != "" {
  215. avail, err := strconv.ParseInt(userLimit, 10, 64)
  216. if err != nil {
  217. return 0, fmt.Errorf("Invalid OLLAMA_MAX_VRAM setting %s: %s", userLimit, err)
  218. }
  219. slog.Info(fmt.Sprintf("user override OLLAMA_MAX_VRAM=%d", avail))
  220. return avail, nil
  221. }
  222. gpuInfo := GetGPUInfo()
  223. if gpuInfo.FreeMemory > 0 && (gpuInfo.Library == "cuda" || gpuInfo.Library == "rocm") {
  224. return int64(gpuInfo.FreeMemory), nil
  225. }
  226. return 0, fmt.Errorf("no GPU detected") // TODO - better handling of CPU based memory determiniation
  227. }
  228. func FindGPULibs(baseLibName string, patterns []string) []string {
  229. // Multiple GPU libraries may exist, and some may not work, so keep trying until we exhaust them
  230. var ldPaths []string
  231. gpuLibPaths := []string{}
  232. slog.Info(fmt.Sprintf("Searching for GPU management library %s", baseLibName))
  233. switch runtime.GOOS {
  234. case "windows":
  235. ldPaths = strings.Split(os.Getenv("PATH"), ";")
  236. case "linux":
  237. ldPaths = strings.Split(os.Getenv("LD_LIBRARY_PATH"), ":")
  238. default:
  239. return gpuLibPaths
  240. }
  241. // Start with whatever we find in the PATH/LD_LIBRARY_PATH
  242. for _, ldPath := range ldPaths {
  243. d, err := filepath.Abs(ldPath)
  244. if err != nil {
  245. continue
  246. }
  247. patterns = append(patterns, filepath.Join(d, baseLibName+"*"))
  248. }
  249. slog.Debug(fmt.Sprintf("gpu management search paths: %v", patterns))
  250. for _, pattern := range patterns {
  251. // Ignore glob discovery errors
  252. matches, _ := filepath.Glob(pattern)
  253. for _, match := range matches {
  254. // Resolve any links so we don't try the same lib multiple times
  255. // and weed out any dups across globs
  256. libPath := match
  257. tmp := match
  258. var err error
  259. for ; err == nil; tmp, err = os.Readlink(libPath) {
  260. if !filepath.IsAbs(tmp) {
  261. tmp = filepath.Join(filepath.Dir(libPath), tmp)
  262. }
  263. libPath = tmp
  264. }
  265. new := true
  266. for _, cmp := range gpuLibPaths {
  267. if cmp == libPath {
  268. new = false
  269. break
  270. }
  271. }
  272. if new {
  273. gpuLibPaths = append(gpuLibPaths, libPath)
  274. }
  275. }
  276. }
  277. slog.Info(fmt.Sprintf("Discovered GPU libraries: %v", gpuLibPaths))
  278. return gpuLibPaths
  279. }
  280. func LoadNVMLMgmt(nvmlLibPaths []string) *C.nvml_handle_t {
  281. var resp C.nvml_init_resp_t
  282. resp.ch.verbose = getVerboseState()
  283. for _, libPath := range nvmlLibPaths {
  284. lib := C.CString(libPath)
  285. defer C.free(unsafe.Pointer(lib))
  286. C.nvml_init(lib, &resp)
  287. if resp.err != nil {
  288. slog.Info(fmt.Sprintf("Unable to load NVML management library %s: %s", libPath, C.GoString(resp.err)))
  289. C.free(unsafe.Pointer(resp.err))
  290. } else {
  291. return &resp.ch
  292. }
  293. }
  294. return nil
  295. }
  296. func LoadCUDARTMgmt(cudartLibPaths []string) *C.cudart_handle_t {
  297. var resp C.cudart_init_resp_t
  298. resp.ch.verbose = getVerboseState()
  299. for _, libPath := range cudartLibPaths {
  300. lib := C.CString(libPath)
  301. defer C.free(unsafe.Pointer(lib))
  302. C.cudart_init(lib, &resp)
  303. if resp.err != nil {
  304. slog.Info(fmt.Sprintf("Unable to load cudart CUDA management library %s: %s", libPath, C.GoString(resp.err)))
  305. C.free(unsafe.Pointer(resp.err))
  306. } else {
  307. return &resp.ch
  308. }
  309. }
  310. return nil
  311. }
  312. func getVerboseState() C.uint16_t {
  313. if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
  314. return C.uint16_t(1)
  315. }
  316. return C.uint16_t(0)
  317. }