payload_common.go 6.6 KB

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