gpu.go 22 KB

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