ext_server.go 14 KB

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