payload_common.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. return dynLibs
  85. }
  86. func rocmDynLibPresent() bool {
  87. for dynLibName := range availableDynLibs {
  88. if strings.HasPrefix(dynLibName, "rocm") {
  89. return true
  90. }
  91. }
  92. return false
  93. }
  94. func nativeInit(workdir string) error {
  95. slog.Info("Extracting dynamic libraries...")
  96. if runtime.GOOS == "darwin" {
  97. err := extractPayloadFiles(workdir, "llama.cpp/ggml-metal.metal")
  98. if err != nil {
  99. if err == payloadMissing {
  100. // TODO perhaps consider this a hard failure on arm macs?
  101. slog.Info("ggml-meta.metal payload missing")
  102. return nil
  103. }
  104. return err
  105. }
  106. os.Setenv("GGML_METAL_PATH_RESOURCES", workdir)
  107. }
  108. libs, err := extractDynamicLibs(workdir, "llama.cpp/build/*/*/*/lib/*")
  109. if err != nil {
  110. if err == payloadMissing {
  111. slog.Info(fmt.Sprintf("%s", payloadMissing))
  112. return nil
  113. }
  114. return err
  115. }
  116. for _, lib := range libs {
  117. // The last dir component is the variant name
  118. variant := filepath.Base(filepath.Dir(lib))
  119. availableDynLibs[variant] = lib
  120. }
  121. if err := verifyDriverAccess(); err != nil {
  122. return err
  123. }
  124. // Report which dynamic libraries we have loaded to assist troubleshooting
  125. variants := make([]string, len(availableDynLibs))
  126. i := 0
  127. for variant := range availableDynLibs {
  128. variants[i] = variant
  129. i++
  130. }
  131. slog.Info(fmt.Sprintf("Dynamic LLM libraries %v", variants))
  132. slog.Debug("Override detection logic by setting OLLAMA_LLM_LIBRARY")
  133. return nil
  134. }
  135. func extractDynamicLibs(workDir, glob string) ([]string, error) {
  136. files, err := fs.Glob(libEmbed, glob)
  137. if err != nil || len(files) == 0 {
  138. return nil, payloadMissing
  139. }
  140. libs := []string{}
  141. // TODO consider making this idempotent with some sort of persistent directory (where we store models probably)
  142. // and tracking by version so we don't reexpand the files every time
  143. // Also maybe consider lazy loading only what is needed
  144. g := new(errgroup.Group)
  145. for _, file := range files {
  146. pathComps := strings.Split(file, "/")
  147. if len(pathComps) != pathComponentCount {
  148. slog.Error(fmt.Sprintf("unexpected payload components: %v", pathComps))
  149. continue
  150. }
  151. file := file
  152. g.Go(func() error {
  153. // llama.cpp/build/$OS/$GOARCH/$VARIANT/lib/$LIBRARY
  154. // Include the variant in the path to avoid conflicts between multiple server libs
  155. targetDir := filepath.Join(workDir, pathComps[pathComponentCount-3])
  156. srcFile, err := libEmbed.Open(file)
  157. if err != nil {
  158. return fmt.Errorf("read payload %s: %v", file, err)
  159. }
  160. defer srcFile.Close()
  161. if err := os.MkdirAll(targetDir, 0o755); err != nil {
  162. return fmt.Errorf("create payload temp dir %s: %v", workDir, err)
  163. }
  164. src := io.Reader(srcFile)
  165. filename := file
  166. if strings.HasSuffix(file, ".gz") {
  167. src, err = gzip.NewReader(src)
  168. if err != nil {
  169. return fmt.Errorf("decompress payload %s: %v", file, err)
  170. }
  171. filename = strings.TrimSuffix(filename, ".gz")
  172. }
  173. destFile := filepath.Join(targetDir, filepath.Base(filename))
  174. if strings.Contains(destFile, "server") {
  175. libs = append(libs, destFile)
  176. }
  177. _, err = os.Stat(destFile)
  178. switch {
  179. case errors.Is(err, os.ErrNotExist):
  180. destFile, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
  181. if err != nil {
  182. return fmt.Errorf("write payload %s: %v", file, err)
  183. }
  184. defer destFile.Close()
  185. if _, err := io.Copy(destFile, src); err != nil {
  186. return fmt.Errorf("copy payload %s: %v", file, err)
  187. }
  188. case err != nil:
  189. return fmt.Errorf("stat payload %s: %v", file, err)
  190. }
  191. return nil
  192. })
  193. }
  194. return libs, g.Wait()
  195. }
  196. func extractPayloadFiles(workDir, 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(workDir, 0o755); err != nil {
  208. return fmt.Errorf("create payload temp dir %s: %v", workDir, 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(workDir, filepath.Base(filename))
  220. _, err = os.Stat(destFile)
  221. switch {
  222. case errors.Is(err, os.ErrNotExist):
  223. destFile, 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 destFile.Close()
  228. if _, err := io.Copy(destFile, 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. }
  234. }
  235. return nil
  236. }
  237. func verifyDriverAccess() error {
  238. if runtime.GOOS != "linux" {
  239. return nil
  240. }
  241. // Only check ROCm access if we have the dynamic lib loaded
  242. if rocmDynLibPresent() {
  243. // Verify we have permissions - either running as root, or we have group access to the driver
  244. fd, err := os.OpenFile("/dev/kfd", os.O_RDWR, 0666)
  245. if err != nil {
  246. if errors.Is(err, fs.ErrPermission) {
  247. 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.")
  248. } else if errors.Is(err, fs.ErrNotExist) {
  249. // expected behavior without a radeon card
  250. return nil
  251. }
  252. return fmt.Errorf("failed to check permission on /dev/kfd: %w", err)
  253. }
  254. fd.Close()
  255. }
  256. return nil
  257. }