shim_ext_server.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. //go:build !darwin
  2. package llm
  3. /*
  4. #include <stdlib.h>
  5. #include "dynamic_shim.h"
  6. */
  7. import "C"
  8. import (
  9. "context"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "io/fs"
  14. "log"
  15. "os"
  16. "path/filepath"
  17. "strings"
  18. "sync"
  19. "unsafe"
  20. "github.com/jmorganca/ollama/api"
  21. )
  22. type shimExtServer struct {
  23. s C.struct_dynamic_llama_server
  24. options api.Options
  25. }
  26. // Note: current implementation does not support concurrent instantiations
  27. var shimMutex sync.Mutex
  28. var llm *shimExtServer
  29. const pathComponentCount = 6
  30. func (llm *shimExtServer) llama_server_init(sparams *C.ext_server_params_t, err *C.ext_server_resp_t) {
  31. C.dynamic_shim_llama_server_init(llm.s, sparams, err)
  32. }
  33. func (llm *shimExtServer) llama_server_start() {
  34. C.dynamic_shim_llama_server_start(llm.s)
  35. }
  36. func (llm *shimExtServer) llama_server_stop() {
  37. C.dynamic_shim_llama_server_stop(llm.s)
  38. }
  39. func (llm *shimExtServer) llama_server_completion(json_req *C.char, resp *C.ext_server_resp_t) {
  40. C.dynamic_shim_llama_server_completion(llm.s, json_req, resp)
  41. }
  42. func (llm *shimExtServer) llama_server_completion_next_result(task_id C.int, resp *C.ext_server_task_result_t) {
  43. C.dynamic_shim_llama_server_completion_next_result(llm.s, task_id, resp)
  44. }
  45. func (llm *shimExtServer) llama_server_completion_cancel(task_id C.int, err *C.ext_server_resp_t) {
  46. C.dynamic_shim_llama_server_completion_cancel(llm.s, task_id, err)
  47. }
  48. func (llm *shimExtServer) llama_server_release_task_result(result *C.ext_server_task_result_t) {
  49. C.dynamic_shim_llama_server_release_task_result(llm.s, result)
  50. }
  51. func (llm *shimExtServer) llama_server_tokenize(json_req *C.char, json_resp **C.char, err *C.ext_server_resp_t) {
  52. C.dynamic_shim_llama_server_tokenize(llm.s, json_req, json_resp, err)
  53. }
  54. func (llm *shimExtServer) llama_server_detokenize(json_req *C.char, json_resp **C.char, err *C.ext_server_resp_t) {
  55. C.dynamic_shim_llama_server_detokenize(llm.s, json_req, json_resp, err)
  56. }
  57. func (llm *shimExtServer) llama_server_embedding(json_req *C.char, json_resp **C.char, err *C.ext_server_resp_t) {
  58. C.dynamic_shim_llama_server_embedding(llm.s, json_req, json_resp, err)
  59. }
  60. func (llm *shimExtServer) llama_server_release_json_resp(json_resp **C.char) {
  61. C.dynamic_shim_llama_server_release_json_resp(llm.s, json_resp)
  62. }
  63. func newDynamicShimExtServer(library, model string, adapters, projectors []string, numLayers int64, opts api.Options) (extServer, error) {
  64. shimMutex.Lock()
  65. defer shimMutex.Unlock()
  66. updatePath(filepath.Dir(library))
  67. libPath := C.CString(library)
  68. defer C.free(unsafe.Pointer(libPath))
  69. resp := newExtServerResp(128)
  70. defer freeExtServerResp(resp)
  71. var srv C.struct_dynamic_llama_server
  72. C.dynamic_shim_init(libPath, &srv, &resp)
  73. if resp.id < 0 {
  74. return nil, fmt.Errorf("Unable to load dynamic library: %s", C.GoString(resp.msg))
  75. }
  76. llm = &shimExtServer{
  77. s: srv,
  78. options: opts,
  79. }
  80. log.Printf("Loading Dynamic Shim llm server: %s", library)
  81. return newExtServer(llm, model, adapters, projectors, numLayers, opts)
  82. }
  83. func (llm *shimExtServer) Predict(ctx context.Context, pred PredictOpts, fn func(PredictResult)) error {
  84. return predict(ctx, llm, pred, fn)
  85. }
  86. func (llm *shimExtServer) Encode(ctx context.Context, prompt string) ([]int, error) {
  87. return encode(llm, ctx, prompt)
  88. }
  89. func (llm *shimExtServer) Decode(ctx context.Context, tokens []int) (string, error) {
  90. return decode(llm, ctx, tokens)
  91. }
  92. func (llm *shimExtServer) Embedding(ctx context.Context, input string) ([]float64, error) {
  93. return embedding(llm, ctx, input)
  94. }
  95. func (llm *shimExtServer) Close() {
  96. close(llm)
  97. }
  98. func nativeInit(workdir string) error {
  99. libs, err := extractDynamicLibs(workdir, "llama.cpp/build/*/*/lib/*")
  100. if err != nil {
  101. if err == payloadMissing {
  102. log.Printf("%s", payloadMissing)
  103. return nil
  104. }
  105. return err
  106. }
  107. for _, lib := range libs {
  108. // The last dir component is the variant name
  109. variant := filepath.Base(filepath.Dir(lib))
  110. AvailableShims[variant] = lib
  111. }
  112. if err := verifyDriverAccess(); err != nil {
  113. return err
  114. }
  115. // Report which dynamic libraries we have loaded to assist troubleshooting
  116. variants := make([]string, len(AvailableShims))
  117. i := 0
  118. for variant := range AvailableShims {
  119. variants[i] = variant
  120. i++
  121. }
  122. log.Printf("Dynamic LLM variants %v", variants)
  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. }