utils.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. #pragma once
  2. #include <string>
  3. #include <vector>
  4. #include <set>
  5. #include <mutex>
  6. #include <condition_variable>
  7. #include <unordered_map>
  8. #include "json.hpp"
  9. #include "../llava/clip.h"
  10. using json = nlohmann::json;
  11. extern bool server_verbose;
  12. #ifndef SERVER_VERBOSE
  13. #define SERVER_VERBOSE 1
  14. #endif
  15. #if SERVER_VERBOSE != 1
  16. #define LOG_VERBOSE(MSG, ...)
  17. #else
  18. #define LOG_VERBOSE(MSG, ...) \
  19. do \
  20. { \
  21. if (server_verbose) \
  22. { \
  23. server_log("VERBOSE", __func__, __LINE__, MSG, __VA_ARGS__); \
  24. } \
  25. } while (0)
  26. #endif
  27. #define LOG_ERROR( MSG, ...) server_log("ERROR", __func__, __LINE__, MSG, __VA_ARGS__)
  28. #define LOG_WARNING(MSG, ...) server_log("WARNING", __func__, __LINE__, MSG, __VA_ARGS__)
  29. #define LOG_INFO( MSG, ...) server_log("INFO", __func__, __LINE__, MSG, __VA_ARGS__)
  30. //
  31. // parallel
  32. //
  33. enum server_state {
  34. SERVER_STATE_LOADING_MODEL, // Server is starting up, model not fully loaded yet
  35. SERVER_STATE_READY, // Server is ready and model is loaded
  36. SERVER_STATE_ERROR // An error occurred, load_model failed
  37. };
  38. enum task_type {
  39. TASK_TYPE_COMPLETION,
  40. TASK_TYPE_CANCEL,
  41. TASK_TYPE_NEXT_RESPONSE,
  42. TASK_TYPE_METRICS
  43. };
  44. struct task_server {
  45. int id = -1; // to be filled by llama_server_queue
  46. int target_id;
  47. task_type type;
  48. json data;
  49. bool infill_mode = false;
  50. bool embedding_mode = false;
  51. int multitask_id = -1;
  52. };
  53. struct task_result {
  54. int id;
  55. int multitask_id = -1;
  56. bool stop;
  57. bool error;
  58. json result_json;
  59. };
  60. struct task_multi {
  61. int id;
  62. std::set<int> subtasks_remaining{};
  63. std::vector<task_result> results{};
  64. };
  65. // TODO: can become bool if we can't find use of more states
  66. enum slot_state
  67. {
  68. IDLE,
  69. PROCESSING,
  70. };
  71. enum slot_command
  72. {
  73. NONE,
  74. LOAD_PROMPT,
  75. RELEASE,
  76. };
  77. struct slot_params
  78. {
  79. bool stream = true;
  80. bool cache_prompt = false; // remember the prompt to avoid reprocessing all prompt
  81. uint32_t seed = -1; // RNG seed
  82. int32_t n_keep = 0; // number of tokens to keep from initial prompt
  83. int32_t n_predict = -1; // new tokens to predict
  84. std::vector<std::string> antiprompt;
  85. json input_prefix;
  86. json input_suffix;
  87. };
  88. struct slot_image
  89. {
  90. int32_t id;
  91. bool request_encode_image = false;
  92. float * image_embedding = nullptr;
  93. int32_t image_tokens = 0;
  94. clip_image_u8 * img_data;
  95. std::string prefix_prompt; // before of this image
  96. };
  97. // completion token output with probabilities
  98. struct completion_token_output
  99. {
  100. struct token_prob
  101. {
  102. llama_token tok;
  103. float prob;
  104. };
  105. std::vector<token_prob> probs;
  106. llama_token tok;
  107. std::string text_to_send;
  108. };
  109. static inline void server_log(const char *level, const char *function, int line,
  110. const char *message, const nlohmann::ordered_json &extra)
  111. {
  112. nlohmann::ordered_json log
  113. {
  114. {"timestamp", time(nullptr)},
  115. {"level", level},
  116. {"function", function},
  117. {"line", line},
  118. {"message", message},
  119. };
  120. if (!extra.empty())
  121. {
  122. log.merge_patch(extra);
  123. }
  124. const std::string str = log.dump(-1, ' ', false, json::error_handler_t::replace);
  125. printf("%.*s\n", (int)str.size(), str.data());
  126. fflush(stdout);
  127. }
  128. //
  129. // server utils
  130. //
  131. template <typename T>
  132. static T json_value(const json &body, const std::string &key, const T &default_value)
  133. {
  134. // Fallback null to default value
  135. return body.contains(key) && !body.at(key).is_null()
  136. ? body.value(key, default_value)
  137. : default_value;
  138. }
  139. // Check if the template supplied via "--chat-template" is supported or not. Returns true if it's valid
  140. inline bool verify_custom_template(const std::string & tmpl) {
  141. llama_chat_message chat[] = {{"user", "test"}};
  142. std::vector<char> buf(1);
  143. int res = llama_chat_apply_template(nullptr, tmpl.c_str(), chat, 1, true, buf.data(), buf.size());
  144. return res >= 0;
  145. }
  146. // Format given chat. If tmpl is empty, we take the template from model metadata
  147. inline std::string format_chat(const struct llama_model * model, const std::string & tmpl, const std::vector<json> & messages)
  148. {
  149. size_t alloc_size = 0;
  150. // vector holding all allocated string to be passed to llama_chat_apply_template
  151. std::vector<std::string> str(messages.size() * 2);
  152. std::vector<llama_chat_message> chat(messages.size());
  153. for (size_t i = 0; i < messages.size(); ++i) {
  154. auto &curr_msg = messages[i];
  155. str[i*2 + 0] = json_value(curr_msg, "role", std::string(""));
  156. str[i*2 + 1] = json_value(curr_msg, "content", std::string(""));
  157. alloc_size += str[i*2 + 1].length();
  158. chat[i].role = str[i*2 + 0].c_str();
  159. chat[i].content = str[i*2 + 1].c_str();
  160. }
  161. const char * ptr_tmpl = tmpl.empty() ? nullptr : tmpl.c_str();
  162. std::vector<char> buf(alloc_size * 2);
  163. // run the first time to get the total output length
  164. int32_t res = llama_chat_apply_template(model, ptr_tmpl, chat.data(), chat.size(), true, buf.data(), buf.size());
  165. // if it turns out that our buffer is too small, we resize it
  166. if ((size_t) res > buf.size()) {
  167. buf.resize(res);
  168. res = llama_chat_apply_template(model, ptr_tmpl, chat.data(), chat.size(), true, buf.data(), buf.size());
  169. }
  170. std::string formatted_chat(buf.data(), res);
  171. LOG_VERBOSE("formatted_chat", {{"text", formatted_chat.c_str()}});
  172. return formatted_chat;
  173. }
  174. //
  175. // work queue utils
  176. //
  177. struct llama_server_queue {
  178. int id = 0;
  179. std::mutex mutex_tasks;
  180. bool running;
  181. // queues
  182. std::vector<task_server> queue_tasks;
  183. std::vector<task_server> queue_tasks_deferred;
  184. std::vector<task_multi> queue_multitasks;
  185. std::condition_variable condition_tasks;
  186. // callback functions
  187. std::function<void(task_server&)> callback_new_task;
  188. std::function<void(task_multi&)> callback_finish_multitask;
  189. std::function<void(void)> callback_all_task_finished;
  190. // Add a new task to the end of the queue
  191. int post(task_server task) {
  192. std::unique_lock<std::mutex> lock(mutex_tasks);
  193. if (task.id == -1) {
  194. task.id = id++;
  195. }
  196. queue_tasks.push_back(std::move(task));
  197. condition_tasks.notify_one();
  198. return task.id;
  199. }
  200. // Add a new task, but defer until one slot is available
  201. void defer(task_server task) {
  202. std::unique_lock<std::mutex> lock(mutex_tasks);
  203. queue_tasks_deferred.push_back(std::move(task));
  204. }
  205. // Get the next id for creating anew task
  206. int get_new_id() {
  207. std::unique_lock<std::mutex> lock(mutex_tasks);
  208. return id++;
  209. }
  210. // Register function to process a new task
  211. void on_new_task(std::function<void(task_server&)> callback) {
  212. callback_new_task = callback;
  213. }
  214. // Register function to process a multitask
  215. void on_finish_multitask(std::function<void(task_multi&)> callback) {
  216. callback_finish_multitask = callback;
  217. }
  218. // Register the function to be called when the batch of tasks is finished
  219. void on_all_tasks_finished(std::function<void(void)> callback) {
  220. callback_all_task_finished = callback;
  221. }
  222. // Call when the state of one slot is changed
  223. void notify_slot_changed() {
  224. // move deferred tasks back to main loop
  225. std::unique_lock<std::mutex> lock(mutex_tasks);
  226. for (auto & task : queue_tasks_deferred) {
  227. queue_tasks.push_back(std::move(task));
  228. }
  229. queue_tasks_deferred.clear();
  230. }
  231. // end the start_loop routine
  232. void terminate() {
  233. {
  234. std::unique_lock<std::mutex> lock(mutex_tasks);
  235. running = false;
  236. }
  237. condition_tasks.notify_all();
  238. }
  239. // Start the main loop.
  240. void start_loop() {
  241. running = true;
  242. while (true) {
  243. // new task arrived
  244. LOG_VERBOSE("have new task", {});
  245. {
  246. while (true)
  247. {
  248. std::unique_lock<std::mutex> lock(mutex_tasks);
  249. if (queue_tasks.empty()) {
  250. lock.unlock();
  251. break;
  252. }
  253. task_server task = queue_tasks.front();
  254. queue_tasks.erase(queue_tasks.begin());
  255. lock.unlock();
  256. LOG_VERBOSE("callback_new_task", {});
  257. callback_new_task(task);
  258. }
  259. LOG_VERBOSE("callback_all_task_finished", {});
  260. // process and update all the multitasks
  261. auto queue_iterator = queue_multitasks.begin();
  262. while (queue_iterator != queue_multitasks.end())
  263. {
  264. if (queue_iterator->subtasks_remaining.empty())
  265. {
  266. // all subtasks done == multitask is done
  267. task_multi current_multitask = *queue_iterator;
  268. callback_finish_multitask(current_multitask);
  269. // remove this multitask
  270. queue_iterator = queue_multitasks.erase(queue_iterator);
  271. }
  272. else
  273. {
  274. ++queue_iterator;
  275. }
  276. }
  277. // all tasks in the current loop is finished
  278. callback_all_task_finished();
  279. }
  280. LOG_VERBOSE("wait for new task", {});
  281. // wait for new task
  282. {
  283. std::unique_lock<std::mutex> lock(mutex_tasks);
  284. if (queue_tasks.empty()) {
  285. if (!running) {
  286. LOG_VERBOSE("ending start_loop", {});
  287. return;
  288. }
  289. condition_tasks.wait(lock, [&]{
  290. return (!queue_tasks.empty() || !running);
  291. });
  292. }
  293. }
  294. }
  295. }
  296. //
  297. // functions to manage multitasks
  298. //
  299. // add a multitask by specifying the id of all subtask (subtask is a task_server)
  300. void add_multitask(int multitask_id, std::vector<int>& sub_ids)
  301. {
  302. std::lock_guard<std::mutex> lock(mutex_tasks);
  303. task_multi multi;
  304. multi.id = multitask_id;
  305. std::copy(sub_ids.begin(), sub_ids.end(), std::inserter(multi.subtasks_remaining, multi.subtasks_remaining.end()));
  306. queue_multitasks.push_back(multi);
  307. }
  308. // updatethe remaining subtasks, while appending results to multitask
  309. void update_multitask(int multitask_id, int subtask_id, task_result& result)
  310. {
  311. std::lock_guard<std::mutex> lock(mutex_tasks);
  312. for (auto& multitask : queue_multitasks)
  313. {
  314. if (multitask.id == multitask_id)
  315. {
  316. multitask.subtasks_remaining.erase(subtask_id);
  317. multitask.results.push_back(result);
  318. }
  319. }
  320. }
  321. };
  322. struct llama_server_response {
  323. typedef std::function<void(int, int, task_result&)> callback_multitask_t;
  324. callback_multitask_t callback_update_multitask;
  325. // for keeping track of all tasks waiting for the result
  326. std::set<int> waiting_task_ids;
  327. // the main result queue
  328. std::vector<task_result> queue_results;
  329. std::mutex mutex_results;
  330. std::condition_variable condition_results;
  331. void add_waiting_task_id(int task_id) {
  332. std::unique_lock<std::mutex> lock(mutex_results);
  333. waiting_task_ids.insert(task_id);
  334. }
  335. void remove_waiting_task_id(int task_id) {
  336. std::unique_lock<std::mutex> lock(mutex_results);
  337. waiting_task_ids.erase(task_id);
  338. }
  339. // This function blocks the thread until there is a response for this task_id
  340. task_result recv(int task_id) {
  341. while (true)
  342. {
  343. std::unique_lock<std::mutex> lock(mutex_results);
  344. condition_results.wait(lock, [&]{
  345. return !queue_results.empty();
  346. });
  347. LOG_VERBOSE("condition_results unblock", {});
  348. for (int i = 0; i < (int) queue_results.size(); i++)
  349. {
  350. if (queue_results[i].id == task_id)
  351. {
  352. assert(queue_results[i].multitask_id == -1);
  353. task_result res = queue_results[i];
  354. queue_results.erase(queue_results.begin() + i);
  355. return res;
  356. }
  357. }
  358. }
  359. // should never reach here
  360. }
  361. // Register the function to update multitask
  362. void on_multitask_update(callback_multitask_t callback) {
  363. callback_update_multitask = callback;
  364. }
  365. // Send a new result to a waiting task_id
  366. void send(task_result result) {
  367. std::unique_lock<std::mutex> lock(mutex_results);
  368. LOG_VERBOSE("send new result", {});
  369. for (auto& task_id : waiting_task_ids) {
  370. // LOG_TEE("waiting task id %i \n", task_id);
  371. // for now, tasks that have associated parent multitasks just get erased once multitask picks up the result
  372. if (result.multitask_id == task_id)
  373. {
  374. LOG_VERBOSE("callback_update_multitask", {});
  375. callback_update_multitask(task_id, result.id, result);
  376. continue;
  377. }
  378. if (result.id == task_id)
  379. {
  380. LOG_VERBOSE("queue_results.push_back", {});
  381. queue_results.push_back(result);
  382. condition_results.notify_all();
  383. return;
  384. }
  385. }
  386. }
  387. };
  388. //
  389. // base64 utils (TODO: move to common in the future)
  390. //
  391. static const std::string base64_chars =
  392. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  393. "abcdefghijklmnopqrstuvwxyz"
  394. "0123456789+/";
  395. static inline bool is_base64(uint8_t c)
  396. {
  397. return (isalnum(c) || (c == '+') || (c == '/'));
  398. }
  399. static inline std::vector<uint8_t> base64_decode(const std::string & encoded_string)
  400. {
  401. int i = 0;
  402. int j = 0;
  403. int in_ = 0;
  404. int in_len = encoded_string.size();
  405. uint8_t char_array_4[4];
  406. uint8_t char_array_3[3];
  407. std::vector<uint8_t> ret;
  408. while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_]))
  409. {
  410. char_array_4[i++] = encoded_string[in_]; in_++;
  411. if (i == 4)
  412. {
  413. for (i = 0; i <4; i++)
  414. {
  415. char_array_4[i] = base64_chars.find(char_array_4[i]);
  416. }
  417. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  418. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  419. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  420. for (i = 0; (i < 3); i++)
  421. {
  422. ret.push_back(char_array_3[i]);
  423. }
  424. i = 0;
  425. }
  426. }
  427. if (i)
  428. {
  429. for (j = i; j <4; j++)
  430. {
  431. char_array_4[j] = 0;
  432. }
  433. for (j = 0; j <4; j++)
  434. {
  435. char_array_4[j] = base64_chars.find(char_array_4[j]);
  436. }
  437. char_array_3[0] = ((char_array_4[0] ) << 2) + ((char_array_4[1] & 0x30) >> 4);
  438. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  439. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  440. for (j = 0; (j < i - 1); j++)
  441. {
  442. ret.push_back(char_array_3[j]);
  443. }
  444. }
  445. return ret;
  446. }
  447. //
  448. // random string / id
  449. //
  450. static std::string random_string()
  451. {
  452. static const std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
  453. std::random_device rd;
  454. std::mt19937 generator(rd());
  455. std::string result(32, ' ');
  456. for (int i = 0; i < 32; ++i) {
  457. result[i] = str[generator() % str.size()];
  458. }
  459. return result;
  460. }
  461. static std::string gen_chatcmplid()
  462. {
  463. std::stringstream chatcmplid;
  464. chatcmplid << "chatcmpl-" << random_string();
  465. return chatcmplid.str();
  466. }