payload_common.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. // delete the assetsDir
  102. if err := os.RemoveAll(assetsDir); err != nil {
  103. return err
  104. }
  105. if runtime.GOOS == "darwin" {
  106. err := extractPayloadFiles(assetsDir, "llama.cpp/ggml-metal.metal")
  107. if err != nil {
  108. if err == payloadMissing {
  109. // TODO perhaps consider this a hard failure on arm macs?
  110. slog.Info("ggml-meta.metal payload missing")
  111. return nil
  112. }
  113. return err
  114. }
  115. os.Setenv("GGML_METAL_PATH_RESOURCES", assetsDir)
  116. }
  117. libs, err := extractDynamicLibs(assetsDir, "llama.cpp/build/*/*/*/lib/*")
  118. if err != nil {
  119. if err == payloadMissing {
  120. slog.Info(fmt.Sprintf("%s", payloadMissing))
  121. return nil
  122. }
  123. return err
  124. }
  125. for _, lib := range libs {
  126. // The last dir component is the variant name
  127. variant := filepath.Base(filepath.Dir(lib))
  128. availableDynLibs[variant] = lib
  129. }
  130. if err := verifyDriverAccess(); err != nil {
  131. return err
  132. }
  133. // Report which dynamic libraries we have loaded to assist troubleshooting
  134. variants := make([]string, len(availableDynLibs))
  135. i := 0
  136. for variant := range availableDynLibs {
  137. variants[i] = variant
  138. i++
  139. }
  140. slog.Info(fmt.Sprintf("Dynamic LLM libraries %v", variants))
  141. slog.Debug("Override detection logic by setting OLLAMA_LLM_LIBRARY")
  142. return nil
  143. }
  144. func extractDynamicLibs(assetsDir, glob string) ([]string, error) {
  145. files, err := fs.Glob(libEmbed, glob)
  146. if err != nil || len(files) == 0 {
  147. return nil, payloadMissing
  148. }
  149. libs := []string{}
  150. g := new(errgroup.Group)
  151. for _, file := range files {
  152. pathComps := strings.Split(file, "/")
  153. if len(pathComps) != pathComponentCount {
  154. slog.Error(fmt.Sprintf("unexpected payload components: %v", pathComps))
  155. continue
  156. }
  157. file := file
  158. g.Go(func() error {
  159. // llama.cpp/build/$OS/$GOARCH/$VARIANT/lib/$LIBRARY
  160. // Include the variant in the path to avoid conflicts between multiple server libs
  161. targetDir := filepath.Join(assetsDir, pathComps[pathComponentCount-3])
  162. srcFile, err := libEmbed.Open(file)
  163. if err != nil {
  164. return fmt.Errorf("read payload %s: %v", file, err)
  165. }
  166. defer srcFile.Close()
  167. if err := os.MkdirAll(targetDir, 0o755); err != nil {
  168. return fmt.Errorf("create payload lib dir %s: %v", assetsDir, err)
  169. }
  170. src := io.Reader(srcFile)
  171. filename := file
  172. if strings.HasSuffix(file, ".gz") {
  173. src, err = gzip.NewReader(src)
  174. if err != nil {
  175. return fmt.Errorf("decompress payload %s: %v", file, err)
  176. }
  177. filename = strings.TrimSuffix(filename, ".gz")
  178. }
  179. destFile := filepath.Join(targetDir, filepath.Base(filename))
  180. if strings.Contains(destFile, "server") {
  181. libs = append(libs, destFile)
  182. }
  183. destFp, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
  184. if err != nil {
  185. return fmt.Errorf("write payload %s: %v", file, err)
  186. }
  187. defer destFp.Close()
  188. if _, err := io.Copy(destFp, src); err != nil {
  189. return fmt.Errorf("copy payload %s: %v", file, err)
  190. }
  191. return nil
  192. })
  193. }
  194. return libs, g.Wait()
  195. }
  196. func extractPayloadFiles(assetsDir, glob string) error {
  197. files, err := fs.Glob(libEmbed, glob)
  198. if err != nil || len(files) == 0 {
  199. return payloadMissing
  200. }
  201. for _, file := range files {
  202. srcFile, err := libEmbed.Open(file)
  203. if err != nil {
  204. return fmt.Errorf("read payload %s: %v", file, err)
  205. }
  206. defer srcFile.Close()
  207. if err := os.MkdirAll(assetsDir, 0o755); err != nil {
  208. return fmt.Errorf("create payload lib dir %s: %v", assetsDir, err)
  209. }
  210. src := io.Reader(srcFile)
  211. filename := file
  212. if strings.HasSuffix(file, ".gz") {
  213. src, err = gzip.NewReader(src)
  214. if err != nil {
  215. return fmt.Errorf("decompress payload %s: %v", file, err)
  216. }
  217. filename = strings.TrimSuffix(filename, ".gz")
  218. }
  219. destFile := filepath.Join(assetsDir, filepath.Base(filename))
  220. _, err = os.Stat(destFile)
  221. switch {
  222. case errors.Is(err, os.ErrNotExist):
  223. destFp, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
  224. if err != nil {
  225. return fmt.Errorf("write payload %s: %v", file, err)
  226. }
  227. defer destFp.Close()
  228. if _, err := io.Copy(destFp, src); err != nil {
  229. return fmt.Errorf("copy payload %s: %v", file, err)
  230. }
  231. case err != nil:
  232. return fmt.Errorf("stat payload %s: %v", file, err)
  233. case err == nil:
  234. slog.Debug("payload already exists: " + destFile)
  235. }
  236. }
  237. return nil
  238. }
  239. func verifyDriverAccess() error {
  240. if runtime.GOOS != "linux" {
  241. return nil
  242. }
  243. // Only check ROCm access if we have the dynamic lib loaded
  244. if rocmDynLibPresent() {
  245. // Verify we have permissions - either running as root, or we have group access to the driver
  246. fd, err := os.OpenFile("/dev/kfd", os.O_RDWR, 0666)
  247. if err != nil {
  248. if errors.Is(err, fs.ErrPermission) {
  249. 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.")
  250. } else if errors.Is(err, fs.ErrNotExist) {
  251. // expected behavior without a radeon card
  252. return nil
  253. }
  254. return fmt.Errorf("failed to check permission on /dev/kfd: %w", err)
  255. }
  256. fd.Close()
  257. }
  258. return nil
  259. }