gpu.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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{CPUInfo{
  184. GpuInfo: GpuInfo{
  185. memInfo: mem,
  186. Library: "cpu",
  187. Variant: cpuCapability,
  188. ID: "0",
  189. },
  190. }}
  191. // Fallback to CPU mode if we're lacking required vector extensions on x86
  192. if cpuCapability < GPURunnerCPUCapability && runtime.GOARCH == "amd64" {
  193. slog.Warn("CPU does not have minimum vector extensions, GPU inference disabled", "required", GPURunnerCPUCapability, "detected", cpuCapability)
  194. bootstrapped = true
  195. // No need to do any GPU discovery, since we can't run on them
  196. return GpuInfoList{cpus[0].GpuInfo}
  197. }
  198. // On windows we bundle the nvidia library one level above the runner dir
  199. depPath := ""
  200. if runtime.GOOS == "windows" && envconfig.RunnersDir != "" {
  201. depPath = filepath.Join(filepath.Dir(envconfig.RunnersDir), "cuda")
  202. }
  203. // Load ALL libraries
  204. cHandles = initCudaHandles()
  205. // NVIDIA
  206. for i := range cHandles.deviceCount {
  207. if cHandles.cudart != nil || cHandles.nvcuda != nil {
  208. gpuInfo := CudaGPUInfo{
  209. GpuInfo: GpuInfo{
  210. Library: "cuda",
  211. },
  212. index: i,
  213. }
  214. var driverMajor int
  215. var driverMinor int
  216. if cHandles.cudart != nil {
  217. C.cudart_bootstrap(*cHandles.cudart, C.int(i), &memInfo)
  218. } else {
  219. C.nvcuda_bootstrap(*cHandles.nvcuda, C.int(i), &memInfo)
  220. driverMajor = int(cHandles.nvcuda.driver_major)
  221. driverMinor = int(cHandles.nvcuda.driver_minor)
  222. }
  223. if memInfo.err != nil {
  224. slog.Info("error looking up nvidia GPU memory", "error", C.GoString(memInfo.err))
  225. C.free(unsafe.Pointer(memInfo.err))
  226. continue
  227. }
  228. if memInfo.major < CudaComputeMin[0] || (memInfo.major == CudaComputeMin[0] && memInfo.minor < CudaComputeMin[1]) {
  229. slog.Info(fmt.Sprintf("[%d] CUDA GPU is too old. Compute Capability detected: %d.%d", i, memInfo.major, memInfo.minor))
  230. continue
  231. }
  232. gpuInfo.TotalMemory = uint64(memInfo.total)
  233. gpuInfo.FreeMemory = uint64(memInfo.free)
  234. gpuInfo.ID = C.GoString(&memInfo.gpu_id[0])
  235. gpuInfo.Compute = fmt.Sprintf("%d.%d", memInfo.major, memInfo.minor)
  236. gpuInfo.MinimumMemory = cudaMinimumMemory
  237. gpuInfo.DependencyPath = depPath
  238. gpuInfo.Name = C.GoString(&memInfo.gpu_name[0])
  239. gpuInfo.DriverMajor = driverMajor
  240. gpuInfo.DriverMinor = driverMinor
  241. // query the management library as well so we can record any skew between the two
  242. // which represents overhead on the GPU we must set aside on subsequent updates
  243. if cHandles.nvml != nil {
  244. C.nvml_get_free(*cHandles.nvml, C.int(gpuInfo.index), &memInfo.free, &memInfo.total, &memInfo.used)
  245. if memInfo.err != nil {
  246. slog.Warn("error looking up nvidia GPU memory", "error", C.GoString(memInfo.err))
  247. C.free(unsafe.Pointer(memInfo.err))
  248. } else {
  249. if memInfo.free != 0 && uint64(memInfo.free) > gpuInfo.FreeMemory {
  250. gpuInfo.OSOverhead = uint64(memInfo.free) - gpuInfo.FreeMemory
  251. slog.Info("detected OS VRAM overhead",
  252. "id", gpuInfo.ID,
  253. "library", gpuInfo.Library,
  254. "compute", gpuInfo.Compute,
  255. "driver", fmt.Sprintf("%d.%d", gpuInfo.DriverMajor, gpuInfo.DriverMinor),
  256. "name", gpuInfo.Name,
  257. "overhead", format.HumanBytes2(gpuInfo.OSOverhead),
  258. )
  259. }
  260. }
  261. }
  262. // TODO potentially sort on our own algorithm instead of what the underlying GPU library does...
  263. cudaGPUs = append(cudaGPUs, gpuInfo)
  264. }
  265. }
  266. // Intel
  267. if envconfig.IntelGpu {
  268. oHandles = initOneAPIHandles()
  269. // On windows we bundle the oneapi library one level above the runner dir
  270. depPath = ""
  271. if runtime.GOOS == "windows" && envconfig.RunnersDir != "" {
  272. depPath = filepath.Join(filepath.Dir(envconfig.RunnersDir), "oneapi")
  273. }
  274. for d := range oHandles.oneapi.num_drivers {
  275. if oHandles.oneapi == nil {
  276. // shouldn't happen
  277. slog.Warn("nil oneapi handle with driver count", "count", int(oHandles.oneapi.num_drivers))
  278. continue
  279. }
  280. devCount := C.oneapi_get_device_count(*oHandles.oneapi, C.int(d))
  281. for i := range devCount {
  282. gpuInfo := OneapiGPUInfo{
  283. GpuInfo: GpuInfo{
  284. Library: "oneapi",
  285. },
  286. driverIndex: int(d),
  287. gpuIndex: int(i),
  288. }
  289. // TODO - split bootstrapping from updating free memory
  290. C.oneapi_check_vram(*oHandles.oneapi, C.int(d), i, &memInfo)
  291. // TODO - convert this to MinimumMemory based on testing...
  292. var totalFreeMem float64 = float64(memInfo.free) * 0.95 // work-around: leave some reserve vram for mkl lib used in ggml-sycl backend.
  293. memInfo.free = C.uint64_t(totalFreeMem)
  294. gpuInfo.TotalMemory = uint64(memInfo.total)
  295. gpuInfo.FreeMemory = uint64(memInfo.free)
  296. gpuInfo.ID = C.GoString(&memInfo.gpu_id[0])
  297. gpuInfo.Name = C.GoString(&memInfo.gpu_name[0])
  298. gpuInfo.DependencyPath = depPath
  299. oneapiGPUs = append(oneapiGPUs, gpuInfo)
  300. }
  301. }
  302. }
  303. rocmGPUs = AMDGetGPUInfo()
  304. bootstrapped = true
  305. if len(cudaGPUs) == 0 && len(rocmGPUs) == 0 && len(oneapiGPUs) == 0 {
  306. slog.Info("no compatible GPUs were discovered")
  307. }
  308. }
  309. // For detected GPUs, load library if not loaded
  310. // Refresh free memory usage
  311. if needRefresh {
  312. mem, err := GetCPUMem()
  313. if err != nil {
  314. slog.Warn("error looking up system memory", "error", err)
  315. } else {
  316. slog.Debug("updating system memory data",
  317. slog.Group(
  318. "before",
  319. "total", format.HumanBytes2(cpus[0].TotalMemory),
  320. "free", format.HumanBytes2(cpus[0].FreeMemory),
  321. ),
  322. slog.Group(
  323. "now",
  324. "total", format.HumanBytes2(mem.TotalMemory),
  325. "free", format.HumanBytes2(mem.FreeMemory),
  326. ),
  327. )
  328. cpus[0].FreeMemory = mem.FreeMemory
  329. }
  330. var memInfo C.mem_info_t
  331. if cHandles == nil && len(cudaGPUs) > 0 {
  332. cHandles = initCudaHandles()
  333. }
  334. for i, gpu := range cudaGPUs {
  335. if cHandles.nvml != nil {
  336. C.nvml_get_free(*cHandles.nvml, C.int(gpu.index), &memInfo.free, &memInfo.total, &memInfo.used)
  337. } else if cHandles.cudart != nil {
  338. C.cudart_bootstrap(*cHandles.cudart, C.int(gpu.index), &memInfo)
  339. } else if cHandles.nvcuda != nil {
  340. C.nvcuda_get_free(*cHandles.nvcuda, C.int(gpu.index), &memInfo.free, &memInfo.total)
  341. memInfo.used = memInfo.total - memInfo.free
  342. } else {
  343. // shouldn't happen
  344. slog.Warn("no valid cuda library loaded to refresh vram usage")
  345. break
  346. }
  347. if memInfo.err != nil {
  348. slog.Warn("error looking up nvidia GPU memory", "error", C.GoString(memInfo.err))
  349. C.free(unsafe.Pointer(memInfo.err))
  350. continue
  351. }
  352. if memInfo.free == 0 {
  353. slog.Warn("error looking up nvidia GPU memory")
  354. continue
  355. }
  356. if cHandles.nvml != nil && gpu.OSOverhead > 0 {
  357. // When using the management library update based on recorded overhead
  358. memInfo.free -= C.uint64_t(gpu.OSOverhead)
  359. }
  360. slog.Debug("updating cuda memory data",
  361. "gpu", gpu.ID,
  362. "name", gpu.Name,
  363. "overhead", format.HumanBytes2(gpu.OSOverhead),
  364. slog.Group(
  365. "before",
  366. "total", format.HumanBytes2(gpu.TotalMemory),
  367. "free", format.HumanBytes2(gpu.FreeMemory),
  368. ),
  369. slog.Group(
  370. "now",
  371. "total", format.HumanBytes2(uint64(memInfo.total)),
  372. "free", format.HumanBytes2(uint64(memInfo.free)),
  373. "used", format.HumanBytes2(uint64(memInfo.used)),
  374. ),
  375. )
  376. cudaGPUs[i].FreeMemory = uint64(memInfo.free)
  377. }
  378. if oHandles == nil && len(oneapiGPUs) > 0 {
  379. oHandles = initOneAPIHandles()
  380. }
  381. for i, gpu := range oneapiGPUs {
  382. if oHandles.oneapi == nil {
  383. // shouldn't happen
  384. slog.Warn("nil oneapi handle with device count", "count", oHandles.deviceCount)
  385. continue
  386. }
  387. C.oneapi_check_vram(*oHandles.oneapi, C.int(gpu.driverIndex), C.int(gpu.gpuIndex), &memInfo)
  388. // TODO - convert this to MinimumMemory based on testing...
  389. var totalFreeMem float64 = float64(memInfo.free) * 0.95 // work-around: leave some reserve vram for mkl lib used in ggml-sycl backend.
  390. memInfo.free = C.uint64_t(totalFreeMem)
  391. oneapiGPUs[i].FreeMemory = uint64(memInfo.free)
  392. }
  393. err = RocmGPUInfoList(rocmGPUs).RefreshFreeMemory()
  394. if err != nil {
  395. slog.Debug("problem refreshing ROCm free memory", "error", err)
  396. }
  397. }
  398. resp := []GpuInfo{}
  399. for _, gpu := range cudaGPUs {
  400. resp = append(resp, gpu.GpuInfo)
  401. }
  402. for _, gpu := range rocmGPUs {
  403. resp = append(resp, gpu.GpuInfo)
  404. }
  405. for _, gpu := range oneapiGPUs {
  406. resp = append(resp, gpu.GpuInfo)
  407. }
  408. if len(resp) == 0 {
  409. resp = append(resp, cpus[0].GpuInfo)
  410. }
  411. return resp
  412. }
  413. func FindGPULibs(baseLibName string, defaultPatterns []string) []string {
  414. // Multiple GPU libraries may exist, and some may not work, so keep trying until we exhaust them
  415. var ldPaths []string
  416. var patterns []string
  417. gpuLibPaths := []string{}
  418. slog.Debug("Searching for GPU library", "name", baseLibName)
  419. switch runtime.GOOS {
  420. case "windows":
  421. ldPaths = strings.Split(os.Getenv("PATH"), ";")
  422. case "linux":
  423. ldPaths = strings.Split(os.Getenv("LD_LIBRARY_PATH"), ":")
  424. default:
  425. return gpuLibPaths
  426. }
  427. // Start with whatever we find in the PATH/LD_LIBRARY_PATH
  428. for _, ldPath := range ldPaths {
  429. d, err := filepath.Abs(ldPath)
  430. if err != nil {
  431. continue
  432. }
  433. patterns = append(patterns, filepath.Join(d, baseLibName+"*"))
  434. }
  435. patterns = append(patterns, defaultPatterns...)
  436. slog.Debug("gpu library search", "globs", patterns)
  437. for _, pattern := range patterns {
  438. // Nvidia PhysX known to return bogus results
  439. if strings.Contains(pattern, "PhysX") {
  440. slog.Debug("skipping PhysX cuda library path", "path", pattern)
  441. continue
  442. }
  443. // Ignore glob discovery errors
  444. matches, _ := filepath.Glob(pattern)
  445. for _, match := range matches {
  446. // Resolve any links so we don't try the same lib multiple times
  447. // and weed out any dups across globs
  448. libPath := match
  449. tmp := match
  450. var err error
  451. for ; err == nil; tmp, err = os.Readlink(libPath) {
  452. if !filepath.IsAbs(tmp) {
  453. tmp = filepath.Join(filepath.Dir(libPath), tmp)
  454. }
  455. libPath = tmp
  456. }
  457. new := true
  458. for _, cmp := range gpuLibPaths {
  459. if cmp == libPath {
  460. new = false
  461. break
  462. }
  463. }
  464. if new {
  465. gpuLibPaths = append(gpuLibPaths, libPath)
  466. }
  467. }
  468. }
  469. slog.Debug("discovered GPU libraries", "paths", gpuLibPaths)
  470. return gpuLibPaths
  471. }
  472. func LoadCUDARTMgmt(cudartLibPaths []string) (int, *C.cudart_handle_t, string) {
  473. var resp C.cudart_init_resp_t
  474. resp.ch.verbose = getVerboseState()
  475. for _, libPath := range cudartLibPaths {
  476. lib := C.CString(libPath)
  477. defer C.free(unsafe.Pointer(lib))
  478. C.cudart_init(lib, &resp)
  479. if resp.err != nil {
  480. slog.Debug("Unable to load cudart", "library", libPath, "error", C.GoString(resp.err))
  481. C.free(unsafe.Pointer(resp.err))
  482. } else {
  483. return int(resp.num_devices), &resp.ch, libPath
  484. }
  485. }
  486. return 0, nil, ""
  487. }
  488. func LoadNVCUDAMgmt(nvcudaLibPaths []string) (int, *C.nvcuda_handle_t, string) {
  489. var resp C.nvcuda_init_resp_t
  490. resp.ch.verbose = getVerboseState()
  491. for _, libPath := range nvcudaLibPaths {
  492. lib := C.CString(libPath)
  493. defer C.free(unsafe.Pointer(lib))
  494. C.nvcuda_init(lib, &resp)
  495. if resp.err != nil {
  496. // Decide what log level based on the type of error message to help users understand why
  497. msg := C.GoString(resp.err)
  498. switch resp.cudaErr {
  499. case C.CUDA_ERROR_INSUFFICIENT_DRIVER, C.CUDA_ERROR_SYSTEM_DRIVER_MISMATCH:
  500. slog.Warn("version mismatch between driver and cuda driver library - reboot or upgrade may be required", "library", libPath, "error", msg)
  501. case C.CUDA_ERROR_NO_DEVICE:
  502. slog.Info("no nvidia devices detected", "library", libPath)
  503. case C.CUDA_ERROR_UNKNOWN:
  504. slog.Warn("unknown error initializing cuda driver library", "library", libPath, "error", msg)
  505. slog.Warn("see https://github.com/ollama/ollama/blob/main/docs/troubleshooting.md for more information")
  506. default:
  507. if strings.Contains(msg, "wrong ELF class") {
  508. slog.Debug("skipping 32bit library", "library", libPath)
  509. } else {
  510. slog.Info("unable to load cuda driver library", "library", libPath, "error", msg)
  511. }
  512. }
  513. C.free(unsafe.Pointer(resp.err))
  514. } else {
  515. return int(resp.num_devices), &resp.ch, libPath
  516. }
  517. }
  518. return 0, nil, ""
  519. }
  520. func LoadNVMLMgmt(nvmlLibPaths []string) (*C.nvml_handle_t, string) {
  521. var resp C.nvml_init_resp_t
  522. resp.ch.verbose = getVerboseState()
  523. for _, libPath := range nvmlLibPaths {
  524. lib := C.CString(libPath)
  525. defer C.free(unsafe.Pointer(lib))
  526. C.nvml_init(lib, &resp)
  527. if resp.err != nil {
  528. slog.Info(fmt.Sprintf("Unable to load NVML management library %s: %s", libPath, C.GoString(resp.err)))
  529. C.free(unsafe.Pointer(resp.err))
  530. } else {
  531. return &resp.ch, libPath
  532. }
  533. }
  534. return nil, ""
  535. }
  536. func LoadOneapiMgmt(oneapiLibPaths []string) (int, *C.oneapi_handle_t, string) {
  537. var resp C.oneapi_init_resp_t
  538. num_devices := 0
  539. resp.oh.verbose = getVerboseState()
  540. for _, libPath := range oneapiLibPaths {
  541. lib := C.CString(libPath)
  542. defer C.free(unsafe.Pointer(lib))
  543. C.oneapi_init(lib, &resp)
  544. if resp.err != nil {
  545. slog.Debug("Unable to load oneAPI management library", "library", libPath, "error", C.GoString(resp.err))
  546. C.free(unsafe.Pointer(resp.err))
  547. } else {
  548. for i := range resp.oh.num_drivers {
  549. num_devices += int(C.oneapi_get_device_count(resp.oh, C.int(i)))
  550. }
  551. return num_devices, &resp.oh, libPath
  552. }
  553. }
  554. return 0, nil, ""
  555. }
  556. func getVerboseState() C.uint16_t {
  557. if envconfig.Debug {
  558. return C.uint16_t(1)
  559. }
  560. return C.uint16_t(0)
  561. }
  562. // Given the list of GPUs this instantiation is targeted for,
  563. // figure out the visible devices environment variable
  564. //
  565. // If different libraries are detected, the first one is what we use
  566. func (l GpuInfoList) GetVisibleDevicesEnv() (string, string) {
  567. if len(l) == 0 {
  568. return "", ""
  569. }
  570. switch l[0].Library {
  571. case "cuda":
  572. return cudaGetVisibleDevicesEnv(l)
  573. case "rocm":
  574. return rocmGetVisibleDevicesEnv(l)
  575. case "oneapi":
  576. return oneapiGetVisibleDevicesEnv(l)
  577. default:
  578. slog.Debug("no filter required for library " + l[0].Library)
  579. return "", ""
  580. }
  581. }