gpu.go 22 KB

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