ext_server.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. #include "ext_server.h"
  2. #include <atomic>
  3. // Necessary evil since the server types are not defined in a header
  4. #include "server.cpp"
  5. // Low level API access to verify GPU access
  6. #if defined(GGML_USE_CUBLAS)
  7. #if defined(GGML_USE_HIPBLAS)
  8. #include <hip/hip_runtime.h>
  9. #include <hipblas/hipblas.h>
  10. #include <hip/hip_fp16.h>
  11. #ifdef __HIP_PLATFORM_AMD__
  12. // for rocblas_initialize()
  13. #include "rocblas/rocblas.h"
  14. #endif // __HIP_PLATFORM_AMD__
  15. #define cudaGetDevice hipGetDevice
  16. #define cudaError_t hipError_t
  17. #define cudaSuccess hipSuccess
  18. #define cudaGetErrorString hipGetErrorString
  19. #else
  20. #include <cuda_runtime.h>
  21. #include <cublas_v2.h>
  22. #include <cuda_fp16.h>
  23. #endif // defined(GGML_USE_HIPBLAS)
  24. #endif // GGML_USE_CUBLAS
  25. // Expose the llama server as a callable extern "C" API
  26. llama_server_context *llama = NULL;
  27. std::thread ext_server_thread;
  28. bool shutting_down = false;
  29. std::atomic_int recv_counter;
  30. // RAII wrapper for tracking in-flight recv calls
  31. class atomicRecv {
  32. public:
  33. atomicRecv(std::atomic<int> &atomic) : atomic(atomic) {
  34. ++this->atomic;
  35. }
  36. ~atomicRecv() {
  37. --this->atomic;
  38. }
  39. private:
  40. std::atomic<int> &atomic;
  41. };
  42. void llama_server_init(ext_server_params *sparams, ext_server_resp_t *err) {
  43. recv_counter = 0;
  44. assert(err != NULL && sparams != NULL);
  45. log_set_target(stderr);
  46. if (!sparams->verbose_logging) {
  47. server_verbose = true;
  48. log_disable();
  49. }
  50. LOG_TEE("system info: %s\n", llama_print_system_info());
  51. err->id = 0;
  52. err->msg[0] = '\0';
  53. try {
  54. llama = new llama_server_context;
  55. gpt_params params;
  56. params.n_ctx = sparams->n_ctx;
  57. params.n_batch = sparams->n_batch;
  58. if (sparams->n_threads > 0) {
  59. params.n_threads = sparams->n_threads;
  60. }
  61. params.n_parallel = sparams->n_parallel;
  62. params.rope_freq_base = sparams->rope_freq_base;
  63. params.rope_freq_scale = sparams->rope_freq_scale;
  64. if (sparams->memory_f16) {
  65. params.cache_type_k = "f16";
  66. params.cache_type_v = "f16";
  67. } else {
  68. params.cache_type_k = "f32";
  69. params.cache_type_v = "f32";
  70. }
  71. params.n_gpu_layers = sparams->n_gpu_layers;
  72. params.main_gpu = sparams->main_gpu;
  73. params.use_mlock = sparams->use_mlock;
  74. params.use_mmap = sparams->use_mmap;
  75. params.numa = (ggml_numa_strategy)sparams->numa;
  76. params.embedding = sparams->embedding;
  77. if (sparams->model != NULL) {
  78. params.model = sparams->model;
  79. }
  80. if (sparams->lora_adapters != NULL) {
  81. for (ext_server_lora_adapter *la = sparams->lora_adapters; la != NULL;
  82. la = la->next) {
  83. params.lora_adapter.push_back(std::make_tuple(la->adapter, la->scale));
  84. }
  85. params.use_mmap = false;
  86. }
  87. if (sparams->mmproj != NULL) {
  88. params.mmproj = std::string(sparams->mmproj);
  89. }
  90. #if defined(GGML_USE_CUBLAS)
  91. // Before attempting to init the backend which will assert on error, verify the CUDA/ROCM GPU is accessible
  92. LOG_TEE("Performing pre-initialization of GPU\n");
  93. int id;
  94. cudaError_t cudaErr = cudaGetDevice(&id);
  95. if (cudaErr != cudaSuccess) {
  96. err->id = -1;
  97. snprintf(err->msg, err->msg_len, "Unable to init GPU: %s", cudaGetErrorString(cudaErr));
  98. return;
  99. }
  100. #endif
  101. llama_backend_init();
  102. llama_numa_init(params.numa);
  103. if (!llama->load_model(params)) {
  104. // an error occurred that was not thrown
  105. err->id = -1;
  106. snprintf(err->msg, err->msg_len, "error loading model %s", params.model.c_str());
  107. return;
  108. }
  109. llama->initialize();
  110. } catch (std::exception &e) {
  111. err->id = -1;
  112. snprintf(err->msg, err->msg_len, "exception %s", e.what());
  113. } catch (...) {
  114. err->id = -1;
  115. snprintf(err->msg, err->msg_len,
  116. "Unknown exception initializing llama server");
  117. }
  118. }
  119. void llama_server_start() {
  120. assert(llama != NULL);
  121. // TODO mutex to protect thread creation
  122. ext_server_thread = std::thread([&]() {
  123. try {
  124. LOG_TEE("llama server main loop starting\n");
  125. ggml_time_init();
  126. llama->queue_tasks.on_new_task(std::bind(
  127. &llama_server_context::process_single_task, llama, std::placeholders::_1));
  128. llama->queue_tasks.on_finish_multitask(std::bind(
  129. &llama_server_context::on_finish_multitask, llama, std::placeholders::_1));
  130. llama->queue_tasks.on_run_slots(std::bind(
  131. &llama_server_context::update_slots, llama));
  132. llama->queue_results.on_multitask_update(std::bind(
  133. &llama_server_queue::update_multitask,
  134. &llama->queue_tasks,
  135. std::placeholders::_1,
  136. std::placeholders::_2,
  137. std::placeholders::_3
  138. ));
  139. llama->queue_tasks.start_loop();
  140. } catch (std::exception &e) {
  141. LOG_TEE("caught exception in llama server main loop: %s\n", e.what());
  142. } catch (...) {
  143. LOG_TEE("caught unknown exception in llama server main loop\n");
  144. }
  145. LOG_TEE("\nllama server shutting down\n");
  146. llama_backend_free();
  147. });
  148. }
  149. void llama_server_stop() {
  150. assert(llama != NULL);
  151. // Shutdown any in-flight requests and block incoming requests.
  152. LOG_TEE("\ninitiating shutdown - draining remaining tasks...\n");
  153. shutting_down = true;
  154. while (recv_counter.load() > 0) {
  155. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  156. }
  157. // This may take a while for any pending tasks to drain
  158. // TODO - consider a timeout to cancel tasks if it's taking too long
  159. llama->queue_tasks.terminate();
  160. ext_server_thread.join();
  161. delete llama;
  162. llama = NULL;
  163. LOG_TEE("llama server shutdown complete\n");
  164. shutting_down = false;
  165. }
  166. void llama_server_completion(const char *json_req, ext_server_resp_t *resp) {
  167. assert(llama != NULL && json_req != NULL && resp != NULL);
  168. resp->id = -1;
  169. resp->msg[0] = '\0';
  170. try {
  171. if (shutting_down) {
  172. throw std::runtime_error("server shutting down");
  173. }
  174. json data = json::parse(json_req);
  175. resp->id = llama->queue_tasks.get_new_id();
  176. llama->queue_results.add_waiting_task_id(resp->id);
  177. llama->request_completion(resp->id, data, false, false, -1);
  178. } catch (std::exception &e) {
  179. snprintf(resp->msg, resp->msg_len, "exception %s", e.what());
  180. } catch (...) {
  181. snprintf(resp->msg, resp->msg_len, "Unknown exception during completion");
  182. }
  183. }
  184. void llama_server_completion_next_result(const int task_id,
  185. ext_server_task_result_t *resp) {
  186. assert(llama != NULL && resp != NULL);
  187. resp->id = -1;
  188. resp->stop = false;
  189. resp->error = false;
  190. resp->json_resp = NULL;
  191. std::string result_json;
  192. try {
  193. atomicRecv ar(recv_counter);
  194. task_result result = llama->queue_results.recv(task_id);
  195. result_json =
  196. result.result_json.dump(-1, ' ', false, json::error_handler_t::replace);
  197. resp->id = result.id;
  198. resp->stop = result.stop;
  199. resp->error = result.error;
  200. if (result.error) {
  201. LOG_TEE("next result cancel on error\n");
  202. llama->request_cancel(task_id);
  203. LOG_TEE("next result removing waiting tak ID: %d\n", task_id);
  204. llama->queue_results.remove_waiting_task_id(task_id);
  205. } else if (result.stop) {
  206. LOG_TEE("next result cancel on stop\n");
  207. llama->request_cancel(task_id);
  208. LOG_TEE("next result removing waiting task ID: %d\n", task_id);
  209. llama->queue_results.remove_waiting_task_id(task_id);
  210. } else if (shutting_down) {
  211. LOG_TEE("aborting completion due to shutdown %d\n", task_id);
  212. llama->request_cancel(task_id);
  213. llama->queue_results.remove_waiting_task_id(task_id);
  214. resp->stop = true;
  215. }
  216. } catch (std::exception &e) {
  217. resp->error = true;
  218. resp->id = -1;
  219. result_json = "{\"error\":\"exception " + std::string(e.what()) + "\"}";
  220. LOG_TEE("llama server completion exception %s\n", e.what());
  221. } catch (...) {
  222. resp->error = true;
  223. resp->id = -1;
  224. result_json = "{\"error\":\"Unknown exception during completion\"}";
  225. LOG_TEE("llama server completion unknown exception\n");
  226. }
  227. const std::string::size_type size = result_json.size() + 1;
  228. resp->json_resp = new char[size];
  229. snprintf(resp->json_resp, size, "%s", result_json.c_str());
  230. }
  231. void llama_server_release_task_result(ext_server_task_result_t *result) {
  232. if (result == NULL || result->json_resp == NULL) {
  233. return;
  234. }
  235. delete[] result->json_resp;
  236. }
  237. void llama_server_completion_cancel(const int task_id, ext_server_resp_t *err) {
  238. assert(llama != NULL && err != NULL);
  239. err->id = 0;
  240. err->msg[0] = '\0';
  241. try {
  242. llama->request_cancel(task_id);
  243. llama->queue_results.remove_waiting_task_id(task_id);
  244. } catch (std::exception &e) {
  245. err->id = -1;
  246. snprintf(err->msg, err->msg_len, "exception %s", e.what());
  247. } catch (...) {
  248. err->id = -1;
  249. snprintf(err->msg, err->msg_len,
  250. "Unknown exception completion cancel in llama server");
  251. }
  252. }
  253. void llama_server_tokenize(const char *json_req, char **json_resp,
  254. ext_server_resp_t *err) {
  255. assert(llama != NULL && json_req != NULL && json_resp != NULL && err != NULL);
  256. *json_resp = NULL;
  257. err->id = 0;
  258. err->msg[0] = '\0';
  259. try {
  260. if (shutting_down) {
  261. throw std::runtime_error("server shutting down");
  262. }
  263. const json body = json::parse(json_req);
  264. std::vector<llama_token> tokens;
  265. if (body.count("content") != 0) {
  266. tokens = llama->tokenize(body["content"], false);
  267. }
  268. const json data = format_tokenizer_response(tokens);
  269. std::string result_json = data.dump();
  270. const std::string::size_type size = result_json.size() + 1;
  271. *json_resp = new char[size];
  272. snprintf(*json_resp, size, "%s", result_json.c_str());
  273. } catch (std::exception &e) {
  274. err->id = -1;
  275. snprintf(err->msg, err->msg_len, "exception %s", e.what());
  276. } catch (...) {
  277. err->id = -1;
  278. snprintf(err->msg, err->msg_len, "Unknown exception during tokenize");
  279. }
  280. }
  281. void llama_server_release_json_resp(char **json_resp) {
  282. if (json_resp == NULL || *json_resp == NULL) {
  283. return;
  284. }
  285. delete[] *json_resp;
  286. }
  287. void llama_server_detokenize(const char *json_req, char **json_resp,
  288. ext_server_resp_t *err) {
  289. assert(llama != NULL && json_req != NULL && json_resp != NULL && err != NULL);
  290. *json_resp = NULL;
  291. err->id = 0;
  292. err->msg[0] = '\0';
  293. try {
  294. if (shutting_down) {
  295. throw std::runtime_error("server shutting down");
  296. }
  297. const json body = json::parse(json_req);
  298. std::string content;
  299. if (body.count("tokens") != 0) {
  300. const std::vector<llama_token> tokens = body["tokens"];
  301. content = tokens_to_str(llama->ctx, tokens.cbegin(), tokens.cend());
  302. }
  303. const json data = format_detokenized_response(content);
  304. std::string result_json = data.dump();
  305. const std::string::size_type size = result_json.size() + 1;
  306. *json_resp = new char[size];
  307. snprintf(*json_resp, size, "%s", result_json.c_str());
  308. } catch (std::exception &e) {
  309. err->id = -1;
  310. snprintf(err->msg, err->msg_len, "exception %s", e.what());
  311. } catch (...) {
  312. err->id = -1;
  313. snprintf(err->msg, err->msg_len, "Unknown exception during detokenize");
  314. }
  315. }
  316. void llama_server_embedding(const char *json_req, char **json_resp,
  317. ext_server_resp_t *err) {
  318. assert(llama != NULL && json_req != NULL && json_resp != NULL && err != NULL);
  319. *json_resp = NULL;
  320. err->id = 0;
  321. err->msg[0] = '\0';
  322. try {
  323. if (shutting_down) {
  324. throw std::runtime_error("server shutting down");
  325. }
  326. const json body = json::parse(json_req);
  327. json prompt;
  328. if (body.count("content") != 0) {
  329. prompt = body["content"];
  330. } else {
  331. prompt = "";
  332. }
  333. const int task_id = llama->queue_tasks.get_new_id();
  334. llama->queue_results.add_waiting_task_id(task_id);
  335. llama->request_completion(task_id, {{"prompt", prompt}, {"n_predict", 0}}, false, true, -1);
  336. atomicRecv ar(recv_counter);
  337. task_result result = llama->queue_results.recv(task_id);
  338. std::string result_json = result.result_json.dump();
  339. const std::string::size_type size = result_json.size() + 1;
  340. *json_resp = new char[size];
  341. snprintf(*json_resp, size, "%s", result_json.c_str());
  342. llama->queue_results.remove_waiting_task_id(task_id);
  343. } catch (std::exception &e) {
  344. err->id = -1;
  345. snprintf(err->msg, err->msg_len, "exception %s", e.what());
  346. } catch (...) {
  347. err->id = -1;
  348. snprintf(err->msg, err->msg_len, "Unknown exception during embedding");
  349. }
  350. }