gpu.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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.Debug("Detecting GPUs")
  102. nvcudaLibPaths := FindGPULibs(nvcudaMgmtName, nvcudaMgmtPatterns)
  103. if len(nvcudaLibPaths) > 0 {
  104. deviceCount, nvcuda, libPath := LoadNVCUDAMgmt(nvcudaLibPaths)
  105. if nvcuda != nil {
  106. slog.Debug("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.Debug("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. // On windows we bundle the nvidia library one level above the runner dir
  144. depPath := ""
  145. if runtime.GOOS == "windows" && envconfig.RunnersDir != "" {
  146. depPath = filepath.Dir(envconfig.RunnersDir)
  147. }
  148. var memInfo C.mem_info_t
  149. resp := []GpuInfo{}
  150. // NVIDIA first
  151. for i := 0; i < gpuHandles.deviceCount; i++ {
  152. // TODO once we support CPU compilation variants of GPU libraries refine this...
  153. if cpuVariant == "" && runtime.GOARCH == "amd64" {
  154. continue
  155. }
  156. gpuInfo := GpuInfo{
  157. Library: "cuda",
  158. }
  159. var driverMajor int
  160. var driverMinor int
  161. if gpuHandles.cudart != nil {
  162. C.cudart_check_vram(*gpuHandles.cudart, C.int(i), &memInfo)
  163. } else {
  164. C.nvcuda_check_vram(*gpuHandles.nvcuda, C.int(i), &memInfo)
  165. driverMajor = int(gpuHandles.nvcuda.driver_major)
  166. driverMinor = int(gpuHandles.nvcuda.driver_minor)
  167. }
  168. if memInfo.err != nil {
  169. slog.Info("error looking up nvidia GPU memory", "error", C.GoString(memInfo.err))
  170. C.free(unsafe.Pointer(memInfo.err))
  171. continue
  172. }
  173. if memInfo.major < CudaComputeMin[0] || (memInfo.major == CudaComputeMin[0] && memInfo.minor < CudaComputeMin[1]) {
  174. slog.Info(fmt.Sprintf("[%d] CUDA GPU is too old. Compute Capability detected: %d.%d", i, memInfo.major, memInfo.minor))
  175. continue
  176. }
  177. gpuInfo.TotalMemory = uint64(memInfo.total)
  178. gpuInfo.FreeMemory = uint64(memInfo.free)
  179. gpuInfo.ID = C.GoString(&memInfo.gpu_id[0])
  180. gpuInfo.Compute = fmt.Sprintf("%d.%d", memInfo.major, memInfo.minor)
  181. gpuInfo.MinimumMemory = cudaMinimumMemory
  182. gpuInfo.DependencyPath = depPath
  183. gpuInfo.Name = C.GoString(&memInfo.gpu_name[0])
  184. gpuInfo.DriverMajor = int(driverMajor)
  185. gpuInfo.DriverMinor = int(driverMinor)
  186. // TODO potentially sort on our own algorithm instead of what the underlying GPU library does...
  187. resp = append(resp, gpuInfo)
  188. }
  189. // Then AMD
  190. resp = append(resp, AMDGetGPUInfo()...)
  191. if len(resp) == 0 {
  192. C.cpu_check_ram(&memInfo)
  193. if memInfo.err != nil {
  194. slog.Info("error looking up CPU memory", "error", C.GoString(memInfo.err))
  195. C.free(unsafe.Pointer(memInfo.err))
  196. return resp
  197. }
  198. gpuInfo := GpuInfo{
  199. Library: "cpu",
  200. Variant: cpuVariant,
  201. }
  202. gpuInfo.TotalMemory = uint64(memInfo.total)
  203. gpuInfo.FreeMemory = uint64(memInfo.free)
  204. gpuInfo.ID = C.GoString(&memInfo.gpu_id[0])
  205. resp = append(resp, gpuInfo)
  206. }
  207. return resp
  208. }
  209. func GetCPUMem() (memInfo, error) {
  210. var ret memInfo
  211. var info C.mem_info_t
  212. C.cpu_check_ram(&info)
  213. if info.err != nil {
  214. defer C.free(unsafe.Pointer(info.err))
  215. return ret, fmt.Errorf(C.GoString(info.err))
  216. }
  217. ret.FreeMemory = uint64(info.free)
  218. ret.TotalMemory = uint64(info.total)
  219. return ret, nil
  220. }
  221. func FindGPULibs(baseLibName string, defaultPatterns []string) []string {
  222. // Multiple GPU libraries may exist, and some may not work, so keep trying until we exhaust them
  223. var ldPaths []string
  224. var patterns []string
  225. gpuLibPaths := []string{}
  226. slog.Debug("Searching for GPU library", "name", baseLibName)
  227. switch runtime.GOOS {
  228. case "windows":
  229. ldPaths = strings.Split(os.Getenv("PATH"), ";")
  230. case "linux":
  231. ldPaths = strings.Split(os.Getenv("LD_LIBRARY_PATH"), ":")
  232. default:
  233. return gpuLibPaths
  234. }
  235. // Start with whatever we find in the PATH/LD_LIBRARY_PATH
  236. for _, ldPath := range ldPaths {
  237. d, err := filepath.Abs(ldPath)
  238. if err != nil {
  239. continue
  240. }
  241. patterns = append(patterns, filepath.Join(d, baseLibName+"*"))
  242. }
  243. patterns = append(patterns, defaultPatterns...)
  244. slog.Debug("gpu library search", "globs", patterns)
  245. for _, pattern := range patterns {
  246. // Nvidia PhysX known to return bogus results
  247. if strings.Contains(pattern, "PhysX") {
  248. slog.Debug("skipping PhysX cuda library path", "path", pattern)
  249. }
  250. // Ignore glob discovery errors
  251. matches, _ := filepath.Glob(pattern)
  252. for _, match := range matches {
  253. // Resolve any links so we don't try the same lib multiple times
  254. // and weed out any dups across globs
  255. libPath := match
  256. tmp := match
  257. var err error
  258. for ; err == nil; tmp, err = os.Readlink(libPath) {
  259. if !filepath.IsAbs(tmp) {
  260. tmp = filepath.Join(filepath.Dir(libPath), tmp)
  261. }
  262. libPath = tmp
  263. }
  264. new := true
  265. for _, cmp := range gpuLibPaths {
  266. if cmp == libPath {
  267. new = false
  268. break
  269. }
  270. }
  271. if new {
  272. gpuLibPaths = append(gpuLibPaths, libPath)
  273. }
  274. }
  275. }
  276. slog.Debug("discovered GPU libraries", "paths", gpuLibPaths)
  277. return gpuLibPaths
  278. }
  279. func LoadCUDARTMgmt(cudartLibPaths []string) (int, *C.cudart_handle_t, string) {
  280. var resp C.cudart_init_resp_t
  281. resp.ch.verbose = getVerboseState()
  282. for _, libPath := range cudartLibPaths {
  283. lib := C.CString(libPath)
  284. defer C.free(unsafe.Pointer(lib))
  285. C.cudart_init(lib, &resp)
  286. if resp.err != nil {
  287. slog.Debug("Unable to load cudart", "library", libPath, "error", C.GoString(resp.err))
  288. C.free(unsafe.Pointer(resp.err))
  289. } else {
  290. return int(resp.num_devices), &resp.ch, libPath
  291. }
  292. }
  293. return 0, nil, ""
  294. }
  295. func LoadNVCUDAMgmt(nvcudaLibPaths []string) (int, *C.nvcuda_handle_t, string) {
  296. var resp C.nvcuda_init_resp_t
  297. resp.ch.verbose = getVerboseState()
  298. for _, libPath := range nvcudaLibPaths {
  299. lib := C.CString(libPath)
  300. defer C.free(unsafe.Pointer(lib))
  301. C.nvcuda_init(lib, &resp)
  302. if resp.err != nil {
  303. slog.Debug("Unable to load nvcuda", "library", libPath, "error", C.GoString(resp.err))
  304. C.free(unsafe.Pointer(resp.err))
  305. } else {
  306. return int(resp.num_devices), &resp.ch, libPath
  307. }
  308. }
  309. return 0, nil, ""
  310. }
  311. func getVerboseState() C.uint16_t {
  312. if envconfig.Debug {
  313. return C.uint16_t(1)
  314. }
  315. return C.uint16_t(0)
  316. }
  317. // Given the list of GPUs this instantiation is targeted for,
  318. // figure out the visible devices environment variable
  319. //
  320. // If different libraries are detected, the first one is what we use
  321. func (l GpuInfoList) GetVisibleDevicesEnv() (string, string) {
  322. if len(l) == 0 {
  323. return "", ""
  324. }
  325. switch l[0].Library {
  326. case "cuda":
  327. return cudaGetVisibleDevicesEnv(l)
  328. case "rocm":
  329. return rocmGetVisibleDevicesEnv(l)
  330. default:
  331. slog.Debug("no filter required for library " + l[0].Library)
  332. return "", ""
  333. }
  334. }