gpu.go 20 KB

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