gpu.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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 cudaHandles struct {
  22. deviceCount int
  23. cudart *C.cudart_handle_t
  24. nvcuda *C.nvcuda_handle_t
  25. nvml *C.nvml_handle_t
  26. }
  27. type oneapiHandles struct {
  28. oneapi *C.oneapi_handle_t
  29. deviceCount int
  30. }
  31. const (
  32. cudaMinimumMemory = 457 * format.MebiByte
  33. rocmMinimumMemory = 457 * format.MebiByte
  34. // TODO OneAPI minimum memory
  35. )
  36. var (
  37. gpuMutex sync.Mutex
  38. bootstrapped bool
  39. cpuCapability CPUCapability
  40. cpus []CPUInfo
  41. cudaGPUs []CudaGPUInfo
  42. nvcudaLibPath string
  43. cudartLibPath string
  44. oneapiLibPath string
  45. nvmlLibPath string
  46. rocmGPUs []RocmGPUInfo
  47. oneapiGPUs []OneapiGPUInfo
  48. )
  49. // With our current CUDA compile flags, older than 5.0 will not work properly
  50. var CudaComputeMin = [2]C.int{5, 0}
  51. var RocmComputeMin = 9
  52. // TODO find a better way to detect iGPU instead of minimum memory
  53. const IGPUMemLimit = 1 * format.GibiByte // 512G is what they typically report, so anything less than 1G must be iGPU
  54. // Jetson devices have JETSON_JETPACK="x.y.z" factory set to the Jetpack version installed.
  55. // Included to drive logic for reducing Ollama-allocated overhead on L4T/Jetson devices.
  56. var CudaTegra string = os.Getenv("JETSON_JETPACK")
  57. // Note: gpuMutex must already be held
  58. func initCudaHandles() *cudaHandles {
  59. // TODO - if the ollama build is CPU only, don't do these checks as they're irrelevant and confusing
  60. cHandles := &cudaHandles{}
  61. // Short Circuit if we already know which library to use
  62. if nvmlLibPath != "" {
  63. cHandles.nvml, _ = LoadNVMLMgmt([]string{nvmlLibPath})
  64. return cHandles
  65. }
  66. if nvcudaLibPath != "" {
  67. cHandles.deviceCount, cHandles.nvcuda, _ = LoadNVCUDAMgmt([]string{nvcudaLibPath})
  68. return cHandles
  69. }
  70. if cudartLibPath != "" {
  71. cHandles.deviceCount, cHandles.cudart, _ = LoadCUDARTMgmt([]string{cudartLibPath})
  72. return cHandles
  73. }
  74. slog.Debug("searching for GPU discovery libraries for NVIDIA")
  75. var cudartMgmtPatterns []string
  76. // Aligned with driver, we can't carry as payloads
  77. nvcudaMgmtPatterns := NvcudaGlobs
  78. if runtime.GOOS == "windows" {
  79. localAppData := os.Getenv("LOCALAPPDATA")
  80. cudartMgmtPatterns = []string{filepath.Join(localAppData, "Programs", "Ollama", CudartMgmtName)}
  81. }
  82. tmpDir, _ := PayloadsDir()
  83. if tmpDir != "" {
  84. // TODO - add "payloads" for subprocess
  85. cudartMgmtPatterns = []string{filepath.Join(tmpDir, "cuda*", CudartMgmtName)}
  86. }
  87. cudartMgmtPatterns = append(cudartMgmtPatterns, CudartGlobs...)
  88. if len(NvmlGlobs) > 0 {
  89. nvmlLibPaths := FindGPULibs(NvmlMgmtName, NvmlGlobs)
  90. if len(nvmlLibPaths) > 0 {
  91. nvml, libPath := LoadNVMLMgmt(nvmlLibPaths)
  92. if nvml != nil {
  93. slog.Debug("nvidia-ml loaded", "library", libPath)
  94. cHandles.nvml = nvml
  95. nvmlLibPath = libPath
  96. }
  97. }
  98. }
  99. nvcudaLibPaths := FindGPULibs(NvcudaMgmtName, nvcudaMgmtPatterns)
  100. if len(nvcudaLibPaths) > 0 {
  101. deviceCount, nvcuda, libPath := LoadNVCUDAMgmt(nvcudaLibPaths)
  102. if nvcuda != nil {
  103. slog.Debug("detected GPUs", "count", deviceCount, "library", libPath)
  104. cHandles.nvcuda = nvcuda
  105. cHandles.deviceCount = deviceCount
  106. nvcudaLibPath = libPath
  107. return cHandles
  108. }
  109. }
  110. cudartLibPaths := FindGPULibs(CudartMgmtName, cudartMgmtPatterns)
  111. if len(cudartLibPaths) > 0 {
  112. deviceCount, cudart, libPath := LoadCUDARTMgmt(cudartLibPaths)
  113. if cudart != nil {
  114. slog.Debug("detected GPUs", "library", libPath, "count", deviceCount)
  115. cHandles.cudart = cudart
  116. cHandles.deviceCount = deviceCount
  117. cudartLibPath = libPath
  118. return cHandles
  119. }
  120. }
  121. return cHandles
  122. }
  123. // Note: gpuMutex must already be held
  124. func initOneAPIHandles() *oneapiHandles {
  125. oHandles := &oneapiHandles{}
  126. // Short Circuit if we already know which library to use
  127. if oneapiLibPath != "" {
  128. oHandles.deviceCount, oHandles.oneapi, _ = LoadOneapiMgmt([]string{oneapiLibPath})
  129. return oHandles
  130. }
  131. oneapiLibPaths := FindGPULibs(OneapiMgmtName, OneapiGlobs)
  132. if len(oneapiLibPaths) > 0 {
  133. oHandles.deviceCount, oHandles.oneapi, oneapiLibPath = LoadOneapiMgmt(oneapiLibPaths)
  134. }
  135. return oHandles
  136. }
  137. func GetCPUInfo() GpuInfoList {
  138. gpuMutex.Lock()
  139. if !bootstrapped {
  140. gpuMutex.Unlock()
  141. GetGPUInfo()
  142. } else {
  143. gpuMutex.Unlock()
  144. }
  145. return GpuInfoList{cpus[0].GpuInfo}
  146. }
  147. func GetGPUInfo() GpuInfoList {
  148. // TODO - consider exploring lspci (and equivalent on windows) to check for
  149. // GPUs so we can report warnings if we see Nvidia/AMD but fail to load the libraries
  150. gpuMutex.Lock()
  151. defer gpuMutex.Unlock()
  152. needRefresh := true
  153. var cHandles *cudaHandles
  154. var oHandles *oneapiHandles
  155. defer func() {
  156. if cHandles != nil {
  157. if cHandles.cudart != nil {
  158. C.cudart_release(*cHandles.cudart)
  159. }
  160. if cHandles.nvcuda != nil {
  161. C.nvcuda_release(*cHandles.nvcuda)
  162. }
  163. if cHandles.nvml != nil {
  164. C.nvml_release(*cHandles.nvml)
  165. }
  166. }
  167. if oHandles != nil {
  168. if oHandles.oneapi != nil {
  169. // TODO - is this needed?
  170. C.oneapi_release(*oHandles.oneapi)
  171. }
  172. }
  173. }()
  174. if !bootstrapped {
  175. slog.Info("looking for compatible GPUs")
  176. needRefresh = false
  177. cpuCapability = GetCPUCapability()
  178. var memInfo C.mem_info_t
  179. mem, err := GetCPUMem()
  180. if err != nil {
  181. slog.Warn("error looking up system memory", "error", err)
  182. }
  183. cpus = []CPUInfo{
  184. {
  185. GpuInfo: GpuInfo{
  186. memInfo: mem,
  187. Library: "cpu",
  188. Variant: cpuCapability,
  189. ID: "0",
  190. },
  191. },
  192. }
  193. // Fallback to CPU mode if we're lacking required vector extensions on x86
  194. if cpuCapability < GPURunnerCPUCapability && runtime.GOARCH == "amd64" {
  195. slog.Warn("CPU does not have minimum vector extensions, GPU inference disabled", "required", GPURunnerCPUCapability, "detected", cpuCapability)
  196. bootstrapped = true
  197. // No need to do any GPU discovery, since we can't run on them
  198. return GpuInfoList{cpus[0].GpuInfo}
  199. }
  200. // On windows we bundle the nvidia library one level above the runner dir
  201. depPath := ""
  202. if runtime.GOOS == "windows" && envconfig.RunnersDir() != "" {
  203. depPath = filepath.Join(filepath.Dir(envconfig.RunnersDir()), "cuda")
  204. }
  205. // Load ALL libraries
  206. cHandles = initCudaHandles()
  207. // NVIDIA
  208. for i := range cHandles.deviceCount {
  209. if cHandles.cudart != nil || cHandles.nvcuda != nil {
  210. gpuInfo := CudaGPUInfo{
  211. GpuInfo: GpuInfo{
  212. Library: "cuda",
  213. },
  214. index: i,
  215. }
  216. var driverMajor int
  217. var driverMinor int
  218. if cHandles.cudart != nil {
  219. C.cudart_bootstrap(*cHandles.cudart, C.int(i), &memInfo)
  220. } else {
  221. C.nvcuda_bootstrap(*cHandles.nvcuda, C.int(i), &memInfo)
  222. driverMajor = int(cHandles.nvcuda.driver_major)
  223. driverMinor = int(cHandles.nvcuda.driver_minor)
  224. }
  225. if memInfo.err != nil {
  226. slog.Info("error looking up nvidia GPU memory", "error", C.GoString(memInfo.err))
  227. C.free(unsafe.Pointer(memInfo.err))
  228. continue
  229. }
  230. if memInfo.major < CudaComputeMin[0] || (memInfo.major == CudaComputeMin[0] && memInfo.minor < CudaComputeMin[1]) {
  231. slog.Info(fmt.Sprintf("[%d] CUDA GPU is too old. Compute Capability detected: %d.%d", i, memInfo.major, memInfo.minor))
  232. continue
  233. }
  234. gpuInfo.TotalMemory = uint64(memInfo.total)
  235. gpuInfo.FreeMemory = uint64(memInfo.free)
  236. gpuInfo.ID = C.GoString(&memInfo.gpu_id[0])
  237. gpuInfo.Compute = fmt.Sprintf("%d.%d", memInfo.major, memInfo.minor)
  238. gpuInfo.MinimumMemory = cudaMinimumMemory
  239. gpuInfo.DependencyPath = depPath
  240. gpuInfo.Name = C.GoString(&memInfo.gpu_name[0])
  241. gpuInfo.DriverMajor = driverMajor
  242. gpuInfo.DriverMinor = driverMinor
  243. // query the management library as well so we can record any skew between the two
  244. // which represents overhead on the GPU we must set aside on subsequent updates
  245. if cHandles.nvml != nil {
  246. C.nvml_get_free(*cHandles.nvml, C.int(gpuInfo.index), &memInfo.free, &memInfo.total, &memInfo.used)
  247. if memInfo.err != nil {
  248. slog.Warn("error looking up nvidia GPU memory", "error", C.GoString(memInfo.err))
  249. C.free(unsafe.Pointer(memInfo.err))
  250. } else {
  251. if memInfo.free != 0 && uint64(memInfo.free) > gpuInfo.FreeMemory {
  252. gpuInfo.OSOverhead = uint64(memInfo.free) - gpuInfo.FreeMemory
  253. slog.Info("detected OS VRAM overhead",
  254. "id", gpuInfo.ID,
  255. "library", gpuInfo.Library,
  256. "compute", gpuInfo.Compute,
  257. "driver", fmt.Sprintf("%d.%d", gpuInfo.DriverMajor, gpuInfo.DriverMinor),
  258. "name", gpuInfo.Name,
  259. "overhead", format.HumanBytes2(gpuInfo.OSOverhead),
  260. )
  261. }
  262. }
  263. }
  264. // TODO potentially sort on our own algorithm instead of what the underlying GPU library does...
  265. cudaGPUs = append(cudaGPUs, gpuInfo)
  266. }
  267. }
  268. // Intel
  269. if envconfig.IntelGPU() {
  270. oHandles = initOneAPIHandles()
  271. // On windows we bundle the oneapi library one level above the runner dir
  272. depPath = ""
  273. if runtime.GOOS == "windows" && envconfig.RunnersDir() != "" {
  274. depPath = filepath.Join(filepath.Dir(envconfig.RunnersDir()), "oneapi")
  275. }
  276. for d := range oHandles.oneapi.num_drivers {
  277. if oHandles.oneapi == nil {
  278. // shouldn't happen
  279. slog.Warn("nil oneapi handle with driver count", "count", int(oHandles.oneapi.num_drivers))
  280. continue
  281. }
  282. devCount := C.oneapi_get_device_count(*oHandles.oneapi, C.int(d))
  283. for i := range devCount {
  284. gpuInfo := OneapiGPUInfo{
  285. GpuInfo: GpuInfo{
  286. Library: "oneapi",
  287. },
  288. driverIndex: int(d),
  289. gpuIndex: int(i),
  290. }
  291. // TODO - split bootstrapping from updating free memory
  292. C.oneapi_check_vram(*oHandles.oneapi, C.int(d), i, &memInfo)
  293. // TODO - convert this to MinimumMemory based on testing...
  294. var totalFreeMem float64 = float64(memInfo.free) * 0.95 // work-around: leave some reserve vram for mkl lib used in ggml-sycl backend.
  295. memInfo.free = C.uint64_t(totalFreeMem)
  296. gpuInfo.TotalMemory = uint64(memInfo.total)
  297. gpuInfo.FreeMemory = uint64(memInfo.free)
  298. gpuInfo.ID = C.GoString(&memInfo.gpu_id[0])
  299. gpuInfo.Name = C.GoString(&memInfo.gpu_name[0])
  300. gpuInfo.DependencyPath = depPath
  301. oneapiGPUs = append(oneapiGPUs, gpuInfo)
  302. }
  303. }
  304. }
  305. rocmGPUs = AMDGetGPUInfo()
  306. bootstrapped = true
  307. if len(cudaGPUs) == 0 && len(rocmGPUs) == 0 && len(oneapiGPUs) == 0 {
  308. slog.Info("no compatible GPUs were discovered")
  309. }
  310. }
  311. // For detected GPUs, load library if not loaded
  312. // Refresh free memory usage
  313. if needRefresh {
  314. mem, err := GetCPUMem()
  315. if err != nil {
  316. slog.Warn("error looking up system memory", "error", err)
  317. } else {
  318. slog.Debug("updating system memory data",
  319. slog.Group(
  320. "before",
  321. "total", format.HumanBytes2(cpus[0].TotalMemory),
  322. "free", format.HumanBytes2(cpus[0].FreeMemory),
  323. "free_swap", format.HumanBytes2(cpus[0].FreeSwap),
  324. ),
  325. slog.Group(
  326. "now",
  327. "total", format.HumanBytes2(mem.TotalMemory),
  328. "free", format.HumanBytes2(mem.FreeMemory),
  329. "free_swap", format.HumanBytes2(mem.FreeSwap),
  330. ),
  331. )
  332. cpus[0].FreeMemory = mem.FreeMemory
  333. cpus[0].FreeSwap = mem.FreeSwap
  334. }
  335. var memInfo C.mem_info_t
  336. if cHandles == nil && len(cudaGPUs) > 0 {
  337. cHandles = initCudaHandles()
  338. }
  339. for i, gpu := range cudaGPUs {
  340. if cHandles.nvml != nil {
  341. C.nvml_get_free(*cHandles.nvml, C.int(gpu.index), &memInfo.free, &memInfo.total, &memInfo.used)
  342. } else if cHandles.cudart != nil {
  343. C.cudart_bootstrap(*cHandles.cudart, C.int(gpu.index), &memInfo)
  344. } else if cHandles.nvcuda != nil {
  345. C.nvcuda_get_free(*cHandles.nvcuda, C.int(gpu.index), &memInfo.free, &memInfo.total)
  346. memInfo.used = memInfo.total - memInfo.free
  347. } else {
  348. // shouldn't happen
  349. slog.Warn("no valid cuda library loaded to refresh vram usage")
  350. break
  351. }
  352. if memInfo.err != nil {
  353. slog.Warn("error looking up nvidia GPU memory", "error", C.GoString(memInfo.err))
  354. C.free(unsafe.Pointer(memInfo.err))
  355. continue
  356. }
  357. if memInfo.free == 0 {
  358. slog.Warn("error looking up nvidia GPU memory")
  359. continue
  360. }
  361. if cHandles.nvml != nil && gpu.OSOverhead > 0 {
  362. // When using the management library update based on recorded overhead
  363. memInfo.free -= C.uint64_t(gpu.OSOverhead)
  364. }
  365. slog.Debug("updating cuda memory data",
  366. "gpu", gpu.ID,
  367. "name", gpu.Name,
  368. "overhead", format.HumanBytes2(gpu.OSOverhead),
  369. slog.Group(
  370. "before",
  371. "total", format.HumanBytes2(gpu.TotalMemory),
  372. "free", format.HumanBytes2(gpu.FreeMemory),
  373. ),
  374. slog.Group(
  375. "now",
  376. "total", format.HumanBytes2(uint64(memInfo.total)),
  377. "free", format.HumanBytes2(uint64(memInfo.free)),
  378. "used", format.HumanBytes2(uint64(memInfo.used)),
  379. ),
  380. )
  381. cudaGPUs[i].FreeMemory = uint64(memInfo.free)
  382. }
  383. if oHandles == nil && len(oneapiGPUs) > 0 {
  384. oHandles = initOneAPIHandles()
  385. }
  386. for i, gpu := range oneapiGPUs {
  387. if oHandles.oneapi == nil {
  388. // shouldn't happen
  389. slog.Warn("nil oneapi handle with device count", "count", oHandles.deviceCount)
  390. continue
  391. }
  392. C.oneapi_check_vram(*oHandles.oneapi, C.int(gpu.driverIndex), C.int(gpu.gpuIndex), &memInfo)
  393. // TODO - convert this to MinimumMemory based on testing...
  394. var totalFreeMem float64 = float64(memInfo.free) * 0.95 // work-around: leave some reserve vram for mkl lib used in ggml-sycl backend.
  395. memInfo.free = C.uint64_t(totalFreeMem)
  396. oneapiGPUs[i].FreeMemory = uint64(memInfo.free)
  397. }
  398. err = RocmGPUInfoList(rocmGPUs).RefreshFreeMemory()
  399. if err != nil {
  400. slog.Debug("problem refreshing ROCm free memory", "error", err)
  401. }
  402. }
  403. resp := []GpuInfo{}
  404. for _, gpu := range cudaGPUs {
  405. resp = append(resp, gpu.GpuInfo)
  406. }
  407. for _, gpu := range rocmGPUs {
  408. resp = append(resp, gpu.GpuInfo)
  409. }
  410. for _, gpu := range oneapiGPUs {
  411. resp = append(resp, gpu.GpuInfo)
  412. }
  413. if len(resp) == 0 {
  414. resp = append(resp, cpus[0].GpuInfo)
  415. }
  416. return resp
  417. }
  418. func FindGPULibs(baseLibName string, defaultPatterns []string) []string {
  419. // Multiple GPU libraries may exist, and some may not work, so keep trying until we exhaust them
  420. var ldPaths []string
  421. var patterns []string
  422. gpuLibPaths := []string{}
  423. slog.Debug("Searching for GPU library", "name", baseLibName)
  424. switch runtime.GOOS {
  425. case "windows":
  426. ldPaths = strings.Split(os.Getenv("PATH"), ";")
  427. case "linux":
  428. ldPaths = strings.Split(os.Getenv("LD_LIBRARY_PATH"), ":")
  429. default:
  430. return gpuLibPaths
  431. }
  432. // Start with whatever we find in the PATH/LD_LIBRARY_PATH
  433. for _, ldPath := range ldPaths {
  434. d, err := filepath.Abs(ldPath)
  435. if err != nil {
  436. continue
  437. }
  438. patterns = append(patterns, filepath.Join(d, baseLibName+"*"))
  439. }
  440. patterns = append(patterns, defaultPatterns...)
  441. slog.Debug("gpu library search", "globs", patterns)
  442. for _, pattern := range patterns {
  443. // Nvidia PhysX known to return bogus results
  444. if strings.Contains(pattern, "PhysX") {
  445. slog.Debug("skipping PhysX cuda library path", "path", pattern)
  446. continue
  447. }
  448. // Ignore glob discovery errors
  449. matches, _ := filepath.Glob(pattern)
  450. for _, match := range matches {
  451. // Resolve any links so we don't try the same lib multiple times
  452. // and weed out any dups across globs
  453. libPath := match
  454. tmp := match
  455. var err error
  456. for ; err == nil; tmp, err = os.Readlink(libPath) {
  457. if !filepath.IsAbs(tmp) {
  458. tmp = filepath.Join(filepath.Dir(libPath), tmp)
  459. }
  460. libPath = tmp
  461. }
  462. new := true
  463. for _, cmp := range gpuLibPaths {
  464. if cmp == libPath {
  465. new = false
  466. break
  467. }
  468. }
  469. if new {
  470. gpuLibPaths = append(gpuLibPaths, libPath)
  471. }
  472. }
  473. }
  474. slog.Debug("discovered GPU libraries", "paths", gpuLibPaths)
  475. return gpuLibPaths
  476. }
  477. func LoadCUDARTMgmt(cudartLibPaths []string) (int, *C.cudart_handle_t, string) {
  478. var resp C.cudart_init_resp_t
  479. resp.ch.verbose = getVerboseState()
  480. for _, libPath := range cudartLibPaths {
  481. lib := C.CString(libPath)
  482. defer C.free(unsafe.Pointer(lib))
  483. C.cudart_init(lib, &resp)
  484. if resp.err != nil {
  485. slog.Debug("Unable to load cudart", "library", libPath, "error", C.GoString(resp.err))
  486. C.free(unsafe.Pointer(resp.err))
  487. } else {
  488. return int(resp.num_devices), &resp.ch, libPath
  489. }
  490. }
  491. return 0, nil, ""
  492. }
  493. func LoadNVCUDAMgmt(nvcudaLibPaths []string) (int, *C.nvcuda_handle_t, string) {
  494. var resp C.nvcuda_init_resp_t
  495. resp.ch.verbose = getVerboseState()
  496. for _, libPath := range nvcudaLibPaths {
  497. lib := C.CString(libPath)
  498. defer C.free(unsafe.Pointer(lib))
  499. C.nvcuda_init(lib, &resp)
  500. if resp.err != nil {
  501. // Decide what log level based on the type of error message to help users understand why
  502. msg := C.GoString(resp.err)
  503. switch resp.cudaErr {
  504. case C.CUDA_ERROR_INSUFFICIENT_DRIVER, C.CUDA_ERROR_SYSTEM_DRIVER_MISMATCH:
  505. slog.Warn("version mismatch between driver and cuda driver library - reboot or upgrade may be required", "library", libPath, "error", msg)
  506. case C.CUDA_ERROR_NO_DEVICE:
  507. slog.Info("no nvidia devices detected", "library", libPath)
  508. case C.CUDA_ERROR_UNKNOWN:
  509. slog.Warn("unknown error initializing cuda driver library", "library", libPath, "error", msg)
  510. slog.Warn("see https://github.com/ollama/ollama/blob/main/docs/troubleshooting.md for more information")
  511. default:
  512. if strings.Contains(msg, "wrong ELF class") {
  513. slog.Debug("skipping 32bit library", "library", libPath)
  514. } else {
  515. slog.Info("unable to load cuda driver library", "library", libPath, "error", msg)
  516. }
  517. }
  518. C.free(unsafe.Pointer(resp.err))
  519. } else {
  520. return int(resp.num_devices), &resp.ch, libPath
  521. }
  522. }
  523. return 0, nil, ""
  524. }
  525. func LoadNVMLMgmt(nvmlLibPaths []string) (*C.nvml_handle_t, string) {
  526. var resp C.nvml_init_resp_t
  527. resp.ch.verbose = getVerboseState()
  528. for _, libPath := range nvmlLibPaths {
  529. lib := C.CString(libPath)
  530. defer C.free(unsafe.Pointer(lib))
  531. C.nvml_init(lib, &resp)
  532. if resp.err != nil {
  533. slog.Info(fmt.Sprintf("Unable to load NVML management library %s: %s", libPath, C.GoString(resp.err)))
  534. C.free(unsafe.Pointer(resp.err))
  535. } else {
  536. return &resp.ch, libPath
  537. }
  538. }
  539. return nil, ""
  540. }
  541. func LoadOneapiMgmt(oneapiLibPaths []string) (int, *C.oneapi_handle_t, string) {
  542. var resp C.oneapi_init_resp_t
  543. num_devices := 0
  544. resp.oh.verbose = getVerboseState()
  545. for _, libPath := range oneapiLibPaths {
  546. lib := C.CString(libPath)
  547. defer C.free(unsafe.Pointer(lib))
  548. C.oneapi_init(lib, &resp)
  549. if resp.err != nil {
  550. slog.Debug("Unable to load oneAPI management library", "library", libPath, "error", C.GoString(resp.err))
  551. C.free(unsafe.Pointer(resp.err))
  552. } else {
  553. for i := range resp.oh.num_drivers {
  554. num_devices += int(C.oneapi_get_device_count(resp.oh, C.int(i)))
  555. }
  556. return num_devices, &resp.oh, libPath
  557. }
  558. }
  559. return 0, nil, ""
  560. }
  561. func getVerboseState() C.uint16_t {
  562. if envconfig.Debug() {
  563. return C.uint16_t(1)
  564. }
  565. return C.uint16_t(0)
  566. }
  567. // Given the list of GPUs this instantiation is targeted for,
  568. // figure out the visible devices environment variable
  569. //
  570. // If different libraries are detected, the first one is what we use
  571. func (l GpuInfoList) GetVisibleDevicesEnv() (string, string) {
  572. if len(l) == 0 {
  573. return "", ""
  574. }
  575. switch l[0].Library {
  576. case "cuda":
  577. return cudaGetVisibleDevicesEnv(l)
  578. case "rocm":
  579. return rocmGetVisibleDevicesEnv(l)
  580. case "oneapi":
  581. return oneapiGetVisibleDevicesEnv(l)
  582. default:
  583. slog.Debug("no filter required for library " + l[0].Library)
  584. return "", ""
  585. }
  586. }