gpu.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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/format"
  19. "github.com/ollama/ollama/server/envconfig"
  20. )
  21. type handles struct {
  22. deviceCount int
  23. cudart *C.cudart_handle_t
  24. }
  25. const (
  26. cudaMinimumMemory = 457 * format.MebiByte
  27. rocmMinimumMemory = 457 * format.MebiByte
  28. )
  29. var gpuMutex sync.Mutex
  30. // With our current CUDA compile flags, older than 5.0 will not work properly
  31. var CudaComputeMin = [2]C.int{5, 0}
  32. var RocmComputeMin = 9
  33. // TODO find a better way to detect iGPU instead of minimum memory
  34. const IGPUMemLimit = 1 * format.GibiByte // 512G is what they typically report, so anything less than 1G must be iGPU
  35. var CudartLinuxGlobs = []string{
  36. "/usr/local/cuda/lib64/libcudart.so*",
  37. "/usr/lib/x86_64-linux-gnu/nvidia/current/libcudart.so*",
  38. "/usr/lib/x86_64-linux-gnu/libcudart.so*",
  39. "/usr/lib/wsl/lib/libcudart.so*",
  40. "/usr/lib/wsl/drivers/*/libcudart.so*",
  41. "/opt/cuda/lib64/libcudart.so*",
  42. "/usr/local/cuda*/targets/aarch64-linux/lib/libcudart.so*",
  43. "/usr/lib/aarch64-linux-gnu/nvidia/current/libcudart.so*",
  44. "/usr/lib/aarch64-linux-gnu/libcudart.so*",
  45. "/usr/local/cuda/lib*/libcudart.so*",
  46. "/usr/lib*/libcudart.so*",
  47. "/usr/local/lib*/libcudart.so*",
  48. }
  49. var CudartWindowsGlobs = []string{
  50. "c:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v*\\bin\\cudart64_*.dll",
  51. }
  52. // Jetson devices have JETSON_JETPACK="x.y.z" factory set to the Jetpack version installed.
  53. // Included to drive logic for reducing Ollama-allocated overhead on L4T/Jetson devices.
  54. var CudaTegra string = os.Getenv("JETSON_JETPACK")
  55. // Note: gpuMutex must already be held
  56. func initGPUHandles() *handles {
  57. // TODO - if the ollama build is CPU only, don't do these checks as they're irrelevant and confusing
  58. gpuHandles := &handles{}
  59. var cudartMgmtName string
  60. var cudartMgmtPatterns []string
  61. tmpDir, _ := PayloadsDir()
  62. switch runtime.GOOS {
  63. case "windows":
  64. cudartMgmtName = "cudart64_*.dll"
  65. localAppData := os.Getenv("LOCALAPPDATA")
  66. cudartMgmtPatterns = []string{filepath.Join(localAppData, "Programs", "Ollama", cudartMgmtName)}
  67. cudartMgmtPatterns = append(cudartMgmtPatterns, CudartWindowsGlobs...)
  68. case "linux":
  69. cudartMgmtName = "libcudart.so*"
  70. if tmpDir != "" {
  71. // TODO - add "payloads" for subprocess
  72. cudartMgmtPatterns = []string{filepath.Join(tmpDir, "cuda*", cudartMgmtName)}
  73. }
  74. cudartMgmtPatterns = append(cudartMgmtPatterns, CudartLinuxGlobs...)
  75. default:
  76. return gpuHandles
  77. }
  78. slog.Info("Detecting GPUs")
  79. cudartLibPaths := FindGPULibs(cudartMgmtName, cudartMgmtPatterns)
  80. if len(cudartLibPaths) > 0 {
  81. deviceCount, cudart, libPath := LoadCUDARTMgmt(cudartLibPaths)
  82. if cudart != nil {
  83. slog.Info("detected GPUs", "library", libPath, "count", deviceCount)
  84. gpuHandles.cudart = cudart
  85. gpuHandles.deviceCount = deviceCount
  86. return gpuHandles
  87. }
  88. }
  89. return gpuHandles
  90. }
  91. func GetGPUInfo() GpuInfoList {
  92. // TODO - consider exploring lspci (and equivalent on windows) to check for
  93. // GPUs so we can report warnings if we see Nvidia/AMD but fail to load the libraries
  94. gpuMutex.Lock()
  95. defer gpuMutex.Unlock()
  96. gpuHandles := initGPUHandles()
  97. defer func() {
  98. if gpuHandles.cudart != nil {
  99. C.cudart_release(*gpuHandles.cudart)
  100. }
  101. }()
  102. // All our GPU builds on x86 have AVX enabled, so fallback to CPU if we don't detect at least AVX
  103. cpuVariant := GetCPUVariant()
  104. if cpuVariant == "" && runtime.GOARCH == "amd64" {
  105. slog.Warn("CPU does not have AVX or AVX2, disabling GPU support.")
  106. }
  107. var memInfo C.mem_info_t
  108. resp := []GpuInfo{}
  109. // NVIDIA first
  110. for i := 0; i < gpuHandles.deviceCount; i++ {
  111. // TODO once we support CPU compilation variants of GPU libraries refine this...
  112. if cpuVariant == "" && runtime.GOARCH == "amd64" {
  113. continue
  114. }
  115. gpuInfo := GpuInfo{
  116. Library: "cuda",
  117. }
  118. C.cudart_check_vram(*gpuHandles.cudart, C.int(i), &memInfo)
  119. if memInfo.err != nil {
  120. slog.Info("error looking up nvidia GPU memory", "error", C.GoString(memInfo.err))
  121. C.free(unsafe.Pointer(memInfo.err))
  122. continue
  123. }
  124. if memInfo.major < CudaComputeMin[0] || (memInfo.major == CudaComputeMin[0] && memInfo.minor < CudaComputeMin[1]) {
  125. slog.Info(fmt.Sprintf("[%d] CUDA GPU is too old. Compute Capability detected: %d.%d", i, memInfo.major, memInfo.minor))
  126. continue
  127. }
  128. gpuInfo.TotalMemory = uint64(memInfo.total)
  129. gpuInfo.FreeMemory = uint64(memInfo.free)
  130. gpuInfo.ID = C.GoString(&memInfo.gpu_id[0])
  131. gpuInfo.Major = int(memInfo.major)
  132. gpuInfo.Minor = int(memInfo.minor)
  133. gpuInfo.MinimumMemory = cudaMinimumMemory
  134. // TODO potentially sort on our own algorithm instead of what the underlying GPU library does...
  135. resp = append(resp, gpuInfo)
  136. }
  137. // Then AMD
  138. resp = append(resp, AMDGetGPUInfo()...)
  139. if len(resp) == 0 {
  140. C.cpu_check_ram(&memInfo)
  141. if memInfo.err != nil {
  142. slog.Info("error looking up CPU memory", "error", C.GoString(memInfo.err))
  143. C.free(unsafe.Pointer(memInfo.err))
  144. return resp
  145. }
  146. gpuInfo := GpuInfo{
  147. Library: "cpu",
  148. Variant: cpuVariant,
  149. }
  150. gpuInfo.TotalMemory = uint64(memInfo.total)
  151. gpuInfo.FreeMemory = uint64(memInfo.free)
  152. gpuInfo.ID = C.GoString(&memInfo.gpu_id[0])
  153. resp = append(resp, gpuInfo)
  154. }
  155. return resp
  156. }
  157. func GetCPUMem() (memInfo, error) {
  158. var ret memInfo
  159. var info C.mem_info_t
  160. C.cpu_check_ram(&info)
  161. if info.err != nil {
  162. defer C.free(unsafe.Pointer(info.err))
  163. return ret, fmt.Errorf(C.GoString(info.err))
  164. }
  165. ret.FreeMemory = uint64(info.free)
  166. ret.TotalMemory = uint64(info.total)
  167. return ret, nil
  168. }
  169. func FindGPULibs(baseLibName string, patterns []string) []string {
  170. // Multiple GPU libraries may exist, and some may not work, so keep trying until we exhaust them
  171. var ldPaths []string
  172. gpuLibPaths := []string{}
  173. slog.Debug("Searching for GPU library", "name", baseLibName)
  174. switch runtime.GOOS {
  175. case "windows":
  176. ldPaths = strings.Split(os.Getenv("PATH"), ";")
  177. case "linux":
  178. ldPaths = strings.Split(os.Getenv("LD_LIBRARY_PATH"), ":")
  179. default:
  180. return gpuLibPaths
  181. }
  182. // Start with whatever we find in the PATH/LD_LIBRARY_PATH
  183. for _, ldPath := range ldPaths {
  184. d, err := filepath.Abs(ldPath)
  185. if err != nil {
  186. continue
  187. }
  188. patterns = append(patterns, filepath.Join(d, baseLibName+"*"))
  189. }
  190. slog.Debug("gpu library search", "globs", patterns)
  191. for _, pattern := range patterns {
  192. // Ignore glob discovery errors
  193. matches, _ := filepath.Glob(pattern)
  194. for _, match := range matches {
  195. // Resolve any links so we don't try the same lib multiple times
  196. // and weed out any dups across globs
  197. libPath := match
  198. tmp := match
  199. var err error
  200. for ; err == nil; tmp, err = os.Readlink(libPath) {
  201. if !filepath.IsAbs(tmp) {
  202. tmp = filepath.Join(filepath.Dir(libPath), tmp)
  203. }
  204. libPath = tmp
  205. }
  206. new := true
  207. for _, cmp := range gpuLibPaths {
  208. if cmp == libPath {
  209. new = false
  210. break
  211. }
  212. }
  213. if new {
  214. gpuLibPaths = append(gpuLibPaths, libPath)
  215. }
  216. }
  217. }
  218. slog.Debug("discovered GPU libraries", "paths", gpuLibPaths)
  219. return gpuLibPaths
  220. }
  221. func LoadCUDARTMgmt(cudartLibPaths []string) (int, *C.cudart_handle_t, string) {
  222. var resp C.cudart_init_resp_t
  223. resp.ch.verbose = getVerboseState()
  224. for _, libPath := range cudartLibPaths {
  225. lib := C.CString(libPath)
  226. defer C.free(unsafe.Pointer(lib))
  227. C.cudart_init(lib, &resp)
  228. if resp.err != nil {
  229. slog.Debug("Unable to load cudart", "library", libPath, "error", C.GoString(resp.err))
  230. C.free(unsafe.Pointer(resp.err))
  231. } else {
  232. return int(resp.num_devices), &resp.ch, libPath
  233. }
  234. }
  235. return 0, nil, ""
  236. }
  237. func getVerboseState() C.uint16_t {
  238. if envconfig.Debug {
  239. return C.uint16_t(1)
  240. }
  241. return C.uint16_t(0)
  242. }
  243. // Given the list of GPUs this instantiation is targeted for,
  244. // figure out the visible devices environment variable
  245. //
  246. // If different libraries are detected, the first one is what we use
  247. func (l GpuInfoList) GetVisibleDevicesEnv() (string, string) {
  248. if len(l) == 0 {
  249. return "", ""
  250. }
  251. switch l[0].Library {
  252. case "cuda":
  253. return cudaGetVisibleDevicesEnv(l)
  254. case "rocm":
  255. return rocmGetVisibleDevicesEnv(l)
  256. default:
  257. slog.Debug("no filter required for library " + l[0].Library)
  258. return "", ""
  259. }
  260. }