gpu.go 12 KB

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