gpu.go 11 KB

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