payload_common.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. payloadsDir, err := gpu.PayloadsDir()
  97. if err != nil {
  98. return err
  99. }
  100. slog.Info(fmt.Sprintf("Extracting dynamic libraries to %s ...", payloadsDir))
  101. libs, err := extractDynamicLibs(payloadsDir, "llama.cpp/build/*/*/*/lib/*")
  102. if err != nil {
  103. if err == payloadMissing {
  104. slog.Info(fmt.Sprintf("%s", payloadMissing))
  105. return nil
  106. }
  107. return err
  108. }
  109. for _, lib := range libs {
  110. // The last dir component is the variant name
  111. variant := filepath.Base(filepath.Dir(lib))
  112. availableDynLibs[variant] = lib
  113. }
  114. if err := verifyDriverAccess(); err != nil {
  115. return err
  116. }
  117. // Report which dynamic libraries we have loaded to assist troubleshooting
  118. variants := make([]string, len(availableDynLibs))
  119. i := 0
  120. for variant := range availableDynLibs {
  121. variants[i] = variant
  122. i++
  123. }
  124. slog.Info(fmt.Sprintf("Dynamic LLM libraries %v", variants))
  125. slog.Debug("Override detection logic by setting OLLAMA_LLM_LIBRARY")
  126. return nil
  127. }
  128. func extractDynamicLibs(payloadsDir, glob string) ([]string, error) {
  129. files, err := fs.Glob(libEmbed, glob)
  130. if err != nil || len(files) == 0 {
  131. return nil, payloadMissing
  132. }
  133. libs := []string{}
  134. g := new(errgroup.Group)
  135. for _, file := range files {
  136. pathComps := strings.Split(file, "/")
  137. if len(pathComps) != pathComponentCount {
  138. slog.Error(fmt.Sprintf("unexpected payload components: %v", pathComps))
  139. continue
  140. }
  141. file := file
  142. g.Go(func() error {
  143. // llama.cpp/build/$OS/$GOARCH/$VARIANT/lib/$LIBRARY
  144. // Include the variant in the path to avoid conflicts between multiple server libs
  145. targetDir := filepath.Join(payloadsDir, pathComps[pathComponentCount-3])
  146. srcFile, err := libEmbed.Open(file)
  147. if err != nil {
  148. return fmt.Errorf("read payload %s: %v", file, err)
  149. }
  150. defer srcFile.Close()
  151. if err := os.MkdirAll(targetDir, 0o755); err != nil {
  152. return fmt.Errorf("create payload lib dir %s: %v", payloadsDir, err)
  153. }
  154. src := io.Reader(srcFile)
  155. filename := file
  156. if strings.HasSuffix(file, ".gz") {
  157. src, err = gzip.NewReader(src)
  158. if err != nil {
  159. return fmt.Errorf("decompress payload %s: %v", file, err)
  160. }
  161. filename = strings.TrimSuffix(filename, ".gz")
  162. }
  163. destFile := filepath.Join(targetDir, filepath.Base(filename))
  164. if strings.Contains(destFile, "server") {
  165. libs = append(libs, destFile)
  166. }
  167. destFp, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
  168. if err != nil {
  169. return fmt.Errorf("write payload %s: %v", file, err)
  170. }
  171. defer destFp.Close()
  172. if _, err := io.Copy(destFp, src); err != nil {
  173. return fmt.Errorf("copy payload %s: %v", file, err)
  174. }
  175. return nil
  176. })
  177. }
  178. return libs, g.Wait()
  179. }
  180. func verifyDriverAccess() error {
  181. if runtime.GOOS != "linux" {
  182. return nil
  183. }
  184. // Only check ROCm access if we have the dynamic lib loaded
  185. if rocmDynLibPresent() {
  186. // Verify we have permissions - either running as root, or we have group access to the driver
  187. fd, err := os.OpenFile("/dev/kfd", os.O_RDWR, 0666)
  188. if err != nil {
  189. if errors.Is(err, fs.ErrPermission) {
  190. 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.")
  191. } else if errors.Is(err, fs.ErrNotExist) {
  192. // expected behavior without a radeon card
  193. return nil
  194. }
  195. return fmt.Errorf("failed to check permission on /dev/kfd: %w", err)
  196. }
  197. fd.Close()
  198. }
  199. return nil
  200. }