ext_server.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. package llm
  2. /*
  3. #cgo CFLAGS: -I${SRCDIR}/llama.cpp/gguf -I${SRCDIR}/llama.cpp/gguf/common -I${SRCDIR}/llama.cpp/gguf/examples/server
  4. #cgo CFLAGS: -DNDEBUG -DLLAMA_SERVER_LIBRARY=1 -D_XOPEN_SOURCE=600 -DACCELERATE_NEW_LAPACK -DACCELERATE_LAPACK_ILP64
  5. #cgo CFLAGS: -Wmissing-noreturn -Wall -Wextra -Wcast-qual -Wno-unused-function -Wno-array-bounds
  6. #cgo CPPFLAGS: -Ofast -Wall -Wextra -Wno-unused-function -Wno-unused-variable -Wno-deprecated-declarations -Wno-unused-but-set-variable
  7. #cgo darwin CFLAGS: -D_DARWIN_C_SOURCE
  8. #cgo darwin CPPFLAGS: -DGGML_USE_ACCELERATE
  9. #cgo darwin CPPFLAGS: -DGGML_USE_METAL -DGGML_METAL_NDEBUG
  10. #cgo darwin LDFLAGS: -lc++ -framework Accelerate
  11. #cgo darwin LDFLAGS: -framework Foundation -framework Metal -framework MetalKit -framework MetalPerformanceShaders
  12. #cgo darwin LDFLAGS: ${SRCDIR}/llama.cpp/gguf/build/metal/common/libcommon.a
  13. #cgo darwin LDFLAGS: ${SRCDIR}/llama.cpp/gguf/build/metal/examples/server/libext_server.a
  14. #cgo darwin LDFLAGS: ${SRCDIR}/llama.cpp/gguf/build/metal/libllama.a
  15. #cgo darwin LDFLAGS: ${SRCDIR}/llama.cpp/gguf/build/metal/libggml_static.a
  16. #cgo linux CFLAGS: -D_GNU_SOURCE
  17. #cgo linux windows CFLAGS: -DGGML_CUDA_DMMV_X=32 -DGGML_CUDA_MMV_Y=1 -DGGML_CUDA_PEER_MAX_BATCH_SIZE=128 -DGGML_USE_CUBLAS
  18. #cgo linux LDFLAGS: -L/usr/local/cuda/targets/x86_64-linux/lib -L/usr/local/cuda/lib64 -L/usr/local/cuda/targets/x86_64-linux/lib/stubs
  19. #cgo linux LDFLAGS: ${SRCDIR}/llama.cpp/gguf/build/cpu/examples/server/libext_server.a
  20. #cgo linux LDFLAGS: ${SRCDIR}/llama.cpp/gguf/build/cpu/common/libcommon.a
  21. #cgo linux LDFLAGS: ${SRCDIR}/llama.cpp/gguf/build/cpu/libllama.a
  22. #cgo linux LDFLAGS: ${SRCDIR}/llama.cpp/gguf/build/cpu/libggml_static.a
  23. #cgo linux LDFLAGS: -lrt -lpthread -ldl -lstdc++ -lm
  24. #cgo windows LDFLAGS: -L${SRCDIR}/llama.cpp/gguf/build/wincpu/dist/lib
  25. #cgo windows LDFLAGS: -lcpu_server -lpthread
  26. #include <stdlib.h>
  27. #include "server.h"
  28. */
  29. import "C"
  30. import (
  31. "bytes"
  32. "context"
  33. "encoding/json"
  34. "fmt"
  35. "log"
  36. "os"
  37. "strings"
  38. "sync"
  39. "time"
  40. "unsafe"
  41. "github.com/jmorganca/ollama/api"
  42. "github.com/jmorganca/ollama/gpu"
  43. )
  44. func newExtServerResp(len C.size_t) C.ext_server_resp_t {
  45. var resp C.ext_server_resp_t
  46. resp.msg_len = len
  47. bytes := make([]byte, len)
  48. resp.msg = (*C.char)(C.CBytes(bytes))
  49. return resp
  50. }
  51. func freeExtServerResp(resp C.ext_server_resp_t) {
  52. if resp.msg_len == 0 {
  53. return
  54. }
  55. C.free(unsafe.Pointer(resp.msg))
  56. }
  57. func extServerResponseToErr(resp C.ext_server_resp_t) error {
  58. return fmt.Errorf(C.GoString(resp.msg))
  59. }
  60. type extServer interface {
  61. LLM
  62. llama_server_init(sparams *C.ext_server_params_t, err *C.ext_server_resp_t)
  63. llama_server_start()
  64. llama_server_stop()
  65. llama_server_completion(json_req *C.char, resp *C.ext_server_resp_t)
  66. llama_server_completion_next_result(task_id C.int, resp *C.ext_server_task_result_t)
  67. llama_server_completion_cancel(task_id C.int, err *C.ext_server_resp_t)
  68. llama_server_release_task_result(result *C.ext_server_task_result_t)
  69. llama_server_tokenize(json_req *C.char, json_resp **C.char, err *C.ext_server_resp_t)
  70. llama_server_detokenize(json_req *C.char, json_resp **C.char, err *C.ext_server_resp_t)
  71. llama_server_embedding(json_req *C.char, json_resp **C.char, err *C.ext_server_resp_t)
  72. llama_server_release_json_resp(json_resp **C.char)
  73. }
  74. type llamaExtServer struct {
  75. api.Options
  76. }
  77. // Note: current implementation does not support concurrent instantiations
  78. var mutex sync.Mutex
  79. func (llm *llamaExtServer) llama_server_init(sparams *C.ext_server_params_t, err *C.ext_server_resp_t) {
  80. C.llama_server_init(sparams, err)
  81. }
  82. func (llm *llamaExtServer) llama_server_start() {
  83. C.llama_server_start()
  84. }
  85. func (llm *llamaExtServer) llama_server_stop() {
  86. C.llama_server_stop()
  87. }
  88. func (llm *llamaExtServer) llama_server_completion(json_req *C.char, resp *C.ext_server_resp_t) {
  89. C.llama_server_completion(json_req, resp)
  90. }
  91. func (llm *llamaExtServer) llama_server_completion_next_result(task_id C.int, resp *C.ext_server_task_result_t) {
  92. C.llama_server_completion_next_result(task_id, resp)
  93. }
  94. func (llm *llamaExtServer) llama_server_completion_cancel(task_id C.int, err *C.ext_server_resp_t) {
  95. C.llama_server_completion_cancel(task_id, err)
  96. }
  97. func (llm *llamaExtServer) llama_server_release_task_result(result *C.ext_server_task_result_t) {
  98. C.llama_server_release_task_result(result)
  99. }
  100. func (llm *llamaExtServer) llama_server_tokenize(json_req *C.char, json_resp **C.char, err *C.ext_server_resp_t) {
  101. C.llama_server_tokenize(json_req, json_resp, err)
  102. }
  103. func (llm *llamaExtServer) llama_server_detokenize(json_req *C.char, json_resp **C.char, err *C.ext_server_resp_t) {
  104. C.llama_server_detokenize(json_req, json_resp, err)
  105. }
  106. func (llm *llamaExtServer) llama_server_embedding(json_req *C.char, json_resp **C.char, err *C.ext_server_resp_t) {
  107. C.llama_server_embedding(json_req, json_resp, err)
  108. }
  109. func (llm *llamaExtServer) llama_server_release_json_resp(json_resp **C.char) {
  110. C.llama_server_release_json_resp(json_resp)
  111. }
  112. func newDefaultExtServer(model string, adapters, projectors []string, numLayers int64, opts api.Options) (extServer, error) {
  113. server := &llamaExtServer{opts}
  114. return newExtServer(server, model, adapters, projectors, numLayers, opts)
  115. }
  116. func newExtServer(server extServer, model string, adapters, projectors []string, numLayers int64, opts api.Options) (extServer, error) {
  117. if !mutex.TryLock() {
  118. log.Printf("concurrent llm servers not yet supported, waiting for prior server to complete")
  119. mutex.Lock()
  120. }
  121. fileInfo, err := os.Stat(model)
  122. if err != nil {
  123. return nil, err
  124. }
  125. var sparams C.ext_server_params_t
  126. sparams.model = C.CString(model)
  127. defer C.free(unsafe.Pointer(sparams.model))
  128. numGPU := gpu.NumGPU(numLayers, fileInfo.Size(), opts)
  129. sparams.embedding = true
  130. sparams.n_ctx = C.uint(opts.NumCtx)
  131. sparams.n_batch = C.uint(opts.NumBatch)
  132. sparams.n_gpu_layers = C.int(numGPU)
  133. sparams.main_gpu = C.int(opts.MainGPU)
  134. sparams.n_parallel = 1 // TODO - wire up concurrency
  135. // Always use the value encoded in the model
  136. sparams.rope_freq_base = 0.0
  137. sparams.rope_freq_scale = 0.0
  138. sparams.memory_f16 = C.bool(opts.F16KV)
  139. sparams.use_mlock = C.bool(opts.UseMLock)
  140. sparams.use_mmap = C.bool(opts.UseMMap)
  141. sparams.numa = C.bool(opts.UseNUMA)
  142. sparams.lora_adapters = nil
  143. for i := 0; i < len(adapters); i++ {
  144. la := (*C.ext_server_lora_adapter_t)(C.malloc(C.sizeof_ext_server_lora_adapter_t))
  145. defer C.free(unsafe.Pointer(la))
  146. la.adapter = C.CString(adapters[i])
  147. defer C.free(unsafe.Pointer(la.adapter))
  148. la.scale = C.float(1.0) // TODO expose scale/weights up through ollama UX
  149. la.next = nil
  150. if i == 0 {
  151. sparams.lora_adapters = la
  152. } else {
  153. tmp := sparams.lora_adapters
  154. for ; tmp.next != nil; tmp = tmp.next {
  155. }
  156. tmp.next = la
  157. }
  158. }
  159. if len(projectors) > 0 {
  160. // TODO: applying multiple projectors is not supported by the llama.cpp server yet
  161. sparams.mmproj = C.CString(projectors[0])
  162. defer C.free(unsafe.Pointer(sparams.mmproj))
  163. } else {
  164. sparams.mmproj = nil
  165. }
  166. sparams.n_threads = C.uint(opts.NumThread)
  167. log.Printf("Initializing internal llama server")
  168. resp := newExtServerResp(128)
  169. defer freeExtServerResp(resp)
  170. server.llama_server_init(&sparams, &resp)
  171. if resp.id < 0 {
  172. return nil, extServerResponseToErr(resp)
  173. }
  174. log.Printf("Starting internal llama main loop")
  175. server.llama_server_start()
  176. return server, nil
  177. }
  178. func (llm *llamaExtServer) Predict(ctx context.Context, pred PredictOpts, fn func(PredictResult)) error {
  179. return predict(llm, llm.Options, ctx, pred, fn)
  180. }
  181. func predict(llm extServer, opts api.Options, ctx context.Context, predict PredictOpts, fn func(PredictResult)) error {
  182. resp := newExtServerResp(128)
  183. defer freeExtServerResp(resp)
  184. var imageData []ImageData
  185. if len(predict.Images) > 0 {
  186. for cnt, i := range predict.Images {
  187. imageData = append(imageData, ImageData{Data: i, ID: cnt})
  188. }
  189. }
  190. log.Printf("loaded %d images", len(imageData))
  191. request := map[string]any{
  192. "prompt": predict.Prompt,
  193. "stream": true,
  194. "n_predict": opts.NumPredict,
  195. "n_keep": opts.NumKeep,
  196. "temperature": opts.Temperature,
  197. "top_k": opts.TopK,
  198. "top_p": opts.TopP,
  199. "tfs_z": opts.TFSZ,
  200. "typical_p": opts.TypicalP,
  201. "repeat_last_n": opts.RepeatLastN,
  202. "repeat_penalty": opts.RepeatPenalty,
  203. "presence_penalty": opts.PresencePenalty,
  204. "frequency_penalty": opts.FrequencyPenalty,
  205. "mirostat": opts.Mirostat,
  206. "mirostat_tau": opts.MirostatTau,
  207. "mirostat_eta": opts.MirostatEta,
  208. "penalize_nl": opts.PenalizeNewline,
  209. "seed": opts.Seed,
  210. "stop": opts.Stop,
  211. "image_data": imageData,
  212. }
  213. if predict.Format == "json" {
  214. request["grammar"] = jsonGrammar
  215. }
  216. retryDelay := 100 * time.Microsecond
  217. for retries := 0; retries < maxRetries; retries++ {
  218. if retries > 0 {
  219. time.Sleep(retryDelay) // wait before retrying
  220. retryDelay *= 2 // exponential backoff
  221. }
  222. // Handling JSON marshaling with special characters unescaped.
  223. buffer := &bytes.Buffer{}
  224. enc := json.NewEncoder(buffer)
  225. enc.SetEscapeHTML(false)
  226. if err := enc.Encode(request); err != nil {
  227. return fmt.Errorf("failed to marshal data: %w", err)
  228. }
  229. req := C.CString(buffer.String())
  230. defer C.free(unsafe.Pointer(req))
  231. llm.llama_server_completion(req, &resp)
  232. if resp.id < 0 {
  233. return extServerResponseToErr(resp)
  234. }
  235. retryNeeded := false
  236. out:
  237. for {
  238. select {
  239. case <-ctx.Done():
  240. // This handles the request cancellation
  241. llm.llama_server_completion_cancel(resp.id, &resp)
  242. if resp.id < 0 {
  243. return extServerResponseToErr(resp)
  244. } else {
  245. return nil
  246. }
  247. default:
  248. var result C.ext_server_task_result_t
  249. llm.llama_server_completion_next_result(resp.id, &result)
  250. json_resp := C.GoString(result.json_resp)
  251. llm.llama_server_release_task_result(&result)
  252. var p prediction
  253. if err := json.Unmarshal([]byte(json_resp), &p); err != nil {
  254. llm.llama_server_completion_cancel(resp.id, &resp)
  255. if resp.id < 0 {
  256. return fmt.Errorf("error unmarshaling llm prediction response: %w and cancel %s", err, C.GoString(resp.msg))
  257. } else {
  258. return fmt.Errorf("error unmarshaling llm prediction response: %w", err)
  259. }
  260. }
  261. if bool(result.error) && strings.Contains(json_resp, "slot unavailable") {
  262. retryNeeded = true
  263. // task will already be canceled
  264. break out
  265. }
  266. if p.Content != "" {
  267. fn(PredictResult{
  268. Content: p.Content,
  269. })
  270. }
  271. if p.Stop {
  272. fn(PredictResult{
  273. Done: true,
  274. PromptEvalCount: p.Timings.PromptN,
  275. PromptEvalDuration: parseDurationMs(p.Timings.PromptMS),
  276. EvalCount: p.Timings.PredictedN,
  277. EvalDuration: parseDurationMs(p.Timings.PredictedMS),
  278. })
  279. return nil
  280. }
  281. }
  282. }
  283. if !retryNeeded {
  284. return nil // success
  285. }
  286. }
  287. // should never reach here ideally
  288. return fmt.Errorf("max retries exceeded")
  289. }
  290. func (llm *llamaExtServer) Encode(ctx context.Context, prompt string) ([]int, error) {
  291. return encode(llm, ctx, prompt)
  292. }
  293. func encode(llm extServer, ctx context.Context, prompt string) ([]int, error) {
  294. data, err := json.Marshal(TokenizeRequest{Content: prompt})
  295. if err != nil {
  296. return nil, fmt.Errorf("marshaling encode data: %w", err)
  297. }
  298. req := C.CString(string(data))
  299. defer C.free(unsafe.Pointer(req))
  300. var json_resp *C.char
  301. resp := newExtServerResp(128)
  302. defer freeExtServerResp(resp)
  303. llm.llama_server_tokenize(req, &json_resp, &resp)
  304. if resp.id < 0 {
  305. return nil, extServerResponseToErr(resp)
  306. }
  307. defer llm.llama_server_release_json_resp(&json_resp)
  308. var encoded TokenizeResponse
  309. if err2 := json.Unmarshal([]byte(C.GoString(json_resp)), &encoded); err2 != nil {
  310. return nil, fmt.Errorf("unmarshal encode response: %w", err2)
  311. }
  312. return encoded.Tokens, err
  313. }
  314. func (llm *llamaExtServer) Decode(ctx context.Context, tokens []int) (string, error) {
  315. return decode(llm, ctx, tokens)
  316. }
  317. func decode(llm extServer, ctx context.Context, tokens []int) (string, error) {
  318. if len(tokens) == 0 {
  319. return "", nil
  320. }
  321. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  322. if err != nil {
  323. return "", fmt.Errorf("marshaling decode data: %w", err)
  324. }
  325. req := C.CString(string(data))
  326. defer C.free(unsafe.Pointer(req))
  327. var json_resp *C.char
  328. resp := newExtServerResp(128)
  329. defer freeExtServerResp(resp)
  330. llm.llama_server_detokenize(req, &json_resp, &resp)
  331. if resp.id < 0 {
  332. return "", extServerResponseToErr(resp)
  333. }
  334. defer llm.llama_server_release_json_resp(&json_resp)
  335. var decoded DetokenizeResponse
  336. if err2 := json.Unmarshal([]byte(C.GoString(json_resp)), &decoded); err2 != nil {
  337. return "", fmt.Errorf("unmarshal encode response: %w", err2)
  338. }
  339. return decoded.Content, err
  340. }
  341. func (llm *llamaExtServer) Embedding(ctx context.Context, input string) ([]float64, error) {
  342. return embedding(llm, ctx, input)
  343. }
  344. func embedding(llm extServer, ctx context.Context, input string) ([]float64, error) {
  345. data, err := json.Marshal(TokenizeRequest{Content: input})
  346. if err != nil {
  347. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  348. }
  349. req := C.CString(string(data))
  350. defer C.free(unsafe.Pointer(req))
  351. var json_resp *C.char
  352. resp := newExtServerResp(128)
  353. defer freeExtServerResp(resp)
  354. llm.llama_server_embedding(req, &json_resp, &resp)
  355. if resp.id < 0 {
  356. return nil, extServerResponseToErr(resp)
  357. }
  358. defer llm.llama_server_release_json_resp(&json_resp)
  359. var embedding EmbeddingResponse
  360. if err := json.Unmarshal([]byte(C.GoString(json_resp)), &embedding); err != nil {
  361. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  362. }
  363. return embedding.Embedding, nil
  364. }
  365. func (llm *llamaExtServer) Close() {
  366. close(llm)
  367. }
  368. func close(llm extServer) {
  369. llm.llama_server_stop()
  370. mutex.Unlock()
  371. }