shim_ext_server.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. func (llm *shimExtServer) llama_server_init(sparams *C.ext_server_params_t, err *C.ext_server_resp_t) {
  30. C.dynamic_shim_llama_server_init(llm.s, sparams, err)
  31. }
  32. func (llm *shimExtServer) llama_server_start() {
  33. C.dynamic_shim_llama_server_start(llm.s)
  34. }
  35. func (llm *shimExtServer) llama_server_stop() {
  36. C.dynamic_shim_llama_server_stop(llm.s)
  37. }
  38. func (llm *shimExtServer) llama_server_completion(json_req *C.char, resp *C.ext_server_resp_t) {
  39. C.dynamic_shim_llama_server_completion(llm.s, json_req, resp)
  40. }
  41. func (llm *shimExtServer) llama_server_completion_next_result(task_id C.int, resp *C.ext_server_task_result_t) {
  42. C.dynamic_shim_llama_server_completion_next_result(llm.s, task_id, resp)
  43. }
  44. func (llm *shimExtServer) llama_server_completion_cancel(task_id C.int, err *C.ext_server_resp_t) {
  45. C.dynamic_shim_llama_server_completion_cancel(llm.s, task_id, err)
  46. }
  47. func (llm *shimExtServer) llama_server_release_task_result(result *C.ext_server_task_result_t) {
  48. C.dynamic_shim_llama_server_release_task_result(llm.s, result)
  49. }
  50. func (llm *shimExtServer) llama_server_tokenize(json_req *C.char, json_resp **C.char, err *C.ext_server_resp_t) {
  51. C.dynamic_shim_llama_server_tokenize(llm.s, json_req, json_resp, err)
  52. }
  53. func (llm *shimExtServer) llama_server_detokenize(json_req *C.char, json_resp **C.char, err *C.ext_server_resp_t) {
  54. C.dynamic_shim_llama_server_detokenize(llm.s, json_req, json_resp, err)
  55. }
  56. func (llm *shimExtServer) llama_server_embedding(json_req *C.char, json_resp **C.char, err *C.ext_server_resp_t) {
  57. C.dynamic_shim_llama_server_embedding(llm.s, json_req, json_resp, err)
  58. }
  59. func (llm *shimExtServer) llama_server_release_json_resp(json_resp **C.char) {
  60. C.dynamic_shim_llama_server_release_json_resp(llm.s, json_resp)
  61. }
  62. func newDynamicShimExtServer(library, model string, adapters, projectors []string, numLayers int64, opts api.Options) (extServer, error) {
  63. shimMutex.Lock()
  64. defer shimMutex.Unlock()
  65. updatePath(filepath.Dir(library))
  66. libPath := C.CString(library)
  67. defer C.free(unsafe.Pointer(libPath))
  68. resp := newExtServerResp(128)
  69. defer freeExtServerResp(resp)
  70. var srv C.struct_dynamic_llama_server
  71. C.dynamic_shim_init(libPath, &srv, &resp)
  72. if resp.id < 0 {
  73. return nil, fmt.Errorf("Unable to load dynamic library: %s", C.GoString(resp.msg))
  74. }
  75. llm = &shimExtServer{
  76. s: srv,
  77. options: opts,
  78. }
  79. log.Printf("Loading Dynamic Shim llm server: %s", library)
  80. return newExtServer(llm, model, adapters, projectors, numLayers, opts)
  81. }
  82. func (llm *shimExtServer) Predict(ctx context.Context, pred PredictOpts, fn func(PredictResult)) error {
  83. return predict(ctx, llm, pred, fn)
  84. }
  85. func (llm *shimExtServer) Encode(ctx context.Context, prompt string) ([]int, error) {
  86. return encode(llm, ctx, prompt)
  87. }
  88. func (llm *shimExtServer) Decode(ctx context.Context, tokens []int) (string, error) {
  89. return decode(llm, ctx, tokens)
  90. }
  91. func (llm *shimExtServer) Embedding(ctx context.Context, input string) ([]float64, error) {
  92. return embedding(llm, ctx, input)
  93. }
  94. func (llm *shimExtServer) Close() {
  95. close(llm)
  96. }
  97. func nativeInit(workdir string) error {
  98. libs, err := extractDynamicLibs(workdir, "llama.cpp/gguf/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. AvailableShims[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(AvailableShims))
  116. i := 0
  117. for variant := range AvailableShims {
  118. variants[i] = variant
  119. i++
  120. }
  121. log.Printf("Dynamic LLM variants %v", variants)
  122. return nil
  123. }
  124. func extractDynamicLibs(workDir, glob string) ([]string, error) {
  125. files, err := fs.Glob(libEmbed, glob)
  126. if err != nil || len(files) == 0 {
  127. return nil, payloadMissing
  128. }
  129. libs := []string{}
  130. for _, file := range files {
  131. pathComps := strings.Split(file, "/")
  132. if len(pathComps) != 7 {
  133. log.Printf("unexpected payload components: %v", pathComps)
  134. continue
  135. }
  136. // llama.cpp/gguf/build/$OS/$VARIANT/lib/$LIBRARY
  137. // Include the variant in the path to avoid conflicts between multiple server libs
  138. targetDir := filepath.Join(workDir, pathComps[4])
  139. srcFile, err := libEmbed.Open(file)
  140. if err != nil {
  141. return nil, fmt.Errorf("read payload %s: %v", file, err)
  142. }
  143. defer srcFile.Close()
  144. if err := os.MkdirAll(targetDir, 0o755); err != nil {
  145. return nil, fmt.Errorf("create payload temp dir %s: %v", workDir, err)
  146. }
  147. destFile := filepath.Join(targetDir, filepath.Base(file))
  148. if strings.Contains(destFile, "server") {
  149. libs = append(libs, destFile)
  150. }
  151. _, err = os.Stat(destFile)
  152. switch {
  153. case errors.Is(err, os.ErrNotExist):
  154. destFile, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o755)
  155. if err != nil {
  156. return nil, fmt.Errorf("write payload %s: %v", file, err)
  157. }
  158. defer destFile.Close()
  159. if _, err := io.Copy(destFile, srcFile); err != nil {
  160. return nil, fmt.Errorf("copy payload %s: %v", file, err)
  161. }
  162. case err != nil:
  163. return nil, fmt.Errorf("stat payload %s: %v", file, err)
  164. }
  165. }
  166. return libs, nil
  167. }