gpu.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. "github.com/ollama/ollama/format"
  19. )
  20. type handles struct {
  21. deviceCount int
  22. cudart *C.cudart_handle_t
  23. nvcuda *C.nvcuda_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. var RocmComputeMin = 9
  33. // TODO find a better way to detect iGPU instead of minimum memory
  34. const IGPUMemLimit = 1 * format.GibiByte // 512G is what they typically report, so anything less than 1G must be iGPU
  35. var CudartLinuxGlobs = []string{
  36. "/usr/local/cuda/lib64/libcudart.so*",
  37. "/usr/lib/x86_64-linux-gnu/nvidia/current/libcudart.so*",
  38. "/usr/lib/x86_64-linux-gnu/libcudart.so*",
  39. "/usr/lib/wsl/lib/libcudart.so*",
  40. "/usr/lib/wsl/drivers/*/libcudart.so*",
  41. "/opt/cuda/lib64/libcudart.so*",
  42. "/usr/local/cuda*/targets/aarch64-linux/lib/libcudart.so*",
  43. "/usr/lib/aarch64-linux-gnu/nvidia/current/libcudart.so*",
  44. "/usr/lib/aarch64-linux-gnu/libcudart.so*",
  45. "/usr/local/cuda/lib*/libcudart.so*",
  46. "/usr/lib*/libcudart.so*",
  47. "/usr/local/lib*/libcudart.so*",
  48. }
  49. var CudartWindowsGlobs = []string{
  50. "c:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v*\\bin\\cudart64_*.dll",
  51. }
  52. var NvcudaLinuxGlobs = []string{
  53. "/usr/local/cuda*/targets/*/lib/libcuda.so*",
  54. "/usr/lib/*-linux-gnu/nvidia/current/libcuda.so*",
  55. "/usr/lib/*-linux-gnu/libcuda.so*",
  56. "/usr/lib/wsl/lib/libcuda.so*",
  57. "/usr/lib/wsl/drivers/*/libcuda.so*",
  58. "/opt/cuda/lib*/libcuda.so*",
  59. "/usr/local/cuda/lib*/libcuda.so*",
  60. "/usr/lib*/libcuda.so*",
  61. "/usr/local/lib*/libcuda.so*",
  62. }
  63. var NvcudaWindowsGlobs = []string{
  64. "c:\\windows\\system*\\nvcuda.dll",
  65. }
  66. // Jetson devices have JETSON_JETPACK="x.y.z" factory set to the Jetpack version installed.
  67. // Included to drive logic for reducing Ollama-allocated overhead on L4T/Jetson devices.
  68. var CudaTegra string = os.Getenv("JETSON_JETPACK")
  69. // Note: gpuMutex must already be held
  70. func initGPUHandles() *handles {
  71. // TODO - if the ollama build is CPU only, don't do these checks as they're irrelevant and confusing
  72. gpuHandles := &handles{}
  73. var cudartMgmtName string
  74. var cudartMgmtPatterns []string
  75. var nvcudaMgmtName string
  76. var nvcudaMgmtPatterns []string
  77. tmpDir, _ := PayloadsDir()
  78. switch runtime.GOOS {
  79. case "windows":
  80. cudartMgmtName = "cudart64_*.dll"
  81. localAppData := os.Getenv("LOCALAPPDATA")
  82. cudartMgmtPatterns = []string{filepath.Join(localAppData, "Programs", "Ollama", cudartMgmtName)}
  83. cudartMgmtPatterns = append(cudartMgmtPatterns, CudartWindowsGlobs...)
  84. // Aligned with driver, we can't carry as payloads
  85. nvcudaMgmtName = "nvcuda.dll"
  86. nvcudaMgmtPatterns = NvcudaWindowsGlobs
  87. case "linux":
  88. cudartMgmtName = "libcudart.so*"
  89. if tmpDir != "" {
  90. // TODO - add "payloads" for subprocess
  91. cudartMgmtPatterns = []string{filepath.Join(tmpDir, "cuda*", cudartMgmtName)}
  92. }
  93. cudartMgmtPatterns = append(cudartMgmtPatterns, CudartLinuxGlobs...)
  94. // Aligned with driver, we can't carry as payloads
  95. nvcudaMgmtName = "libcuda.so*"
  96. nvcudaMgmtPatterns = NvcudaLinuxGlobs
  97. default:
  98. return gpuHandles
  99. }
  100. slog.Info("Detecting GPUs")
  101. nvcudaLibPaths := FindGPULibs(nvcudaMgmtName, nvcudaMgmtPatterns)
  102. if len(nvcudaLibPaths) > 0 {
  103. deviceCount, nvcuda, libPath := LoadNVCUDAMgmt(nvcudaLibPaths)
  104. if nvcuda != nil {
  105. slog.Info("detected GPUs", "count", deviceCount, "library", libPath)
  106. gpuHandles.nvcuda = nvcuda
  107. gpuHandles.deviceCount = deviceCount
  108. return gpuHandles
  109. }
  110. }
  111. cudartLibPaths := FindGPULibs(cudartMgmtName, cudartMgmtPatterns)
  112. if len(cudartLibPaths) > 0 {
  113. deviceCount, cudart, libPath := LoadCUDARTMgmt(cudartLibPaths)
  114. if cudart != nil {
  115. slog.Info("detected GPUs", "library", libPath, "count", deviceCount)
  116. gpuHandles.cudart = cudart
  117. gpuHandles.deviceCount = deviceCount
  118. return gpuHandles
  119. }
  120. }
  121. return gpuHandles
  122. }
  123. func GetGPUInfo() GpuInfoList {
  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.cudart != nil {
  131. C.cudart_release(*gpuHandles.cudart)
  132. }
  133. if gpuHandles.nvcuda != nil {
  134. C.nvcuda_release(*gpuHandles.nvcuda)
  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. // NVIDIA first
  145. for i := 0; i < gpuHandles.deviceCount; i++ {
  146. // TODO once we support CPU compilation variants of GPU libraries refine this...
  147. if cpuVariant == "" && runtime.GOARCH == "amd64" {
  148. continue
  149. }
  150. gpuInfo := GpuInfo{
  151. Library: "cuda",
  152. }
  153. if gpuHandles.cudart != nil {
  154. C.cudart_check_vram(*gpuHandles.cudart, C.int(i), &memInfo)
  155. } else {
  156. C.nvcuda_check_vram(*gpuHandles.nvcuda, C.int(i), &memInfo)
  157. }
  158. if memInfo.err != nil {
  159. slog.Info("error looking up nvidia GPU memory", "error", C.GoString(memInfo.err))
  160. C.free(unsafe.Pointer(memInfo.err))
  161. continue
  162. }
  163. if memInfo.major < CudaComputeMin[0] || (memInfo.major == CudaComputeMin[0] && memInfo.minor < CudaComputeMin[1]) {
  164. slog.Info(fmt.Sprintf("[%d] CUDA GPU is too old. Compute Capability detected: %d.%d", i, memInfo.major, memInfo.minor))
  165. continue
  166. }
  167. gpuInfo.TotalMemory = uint64(memInfo.total)
  168. gpuInfo.FreeMemory = uint64(memInfo.free)
  169. gpuInfo.ID = C.GoString(&memInfo.gpu_id[0])
  170. gpuInfo.Major = int(memInfo.major)
  171. gpuInfo.Minor = int(memInfo.minor)
  172. gpuInfo.MinimumMemory = cudaMinimumMemory
  173. // TODO potentially sort on our own algorithm instead of what the underlying GPU library does...
  174. resp = append(resp, gpuInfo)
  175. }
  176. // Then AMD
  177. resp = append(resp, AMDGetGPUInfo()...)
  178. if len(resp) == 0 {
  179. C.cpu_check_ram(&memInfo)
  180. if memInfo.err != nil {
  181. slog.Info("error looking up CPU memory", "error", C.GoString(memInfo.err))
  182. C.free(unsafe.Pointer(memInfo.err))
  183. return resp
  184. }
  185. gpuInfo := GpuInfo{
  186. Library: "cpu",
  187. Variant: cpuVariant,
  188. }
  189. gpuInfo.TotalMemory = uint64(memInfo.total)
  190. gpuInfo.FreeMemory = uint64(memInfo.free)
  191. gpuInfo.ID = C.GoString(&memInfo.gpu_id[0])
  192. resp = append(resp, gpuInfo)
  193. }
  194. return resp
  195. }
  196. func GetCPUMem() (memInfo, error) {
  197. var ret memInfo
  198. var info C.mem_info_t
  199. C.cpu_check_ram(&info)
  200. if info.err != nil {
  201. defer C.free(unsafe.Pointer(info.err))
  202. return ret, fmt.Errorf(C.GoString(info.err))
  203. }
  204. ret.FreeMemory = uint64(info.free)
  205. ret.TotalMemory = uint64(info.total)
  206. return ret, nil
  207. }
  208. func FindGPULibs(baseLibName string, defaultPatterns []string) []string {
  209. // Multiple GPU libraries may exist, and some may not work, so keep trying until we exhaust them
  210. var ldPaths []string
  211. var patterns []string
  212. gpuLibPaths := []string{}
  213. slog.Debug("Searching for GPU library", "name", baseLibName)
  214. switch runtime.GOOS {
  215. case "windows":
  216. ldPaths = strings.Split(os.Getenv("PATH"), ";")
  217. case "linux":
  218. ldPaths = strings.Split(os.Getenv("LD_LIBRARY_PATH"), ":")
  219. default:
  220. return gpuLibPaths
  221. }
  222. // Start with whatever we find in the PATH/LD_LIBRARY_PATH
  223. for _, ldPath := range ldPaths {
  224. d, err := filepath.Abs(ldPath)
  225. if err != nil {
  226. continue
  227. }
  228. patterns = append(patterns, filepath.Join(d, baseLibName+"*"))
  229. }
  230. patterns = append(patterns, defaultPatterns...)
  231. slog.Debug("gpu library search", "globs", patterns)
  232. for _, pattern := range patterns {
  233. // Ignore glob discovery errors
  234. matches, _ := filepath.Glob(pattern)
  235. for _, match := range matches {
  236. // Resolve any links so we don't try the same lib multiple times
  237. // and weed out any dups across globs
  238. libPath := match
  239. tmp := match
  240. var err error
  241. for ; err == nil; tmp, err = os.Readlink(libPath) {
  242. if !filepath.IsAbs(tmp) {
  243. tmp = filepath.Join(filepath.Dir(libPath), tmp)
  244. }
  245. libPath = tmp
  246. }
  247. new := true
  248. for _, cmp := range gpuLibPaths {
  249. if cmp == libPath {
  250. new = false
  251. break
  252. }
  253. }
  254. if new {
  255. gpuLibPaths = append(gpuLibPaths, libPath)
  256. }
  257. }
  258. }
  259. slog.Debug("discovered GPU libraries", "paths", gpuLibPaths)
  260. return gpuLibPaths
  261. }
  262. func LoadCUDARTMgmt(cudartLibPaths []string) (int, *C.cudart_handle_t, string) {
  263. var resp C.cudart_init_resp_t
  264. resp.ch.verbose = getVerboseState()
  265. for _, libPath := range cudartLibPaths {
  266. lib := C.CString(libPath)
  267. defer C.free(unsafe.Pointer(lib))
  268. C.cudart_init(lib, &resp)
  269. if resp.err != nil {
  270. slog.Debug("Unable to load cudart", "library", libPath, "error", C.GoString(resp.err))
  271. C.free(unsafe.Pointer(resp.err))
  272. } else {
  273. return int(resp.num_devices), &resp.ch, libPath
  274. }
  275. }
  276. return 0, nil, ""
  277. }
  278. func LoadNVCUDAMgmt(nvcudaLibPaths []string) (int, *C.nvcuda_handle_t, string) {
  279. var resp C.nvcuda_init_resp_t
  280. resp.ch.verbose = getVerboseState()
  281. for _, libPath := range nvcudaLibPaths {
  282. lib := C.CString(libPath)
  283. defer C.free(unsafe.Pointer(lib))
  284. C.nvcuda_init(lib, &resp)
  285. if resp.err != nil {
  286. slog.Debug("Unable to load nvcuda", "library", libPath, "error", C.GoString(resp.err))
  287. C.free(unsafe.Pointer(resp.err))
  288. } else {
  289. return int(resp.num_devices), &resp.ch, libPath
  290. }
  291. }
  292. return 0, nil, ""
  293. }
  294. func getVerboseState() C.uint16_t {
  295. if debug := os.Getenv("OLLAMA_DEBUG"); debug != "" {
  296. return C.uint16_t(1)
  297. }
  298. return C.uint16_t(0)
  299. }
  300. // Given the list of GPUs this instantiation is targeted for,
  301. // figure out the visible devices environment variable
  302. //
  303. // If different libraries are detected, the first one is what we use
  304. func (l GpuInfoList) GetVisibleDevicesEnv() (string, string) {
  305. if len(l) == 0 {
  306. return "", ""
  307. }
  308. switch l[0].Library {
  309. case "cuda":
  310. return cudaGetVisibleDevicesEnv(l)
  311. case "rocm":
  312. return rocmGetVisibleDevicesEnv(l)
  313. default:
  314. slog.Debug("no filter required for library " + l[0].Library)
  315. return "", ""
  316. }
  317. }