ext_server.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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. "cache_prompt": true,
  213. }
  214. if predict.Format == "json" {
  215. request["grammar"] = jsonGrammar
  216. }
  217. retryDelay := 100 * time.Microsecond
  218. for retries := 0; retries < maxRetries; retries++ {
  219. if retries > 0 {
  220. time.Sleep(retryDelay) // wait before retrying
  221. retryDelay *= 2 // exponential backoff
  222. }
  223. // Handling JSON marshaling with special characters unescaped.
  224. buffer := &bytes.Buffer{}
  225. enc := json.NewEncoder(buffer)
  226. enc.SetEscapeHTML(false)
  227. if err := enc.Encode(request); err != nil {
  228. return fmt.Errorf("failed to marshal data: %w", err)
  229. }
  230. req := C.CString(buffer.String())
  231. defer C.free(unsafe.Pointer(req))
  232. llm.llama_server_completion(req, &resp)
  233. if resp.id < 0 {
  234. return extServerResponseToErr(resp)
  235. }
  236. retryNeeded := false
  237. out:
  238. for {
  239. select {
  240. case <-ctx.Done():
  241. // This handles the request cancellation
  242. llm.llama_server_completion_cancel(resp.id, &resp)
  243. if resp.id < 0 {
  244. return extServerResponseToErr(resp)
  245. } else {
  246. return nil
  247. }
  248. default:
  249. var result C.ext_server_task_result_t
  250. llm.llama_server_completion_next_result(resp.id, &result)
  251. json_resp := C.GoString(result.json_resp)
  252. llm.llama_server_release_task_result(&result)
  253. var p prediction
  254. if err := json.Unmarshal([]byte(json_resp), &p); err != nil {
  255. llm.llama_server_completion_cancel(resp.id, &resp)
  256. if resp.id < 0 {
  257. return fmt.Errorf("error unmarshaling llm prediction response: %w and cancel %s", err, C.GoString(resp.msg))
  258. } else {
  259. return fmt.Errorf("error unmarshaling llm prediction response: %w", err)
  260. }
  261. }
  262. if bool(result.error) && strings.Contains(json_resp, "slot unavailable") {
  263. retryNeeded = true
  264. // task will already be canceled
  265. break out
  266. }
  267. if p.Content != "" {
  268. fn(PredictResult{
  269. Content: p.Content,
  270. })
  271. }
  272. if p.Stop {
  273. fn(PredictResult{
  274. Done: true,
  275. PromptEvalCount: p.Timings.PromptN,
  276. PromptEvalDuration: parseDurationMs(p.Timings.PromptMS),
  277. EvalCount: p.Timings.PredictedN,
  278. EvalDuration: parseDurationMs(p.Timings.PredictedMS),
  279. })
  280. return nil
  281. }
  282. }
  283. }
  284. if !retryNeeded {
  285. return nil // success
  286. }
  287. }
  288. // should never reach here ideally
  289. return fmt.Errorf("max retries exceeded")
  290. }
  291. func (llm *llamaExtServer) Encode(ctx context.Context, prompt string) ([]int, error) {
  292. return encode(llm, ctx, prompt)
  293. }
  294. func encode(llm extServer, ctx context.Context, prompt string) ([]int, error) {
  295. data, err := json.Marshal(TokenizeRequest{Content: prompt})
  296. if err != nil {
  297. return nil, fmt.Errorf("marshaling encode data: %w", err)
  298. }
  299. req := C.CString(string(data))
  300. defer C.free(unsafe.Pointer(req))
  301. var json_resp *C.char
  302. resp := newExtServerResp(128)
  303. defer freeExtServerResp(resp)
  304. llm.llama_server_tokenize(req, &json_resp, &resp)
  305. if resp.id < 0 {
  306. return nil, extServerResponseToErr(resp)
  307. }
  308. defer llm.llama_server_release_json_resp(&json_resp)
  309. var encoded TokenizeResponse
  310. if err2 := json.Unmarshal([]byte(C.GoString(json_resp)), &encoded); err2 != nil {
  311. return nil, fmt.Errorf("unmarshal encode response: %w", err2)
  312. }
  313. return encoded.Tokens, err
  314. }
  315. func (llm *llamaExtServer) Decode(ctx context.Context, tokens []int) (string, error) {
  316. return decode(llm, ctx, tokens)
  317. }
  318. func decode(llm extServer, ctx context.Context, tokens []int) (string, error) {
  319. if len(tokens) == 0 {
  320. return "", nil
  321. }
  322. data, err := json.Marshal(DetokenizeRequest{Tokens: tokens})
  323. if err != nil {
  324. return "", fmt.Errorf("marshaling decode data: %w", err)
  325. }
  326. req := C.CString(string(data))
  327. defer C.free(unsafe.Pointer(req))
  328. var json_resp *C.char
  329. resp := newExtServerResp(128)
  330. defer freeExtServerResp(resp)
  331. llm.llama_server_detokenize(req, &json_resp, &resp)
  332. if resp.id < 0 {
  333. return "", extServerResponseToErr(resp)
  334. }
  335. defer llm.llama_server_release_json_resp(&json_resp)
  336. var decoded DetokenizeResponse
  337. if err2 := json.Unmarshal([]byte(C.GoString(json_resp)), &decoded); err2 != nil {
  338. return "", fmt.Errorf("unmarshal encode response: %w", err2)
  339. }
  340. return decoded.Content, err
  341. }
  342. func (llm *llamaExtServer) Embedding(ctx context.Context, input string) ([]float64, error) {
  343. return embedding(llm, ctx, input)
  344. }
  345. func embedding(llm extServer, ctx context.Context, input string) ([]float64, error) {
  346. data, err := json.Marshal(TokenizeRequest{Content: input})
  347. if err != nil {
  348. return nil, fmt.Errorf("error marshaling embed data: %w", err)
  349. }
  350. req := C.CString(string(data))
  351. defer C.free(unsafe.Pointer(req))
  352. var json_resp *C.char
  353. resp := newExtServerResp(128)
  354. defer freeExtServerResp(resp)
  355. llm.llama_server_embedding(req, &json_resp, &resp)
  356. if resp.id < 0 {
  357. return nil, extServerResponseToErr(resp)
  358. }
  359. defer llm.llama_server_release_json_resp(&json_resp)
  360. var embedding EmbeddingResponse
  361. if err := json.Unmarshal([]byte(C.GoString(json_resp)), &embedding); err != nil {
  362. return nil, fmt.Errorf("unmarshal tokenize response: %w", err)
  363. }
  364. return embedding.Embedding, nil
  365. }
  366. func (llm *llamaExtServer) Close() {
  367. close(llm)
  368. }
  369. func close(llm extServer) {
  370. llm.llama_server_stop()
  371. mutex.Unlock()
  372. }