gpu.go 10 KB

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