payload_common.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package llm
  2. import (
  3. "compress/gzip"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "io/fs"
  8. "log/slog"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. "golang.org/x/exp/slices"
  14. "golang.org/x/sync/errgroup"
  15. "github.com/jmorganca/ollama/gpu"
  16. )
  17. // Libraries names may contain an optional variant separated by '_'
  18. // For example, "rocm_v6" and "rocm_v5" or "cpu" and "cpu_avx2"
  19. // Any library without a variant is the lowest common denominator
  20. var availableDynLibs = map[string]string{}
  21. const pathComponentCount = 7
  22. // getDynLibs returns an ordered list of LLM libraries to try, starting with the best
  23. func getDynLibs(gpuInfo gpu.GpuInfo) []string {
  24. // Short circuit if we know we're using the default built-in (darwin only)
  25. if gpuInfo.Library == "default" {
  26. return []string{"default"}
  27. }
  28. // TODO - temporary until we have multiple CPU variations for Darwin
  29. // Short circuit on darwin with metal only
  30. if len(availableDynLibs) == 1 {
  31. if _, onlyMetal := availableDynLibs["metal"]; onlyMetal {
  32. return []string{availableDynLibs["metal"]}
  33. }
  34. }
  35. exactMatch := ""
  36. dynLibs := []string{}
  37. altDynLibs := []string{}
  38. requested := gpuInfo.Library
  39. if gpuInfo.Variant != "" {
  40. requested += "_" + gpuInfo.Variant
  41. }
  42. // Try to find an exact match
  43. for cmp := range availableDynLibs {
  44. if requested == cmp {
  45. exactMatch = cmp
  46. dynLibs = []string{availableDynLibs[cmp]}
  47. break
  48. }
  49. }
  50. // Then for GPUs load alternates and sort the list for consistent load ordering
  51. if gpuInfo.Library != "cpu" {
  52. for cmp := range availableDynLibs {
  53. if gpuInfo.Library == strings.Split(cmp, "_")[0] && cmp != exactMatch {
  54. altDynLibs = append(altDynLibs, cmp)
  55. }
  56. }
  57. slices.Sort(altDynLibs)
  58. for _, altDynLib := range altDynLibs {
  59. dynLibs = append(dynLibs, availableDynLibs[altDynLib])
  60. }
  61. }
  62. // Load up the best CPU variant if not primary requested
  63. if gpuInfo.Library != "cpu" {
  64. variant := gpu.GetCPUVariant()
  65. // If no variant, then we fall back to default
  66. // If we have a variant, try that if we find an exact match
  67. // Attempting to run the wrong CPU instructions will panic the
  68. // process
  69. if variant != "" {
  70. for cmp := range availableDynLibs {
  71. if cmp == "cpu_"+variant {
  72. dynLibs = append(dynLibs, availableDynLibs[cmp])
  73. break
  74. }
  75. }
  76. } else {
  77. dynLibs = append(dynLibs, availableDynLibs["cpu"])
  78. }
  79. }
  80. // Finally, if we didn't find any matches, LCD CPU FTW
  81. if len(dynLibs) == 0 {
  82. dynLibs = []string{availableDynLibs["cpu"]}
  83. }
  84. slog.Debug(fmt.Sprintf("ordered list of LLM libraries to try %v", dynLibs))
  85. return dynLibs
  86. }
  87. func rocmDynLibPresent() bool {
  88. for dynLibName := range availableDynLibs {
  89. if strings.HasPrefix(dynLibName, "rocm") {
  90. return true
  91. }
  92. }
  93. return false
  94. }
  95. func nativeInit() error {
  96. slog.Info("Extracting dynamic libraries...")
  97. assetsDir, err := gpu.AssetsDir()
  98. if err != nil {
  99. return err
  100. }
  101. if runtime.GOOS == "darwin" {
  102. err := extractPayloadFiles(assetsDir, "llama.cpp/ggml-metal.metal")
  103. if err != nil {
  104. if err == payloadMissing {
  105. // TODO perhaps consider this a hard failure on arm macs?
  106. slog.Info("ggml-meta.metal payload missing")
  107. return nil
  108. }
  109. return err
  110. }
  111. os.Setenv("GGML_METAL_PATH_RESOURCES", assetsDir)
  112. }
  113. libs, err := extractDynamicLibs(assetsDir, "llama.cpp/build/*/*/*/lib/*")
  114. if err != nil {
  115. if err == payloadMissing {
  116. slog.Info(fmt.Sprintf("%s", payloadMissing))
  117. return nil
  118. }
  119. return err
  120. }
  121. for _, lib := range libs {
  122. // The last dir component is the variant name
  123. variant := filepath.Base(filepath.Dir(lib))
  124. availableDynLibs[variant] = lib
  125. }
  126. if err := verifyDriverAccess(); err != nil {
  127. return err
  128. }
  129. // Report which dynamic libraries we have loaded to assist troubleshooting
  130. variants := make([]string, len(availableDynLibs))
  131. i := 0
  132. for variant := range availableDynLibs {
  133. variants[i] = variant
  134. i++
  135. }
  136. slog.Info(fmt.Sprintf("Dynamic LLM libraries %v", variants))
  137. slog.Debug("Override detection logic by setting OLLAMA_LLM_LIBRARY")
  138. return nil
  139. }
  140. func extractDynamicLibs(assetsDir, glob string) ([]string, error) {
  141. files, err := fs.Glob(libEmbed, glob)
  142. if err != nil || len(files) == 0 {
  143. return nil, payloadMissing
  144. }
  145. libs := []string{}
  146. g := new(errgroup.Group)
  147. for _, file := range files {
  148. pathComps := strings.Split(file, "/")
  149. if len(pathComps) != pathComponentCount {
  150. slog.Error(fmt.Sprintf("unexpected payload components: %v", pathComps))
  151. continue
  152. }
  153. file := file
  154. g.Go(func() error {
  155. // llama.cpp/build/$OS/$GOARCH/$VARIANT/lib/$LIBRARY
  156. // Include the variant in the path to avoid conflicts between multiple server libs
  157. targetDir := filepath.Join(assetsDir, pathComps[pathComponentCount-3])
  158. srcFile, err := libEmbed.Open(file)
  159. if err != nil {
  160. return fmt.Errorf("read payload %s: %v", file, err)
  161. }
  162. defer srcFile.Close()
  163. if err := os.MkdirAll(targetDir, 0o755); err != nil {
  164. return fmt.Errorf("create payload lib dir %s: %v", assetsDir, err)
  165. }
  166. src := io.Reader(srcFile)
  167. filename := file
  168. if strings.HasSuffix(file, ".gz") {
  169. src, err = gzip.NewReader(src)
  170. if err != nil {
  171. return fmt.Errorf("decompress payload %s: %v", file, err)
  172. }
  173. filename = strings.TrimSuffix(filename, ".gz")
  174. }
  175. destFile := filepath.Join(targetDir, filepath.Base(filename))
  176. if strings.Contains(destFile, "server") {
  177. libs = append(libs, destFile)
  178. }
  179. destFp, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
  180. if err != nil {
  181. return fmt.Errorf("write payload %s: %v", file, err)
  182. }
  183. defer destFp.Close()
  184. if _, err := io.Copy(destFp, src); err != nil {
  185. return fmt.Errorf("copy payload %s: %v", file, err)
  186. }
  187. return nil
  188. })
  189. }
  190. return libs, g.Wait()
  191. }
  192. func extractPayloadFiles(assetsDir, glob string) error {
  193. files, err := fs.Glob(libEmbed, glob)
  194. if err != nil || len(files) == 0 {
  195. return payloadMissing
  196. }
  197. for _, file := range files {
  198. srcFile, err := libEmbed.Open(file)
  199. if err != nil {
  200. return fmt.Errorf("read payload %s: %v", file, err)
  201. }
  202. defer srcFile.Close()
  203. if err := os.MkdirAll(assetsDir, 0o755); err != nil {
  204. return fmt.Errorf("create payload lib dir %s: %v", assetsDir, err)
  205. }
  206. src := io.Reader(srcFile)
  207. filename := file
  208. if strings.HasSuffix(file, ".gz") {
  209. src, err = gzip.NewReader(src)
  210. if err != nil {
  211. return fmt.Errorf("decompress payload %s: %v", file, err)
  212. }
  213. filename = strings.TrimSuffix(filename, ".gz")
  214. }
  215. destFile := filepath.Join(assetsDir, filepath.Base(filename))
  216. _, err = os.Stat(destFile)
  217. switch {
  218. case errors.Is(err, os.ErrNotExist):
  219. destFp, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
  220. if err != nil {
  221. return fmt.Errorf("write payload %s: %v", file, err)
  222. }
  223. defer destFp.Close()
  224. if _, err := io.Copy(destFp, src); err != nil {
  225. return fmt.Errorf("copy payload %s: %v", file, err)
  226. }
  227. case err != nil:
  228. return fmt.Errorf("stat payload %s: %v", file, err)
  229. case err == nil:
  230. slog.Debug("payload already exists: " + destFile)
  231. }
  232. }
  233. return nil
  234. }
  235. func verifyDriverAccess() error {
  236. if runtime.GOOS != "linux" {
  237. return nil
  238. }
  239. // Only check ROCm access if we have the dynamic lib loaded
  240. if rocmDynLibPresent() {
  241. // Verify we have permissions - either running as root, or we have group access to the driver
  242. fd, err := os.OpenFile("/dev/kfd", os.O_RDWR, 0666)
  243. if err != nil {
  244. if errors.Is(err, fs.ErrPermission) {
  245. return fmt.Errorf("Radeon card detected, but permissions not set up properly. Either run ollama as root, or add you user account to the render group.")
  246. } else if errors.Is(err, fs.ErrNotExist) {
  247. // expected behavior without a radeon card
  248. return nil
  249. }
  250. return fmt.Errorf("failed to check permission on /dev/kfd: %w", err)
  251. }
  252. fd.Close()
  253. }
  254. return nil
  255. }